跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

netguard.go

272 行 · 8.1 KB历史下载
1// Package netguard decides what a VM may reach on the network: the internet,
2// never this machine, its local networks or the other VMs (through this
3// machine's loopback, where their ports are forwarded), unless the user
4// allows it in ~/.agent-vm/network. It runs in the hostagent, where every
5// connection the guest opens is made (Lima's per-instance netstack).
6package netguard
7
8import (
9 "bufio"
10 "errors"
11 "fmt"
12 "net"
13 "net/netip"
14 "os"
15 "strconv"
16 "strings"
17 "sync"
18 "time"
19)
20
21// FileName is the policy's file in agent-vm's state folder.
22const FileName = "network"
23
24// resolvedFor is how long an address answered for an allowed domain stays
25// reachable: a connection pool may reuse it well after the lookup.
26const resolvedFor = 30 * time.Minute
27
28// Policy is what the VMs may reach. The zero Policy is the default: the
29// internet only.
30type Policy struct {
31 // Open turns isolation off (AGENT_VM_UNSAFE_OPEN_NETWORK=1).
32 Open bool
33 // Allow are reachable whatever else: an address or network, every port
34 // when Port is 0.
35 Allow []Rule
36 // Domains, when any, are the only names of the internet the VMs may
37 // reach, subdomains included: an address is reachable once agent-vm's
38 // DNS gave it for one of them.
39 Domains []string
40
41 mu sync.Mutex
42 resolved map[netip.Addr]time.Time
43 own []netip.Prefix
44 ownAt time.Time
45}
46
47// Rule is an allow line: a network, and a port or 0 for every one.
48type Rule struct {
49 Net netip.Prefix
50 Port uint16
51}
52
53// Load reads the policy from the state folder's network file (none: the
54// default), and AGENT_VM_UNSAFE_OPEN_NETWORK.
55func Load(stateDir string) (*Policy, error) {
56 p := &Policy{Open: os.Getenv("AGENT_VM_UNSAFE_OPEN_NETWORK") == "1"}
57 f, err := os.Open(stateDir + "/" + FileName)
58 if errors.Is(err, os.ErrNotExist) {
59 return p, nil
60 }
61 if err != nil {
62 return nil, err
63 }
64 defer f.Close()
65 sc := bufio.NewScanner(f)
66 for n := 1; sc.Scan(); n++ {
67 line, _, _ := strings.Cut(sc.Text(), "#")
68 fields := strings.Fields(line)
69 if len(fields) == 0 {
70 continue
71 }
72 if len(fields) != 2 {
73 return nil, fmt.Errorf("%s/%s, line %d: want 'allow <address>' or 'domain <name>'", stateDir, FileName, n)
74 }
75 switch fields[0] {
76 case "allow":
77 rules, err := parseAllow(fields[1])
78 if err != nil {
79 return nil, fmt.Errorf("%s/%s, line %d: %v", stateDir, FileName, n, err)
80 }
81 p.Allow = append(p.Allow, rules...)
82 case "domain":
83 d := strings.ToLower(strings.TrimSuffix(strings.TrimPrefix(fields[1], "*."), "."))
84 if d == "" || strings.ContainsAny(d, "/:*") {
85 return nil, fmt.Errorf("%s/%s, line %d: %q is not a domain name", stateDir, FileName, n, fields[1])
86 }
87 p.Domains = append(p.Domains, d)
88 default:
89 return nil, fmt.Errorf("%s/%s, line %d: unknown %q (allow, domain)", stateDir, FileName, n, fields[0])
90 }
91 }
92 return p, sc.Err()
93}
94
95// parseAllow reads 10.0.0.5, 10.0.0.5:8080, [::1]:8080, 192.168.1.0/24,
96// localhost:11434 (127.0.0.1 and ::1).
97func parseAllow(s string) ([]Rule, error) {
98 if pf, err := netip.ParsePrefix(s); err == nil {
99 return []Rule{{Net: pf.Masked()}}, nil
100 }
101 host, port := s, uint16(0)
102 if h, p, err := net.SplitHostPort(s); err == nil {
103 n, err := strconv.ParseUint(p, 10, 16)
104 if err != nil || n == 0 {
105 return nil, fmt.Errorf("bad port in %q", s)
106 }
107 host, port = h, uint16(n)
108 }
109 if host == "localhost" {
110 return []Rule{
111 {Net: netip.PrefixFrom(netip.MustParseAddr("127.0.0.1"), 32), Port: port},
112 {Net: netip.PrefixFrom(netip.IPv6Loopback(), 128), Port: port},
113 }, nil
114 }
115 a, err := netip.ParseAddr(host)
116 if err != nil {
117 return nil, fmt.Errorf("%q is not an address, an address:port or a network", s)
118 }
119 a = a.Unmap()
120 return []Rule{{Net: netip.PrefixFrom(a, a.BitLen()), Port: port}}, nil
121}
122
123// reserved are the ranges the standard library does not call private, that
124// never lead to the internet: carrier-grade NAT (VPNs like Tailscale), IETF
125// protocol assignments, documentation, benchmarking (proxies use it for fake
126// addresses), and the reserved class E with the broadcast address.
127var reserved = []netip.Prefix{
128 netip.MustParsePrefix("0.0.0.0/8"),
129 netip.MustParsePrefix("100.64.0.0/10"),
130 netip.MustParsePrefix("192.0.0.0/24"),
131 netip.MustParsePrefix("192.0.2.0/24"),
132 netip.MustParsePrefix("198.18.0.0/15"),
133 netip.MustParsePrefix("198.51.100.0/24"),
134 netip.MustParsePrefix("203.0.113.0/24"),
135 netip.MustParsePrefix("240.0.0.0/4"),
136 netip.MustParsePrefix("::/96"), // IPv4-compatible, deprecated
137 netip.MustParsePrefix("100::/64"), // discard
138 netip.MustParsePrefix("2001:db8::/32"), // documentation
139 netip.MustParsePrefix("fec0::/10"), // site-local, deprecated
140 netip.MustParsePrefix("64:ff9b:1::/48"), // local-use NAT64
141}
142
143var (
144 nat64 = netip.MustParsePrefix("64:ff9b::/96")
145 sixToFour = netip.MustParsePrefix("2002::/16")
146 teredo = netip.MustParsePrefix("2001::/32")
147)
148
149// internal reports whether a is of this machine or its local networks, or
150// not routed: an IPv6 address that embeds such an IPv4 one (NAT64, 6to4,
151// Teredo) is too, as a router of the host's network may translate it.
152func internal(a netip.Addr) bool {
153 a = a.Unmap().WithZone("")
154 if a.IsLoopback() || a.IsPrivate() || a.IsLinkLocalUnicast() || a.IsLinkLocalMulticast() ||
155 a.IsInterfaceLocalMulticast() || a.IsMulticast() || a.IsUnspecified() {
156 return true
157 }
158 for _, r := range reserved {
159 if r.Contains(a) {
160 return true
161 }
162 }
163 b := a.As16()
164 switch {
165 case a.Is4():
166 return false
167 case nat64.Contains(a):
168 return internal(netip.AddrFrom4([4]byte(b[12:])))
169 case sixToFour.Contains(a):
170 return internal(netip.AddrFrom4([4]byte(b[2:6])))
171 case teredo.Contains(a):
172 // The server's address, and the client's with its bits flipped.
173 client := [4]byte{^b[12], ^b[13], ^b[14], ^b[15]}
174 return internal(netip.AddrFrom4([4]byte(b[4:8]))) || internal(netip.AddrFrom4(client))
175 }
176 return false
177}
178
179// Allows reports whether the guest may reach dst over network ("tcp" or
180// "udp": nothing else is allowed).
181func (p *Policy) Allows(network string, dst netip.AddrPort) bool {
182 if p.Open {
183 return true
184 }
185 if network != "tcp" && network != "udp" {
186 return false
187 }
188 a := dst.Addr().Unmap().WithZone("")
189 for _, r := range p.Allow {
190 if r.Net.Contains(a) && (r.Port == 0 || r.Port == dst.Port()) {
191 return true
192 }
193 }
194 if internal(a) || p.ownAddress(a) {
195 return false
196 }
197 if len(p.Domains) == 0 {
198 return true
199 }
200 p.mu.Lock()
201 defer p.mu.Unlock()
202 until, ok := p.resolved[a]
203 return ok && time.Now().Before(until)
204}
205
206// ownAddress reports whether a is an address of this machine (a public one
207// included): what listens on all its interfaces is reached there. Read again
208// every few seconds, as interfaces come and go.
209func (p *Policy) ownAddress(a netip.Addr) bool {
210 p.mu.Lock()
211 defer p.mu.Unlock()
212 if time.Since(p.ownAt) > 5*time.Second {
213 p.own = p.own[:0]
214 if addrs, err := net.InterfaceAddrs(); err == nil {
215 for _, ad := range addrs {
216 if n, ok := ad.(*net.IPNet); ok {
217 if ip, ok := netip.AddrFromSlice(n.IP); ok {
218 p.own = append(p.own, netip.PrefixFrom(ip.Unmap(), ip.Unmap().BitLen()))
219 }
220 }
221 }
222 }
223 p.ownAt = time.Now()
224 }
225 for _, o := range p.own {
226 if o.Contains(a) {
227 return true
228 }
229 }
230 return false
231}
232
233// Name reports whether the guest may resolve name: with Domains, those and
234// their subdomains only. That includes host.lima.internal and the VM's own
235// name, which then get NXDOMAIN from the resolver.
236func (p *Policy) Name(name string) bool {
237 if p.Open || len(p.Domains) == 0 {
238 return true
239 }
240 name = strings.ToLower(strings.TrimSuffix(name, "."))
241 for _, d := range p.Domains {
242 if name == d || strings.HasSuffix(name, "."+d) {
243 return true
244 }
245 }
246 return false
247}
248
249// Answered records the addresses given for an allowed name: reachable for
250// resolvedFor.
251func (p *Policy) Answered(name string, ips []net.IP) {
252 if !p.Name(name) {
253 return
254 }
255 p.mu.Lock()
256 defer p.mu.Unlock()
257 if p.resolved == nil {
258 p.resolved = map[netip.Addr]time.Time{}
259 }
260 now := time.Now()
261 for a, until := range p.resolved {
262 if !now.Before(until) {
263 delete(p.resolved, a)
264 }
265 }
266 until := now.Add(resolvedFor)
267 for _, ip := range ips {
268 if a, ok := netip.AddrFromSlice(ip); ok {
269 p.resolved[a.Unmap()] = until
270 }
271 }
272}