Repository navigation
Expand file tree
/
Copy pathredirect_route_vpnservice_android.go
More file actions
240 lines (229 loc) · 8 KB
/
Copy pathredirect_route_vpnservice_android.go
File metadata and controls
240 lines (229 loc) · 8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package tun
import (
"errors"
"os"
"slices"
"strconv"
"strings"
"github.com/sagernet/netlink"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
"golang.org/x/sys/unix"
)
func (r *autoRedirect) androidVPNServiceRulePriority() int {
if r.tunOptions.IPRoute2RuleIndex != 0 {
return r.tunOptions.IPRoute2RuleIndex
}
return DefaultIPRoute2RuleIndex
}
type androidVPNServiceTables struct {
physical []int
localNetwork int
}
// netd adds one default network rule per interface of the default network
// (with 464xlat: the base interface and the clat interface, only the latter
// holding the IPv4 default route), so every table is kept in dump order and
// the kernel falls through on a lookup miss. netd reaches the local network
// table through the rule matching the VPN as the incoming interface; the
// explicit select mask instead matches the legacy system and legacy network
// tables first, which stay empty.
func discoverAndroidVPNServiceTables(ruleList []netlink.Rule, tunInterfaceName string) androidVPNServiceTables {
var tables androidVPNServiceTables
for _, rule := range ruleList {
if rule.Table > 0 && rule.UIDRange == nil && rule.Mark == 0 && rule.Mask == androidNetIDMask && !slices.Contains(tables.physical, rule.Table) {
tables.physical = append(tables.physical, rule.Table)
}
if rule.Table > 0 && rule.Mark == 0 && rule.UIDRange == nil && rule.IifName == tunInterfaceName && rule.OifName == "" && tables.localNetwork == 0 {
tables.localNetwork = rule.Table
}
}
return tables
}
func (r *autoRedirect) discoverAndroidVPNServiceRules() ([]*netlink.Rule, error) {
priority := r.androidVPNServiceRulePriority()
mask := int(r.effectiveMarkMask())
tunLink, err := netlink.LinkByName(r.tunOptions.Name)
if err != nil {
return nil, E.Cause(err, "find tun interface")
}
vpnTable := tunLink.Attrs().Index + androidRouteTableOffsetFromIndex
var (
rules []*netlink.Rule
ruleList []netlink.Rule
)
for _, family := range []int{unix.AF_INET, unix.AF_INET6} {
familyName := "ipv4"
if family == unix.AF_INET6 {
if !r.enableIPv6 {
continue
}
familyName = "ipv6"
} else if !r.enableIPv4 {
continue
}
ruleList, err = netlink.RuleList(family)
if err != nil {
return nil, E.Cause(err, "list ", familyName, " rules")
}
tables := discoverAndroidVPNServiceTables(ruleList, r.tunOptions.Name)
physicalTables := tables.physical
localNetworkTable := tables.localNetwork
r.logger.Debug(familyName, " vpn service rules: vpn table ", vpnTable, ", default network tables ", strings.Join(common.Map(physicalTables, strconv.Itoa), " "), ", local network table ", localNetworkTable)
inputRule := netlink.NewRule()
inputRule.Priority = priority
inputRule.Family = family
inputRule.Mark = r.tunOptions.AutoRedirectInputMark
inputRule.MarkSet = true
inputRule.Mask = mask
inputRule.Table = vpnTable
rules = append(rules, inputRule)
// A reset generated by the REJECT chain keeps the reset mark of the
// packet that triggered it and has to reach the client on the served
// network instead of the netd VPN rule that catches unmarked flows.
if localNetworkTable > 0 {
resetRule := netlink.NewRule()
resetRule.Priority = priority
resetRule.Family = family
resetRule.Mark = r.tunOptions.AutoRedirectResetMark
resetRule.MarkSet = true
resetRule.Mask = mask
resetRule.Table = localNetworkTable
rules = append(rules, resetRule)
}
// Bypassed local flows carry the tun address as their source and
// Android ships no ip6tables nat table to rewrite it.
if family == unix.AF_INET6 {
continue
}
if localNetworkTable > 0 {
localOutputRule := netlink.NewRule()
localOutputRule.Priority = priority
localOutputRule.Family = family
localOutputRule.Mark = r.tunOptions.AutoRedirectOutputMark
localOutputRule.MarkSet = true
localOutputRule.Mask = mask
localOutputRule.IifName = "lo"
localOutputRule.Table = localNetworkTable
rules = append(rules, localOutputRule)
}
for _, physicalTable := range physicalTables {
outputRule := netlink.NewRule()
outputRule.Priority = priority
outputRule.Family = family
outputRule.Mark = r.tunOptions.AutoRedirectOutputMark
outputRule.MarkSet = true
outputRule.Mask = mask
outputRule.IifName = "lo"
outputRule.Table = physicalTable
rules = append(rules, outputRule)
}
}
return rules, nil
}
func androidVPNServiceRuleEquals(left *netlink.Rule, right *netlink.Rule) bool {
return left.Family == right.Family &&
left.Priority == right.Priority &&
left.Mark == right.Mark &&
left.Mask == right.Mask &&
left.IifName == right.IifName &&
left.Table == right.Table
}
func (r *autoRedirect) setupAndroidVPNServiceRules() error {
r.androidVPNServiceRuleAccess.Lock()
defer r.androidVPNServiceRuleAccess.Unlock()
priority := r.androidVPNServiceRulePriority()
inputMark := r.tunOptions.AutoRedirectInputMark
outputMark := r.tunOptions.AutoRedirectOutputMark
resetMark := r.tunOptions.AutoRedirectResetMark
for _, family := range []int{unix.AF_INET, unix.AF_INET6} {
staleRules, err := netlink.RuleListFiltered(family, &netlink.Rule{Priority: priority}, netlink.RT_FILTER_PRIORITY)
if err != nil {
continue
}
for _, staleRule := range staleRules {
if staleRule.Mark != inputMark && staleRule.Mark != outputMark && staleRule.Mark != resetMark {
continue
}
deleteRule := netlink.NewRule()
deleteRule.Family = family
deleteRule.Priority = priority
deleteRule.Mark = staleRule.Mark
deleteRule.MarkSet = true
deleteRule.Mask = staleRule.Mask
_ = netlink.RuleDel(deleteRule)
}
}
rules, err := r.discoverAndroidVPNServiceRules()
if err != nil {
return err
}
r.androidVPNServiceRulesActive = true
for _, rule := range rules {
err = netlink.RuleAdd(rule)
if err != nil && !E.IsMulti(err, unix.EEXIST, os.ErrExist) {
return E.Cause(err, "add rule ", rule)
}
r.androidVPNServiceRules = append(r.androidVPNServiceRules, rule)
}
return r.removeAndroidIngressDiscardRulesLocked()
}
func (r *autoRedirect) updateAndroidVPNServiceRules() error {
r.androidVPNServiceRuleAccess.Lock()
defer r.androidVPNServiceRuleAccess.Unlock()
if !r.androidVPNServiceRulesActive {
return nil
}
rules, err := r.discoverAndroidVPNServiceRules()
if err != nil {
var linkNotFound netlink.LinkNotFoundError
if errors.As(err, &linkNotFound) {
return nil
}
return err
}
currentRules, err := netlink.RuleListFiltered(netlink.FAMILY_ALL, &netlink.Rule{Priority: r.androidVPNServiceRulePriority()}, netlink.RT_FILTER_PRIORITY)
if err != nil {
return E.Cause(err, "list current vpn service rules")
}
var errorList []error
var installedRules []*netlink.Rule
for _, installedRule := range r.androidVPNServiceRules {
if slices.ContainsFunc(rules, func(it *netlink.Rule) bool {
return androidVPNServiceRuleEquals(it, installedRule)
}) {
continue
}
deleteErr := netlink.RuleDel(installedRule)
if deleteErr != nil && !E.IsMulti(deleteErr, unix.ENOENT, os.ErrNotExist) {
errorList = append(errorList, E.Cause(deleteErr, "delete rule ", installedRule))
installedRules = append(installedRules, installedRule)
}
}
for _, rule := range rules {
if slices.ContainsFunc(currentRules, func(it netlink.Rule) bool {
return androidVPNServiceRuleEquals(&it, rule)
}) {
installedRules = append(installedRules, rule)
continue
}
addErr := netlink.RuleAdd(rule)
if addErr != nil && !E.IsMulti(addErr, unix.EEXIST, os.ErrExist) {
errorList = append(errorList, E.Cause(addErr, "add rule ", rule))
continue
}
installedRules = append(installedRules, rule)
}
r.androidVPNServiceRules = installedRules
errorList = append(errorList, r.removeAndroidIngressDiscardRulesLocked())
return E.Errors(errorList...)
}
func (r *autoRedirect) cleanupAndroidVPNServiceRules() {
r.androidVPNServiceRuleAccess.Lock()
defer r.androidVPNServiceRuleAccess.Unlock()
r.androidVPNServiceRulesActive = false
r.restoreAndroidIngressDiscardRulesLocked()
for _, rule := range r.androidVPNServiceRules {
_ = netlink.RuleDel(rule)
}
r.androidVPNServiceRules = nil
}