oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package egress
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "io"
8 "net"
9 "net/http"
10 "net/netip"
11 "os"
12 "path/filepath"
13 "strconv"
14 "strings"
15 "sync"
16 "sync/atomic"
17 "time"
18
19 "golang.org/x/sys/unix"
20)
21
22const (
23 MaxHeaders = 8 * 1024
24 MaxTunnels = 16
25 ConnectTimeout = 15 * time.Second
26 IdleTimeout = 60 * time.Second
27 NamespaceSocket = "/egress/proxy.sock"
28 RelayAddress = "127.0.0.1:18080"
29 ProxyURL = "http://127.0.0.1:18080"
30)
31
32type dependencies struct {
33 lookup func(context.Context, string) ([]netip.Addr, error)
34 dial func(context.Context, string, string) (net.Conn, error)
35 connect, idle time.Duration
36}
37
38func defaults() dependencies {
39 return dependencies{
40 lookup: func(ctx context.Context, host string) ([]netip.Addr, error) {
41 return net.DefaultResolver.LookupNetIP(ctx, "ip", host)
42 },
43 dial: (&net.Dialer{}).DialContext,
44 connect: ConnectTimeout, idle: IdleTimeout,
45 }
46}
47
48type Proxy struct {
49 denials atomic.Uint64
50 listener net.Listener
51 directory *os.File
52 path string
53 hosts map[string]bool
54 deps dependencies
55 ctx context.Context
56 cancel context.CancelFunc
57 done chan struct{}
58 once sync.Once
59 mu sync.Mutex
60 closed bool
61 clients map[net.Conn]struct{}
62 upstreams map[net.Conn]struct{}
63 wg sync.WaitGroup
64}
65
66// Open requires an existing private, symlink-free directory owned by the runner.
67// It creates no TCP listener. Each attempt must have a different directory.
68func Open(ctx context.Context, dir string, policy Policy) (*Proxy, error) {
69 return open(ctx, dir, policy, defaults())
70}
71func open(ctx context.Context, dir string, policy Policy, d dependencies) (*Proxy, error) {
72 if _, e := policy.Hash(); e != nil {
73 return nil, e
74 }
75 if e := ctx.Err(); e != nil {
76 return nil, e
77 }
78 if !filepath.IsAbs(dir) || filepath.Clean(dir) != dir {
79 return nil, errPolicy
80 }
81 fd, e := openDirNoLinks(dir)
82 if e != nil {
83 return nil, e
84 }
85 directory := os.NewFile(uintptr(fd), dir)
86 defer func() {
87 if directory != nil {
88 directory.Close()
89 }
90 }()
91 var st unix.Stat_t
92 if e = unix.Fstat(fd, &st); e != nil {
93 return nil, e
94 }
95 if st.Mode&0777 != 0700 || st.Uid != uint32(os.Geteuid()) {
96 return nil, errPolicy
97 }
98 path := filepath.Join(dir, "proxy.sock")
99 // Bind and chmod through the verified directory. Keep its descriptor until
100 // listener.Close unlinks the socket, even if the directory has been renamed.
101 bindPath := "/proc/self/fd/" + strconv.Itoa(fd) + "/proxy.sock"
102 ln, e := net.Listen("unix", bindPath)
103 if e != nil {
104 return nil, e
105 }
106 if e = os.Chmod(bindPath, 0600); e != nil {
107 ln.Close()
108 return nil, e
109 }
110 ctx, cancel := context.WithCancel(ctx)
111 p := &Proxy{listener: ln, directory: directory, path: path, hosts: map[string]bool{}, deps: d, ctx: ctx, cancel: cancel, done: make(chan struct{}), clients: map[net.Conn]struct{}{}, upstreams: map[net.Conn]struct{}{}}
112 directory = nil
113 for _, h := range policy.Hosts {
114 p.hosts[h] = true
115 }
116 p.wg.Add(1)
117 go p.serve()
118 go func() {
119 select {
120 case <-ctx.Done():
121 p.shutdown()
122 case <-p.done:
123 }
124 }()
125 return p, nil
126}
127func (p *Proxy) Denials() uint64 { return p.denials.Load() }
128
129func (p *Proxy) SocketPath() string { return p.path }
130
131// Done closes on endpoint loss, cancellation or Close. Owners stop the attempt.
132func (p *Proxy) Done() <-chan struct{} { return p.done }
133func (p *Proxy) shutdown() {
134 p.once.Do(func() {
135 p.mu.Lock()
136 p.closed = true
137 p.cancel()
138 p.listener.Close()
139 p.directory.Close()
140 for c := range p.clients {
141 c.Close()
142 }
143 for c := range p.upstreams {
144 c.Close()
145 }
146 p.mu.Unlock()
147 close(p.done)
148 })
149}
150func (p *Proxy) Close() error { p.shutdown(); p.wg.Wait(); return nil }
151func (p *Proxy) active() int { p.mu.Lock(); defer p.mu.Unlock(); return len(p.clients) }
152func (p *Proxy) serve() {
153 defer p.wg.Done()
154 defer p.shutdown()
155 for {
156 c, e := p.listener.Accept()
157 if e != nil {
158 return
159 }
160 p.mu.Lock()
161 if p.closed || len(p.clients) >= MaxTunnels {
162 p.mu.Unlock()
163 c.Close()
164 continue
165 }
166 p.clients[c] = struct{}{}
167 p.wg.Add(1)
168 p.mu.Unlock()
169 go func() {
170 defer p.wg.Done()
171 defer func() { c.Close(); p.mu.Lock(); delete(p.clients, c); p.mu.Unlock() }()
172 p.handle(c)
173 }()
174 }
175}
176
177// Read exactly one bounded CONNECT header. No HTTP request is forwarded to the
178// destination. Framing headers and queued requests are rejected before dialing.
179func authority(r *bufio.Reader) (string, error) {
180 data := make([]byte, 0, MaxHeaders)
181 for len(data) < MaxHeaders {
182 b, e := r.ReadByte()
183 if e != nil {
184 return "", e
185 }
186 data = append(data, b)
187 if bytes.HasSuffix(data, []byte("\r\n\r\n")) {
188 break
189 }
190 }
191 if !bytes.HasSuffix(data, []byte("\r\n\r\n")) || r.Buffered() != 0 {
192 return "", errPolicy
193 }
194 lines := strings.Split(string(data), "\r\n")
195 first := strings.Split(lines[0], " ")
196 if len(first) != 3 || first[0] != "CONNECT" || (first[2] != "HTTP/1.1" && first[2] != "HTTP/1.0") {
197 return "", errPolicy
198 }
199 host, port, e := net.SplitHostPort(first[1])
200 if e != nil || port != "443" || !hostname(host) {
201 return "", errPolicy
202 }
203 seen := map[string]bool{}
204 for _, line := range lines[1 : len(lines)-2] {
205 key, value, ok := strings.Cut(line, ":")
206 key = strings.ToLower(key)
207 if !ok || seen[key] {
208 return "", errPolicy
209 }
210 seen[key] = true
211 switch key {
212 case "host":
213 // The authority itself, or (Node's fetch) its host alone,
214 // which names the default port 443.
215 if v := strings.TrimSpace(value); v != first[1] && v != host {
216 return "", errPolicy
217 }
218 case "user-agent", "proxy-connection", "connection":
219 default:
220 return "", errPolicy
221 }
222 }
223 req, e := http.ReadRequest(bufio.NewReader(bytes.NewReader(data)))
224 if e != nil {
225 return "", errPolicy
226 }
227 req.Body.Close()
228 return host, nil
229}
230func (p *Proxy) handle(c net.Conn) {
231 c.SetDeadline(time.Now().Add(p.deps.connect))
232 r := bufio.NewReaderSize(c, MaxHeaders+1)
233 host, e := authority(r)
234 if e != nil || !p.hosts[host] {
235 p.denials.Add(1)
236 io.WriteString(c, "HTTP/1.1 403 Forbidden\r\n\r\n")
237 return
238 }
239 ctx, cancel := context.WithTimeout(p.ctx, p.deps.connect)
240 defer cancel()
241 if upstreamOverride != nil {
242 if to, ok := upstreamOverride(host); ok {
243 p.tunnelTo(ctx, c, to)
244 return
245 }
246 }
247 addresses, e := p.deps.lookup(ctx, host)
248 if e != nil || len(addresses) == 0 {
249 io.WriteString(c, "HTTP/1.1 502 Bad Gateway\r\n\r\n")
250 return
251 }
252 // Reject the whole answer if any address is unsafe. Never resolve again in Dial.
253 for _, a := range addresses {
254 if !publicAddress(a) {
255 p.denials.Add(1)
256 io.WriteString(c, "HTTP/1.1 403 Forbidden\r\n\r\n")
257 return
258 }
259 }
260 upstream, e := p.deps.dial(ctx, "tcp", net.JoinHostPort(addresses[0].Unmap().String(), "443"))
261 if e != nil {
262 io.WriteString(c, "HTTP/1.1 502 Bad Gateway\r\n\r\n")
263 return
264 }
265 defer upstream.Close()
266 p.mu.Lock()
267 if p.closed {
268 p.mu.Unlock()
269 return
270 }
271 p.upstreams[upstream] = struct{}{}
272 p.mu.Unlock()
273 defer func() { p.mu.Lock(); delete(p.upstreams, upstream); p.mu.Unlock() }()
274 if _, e = io.WriteString(c, "HTTP/1.1 200 Connection Established\r\n\r\n"); e != nil {
275 return
276 }
277 Tunnel(c, upstream, p.deps.idle)
278}
279
280// upstreamOverride is nil in every build but a test build
281// (proxy_testbuild.go), where it sends an allowed host's tunnels to a fake
282// provider on a loopback address instead of resolving the host.
283var upstreamOverride func(host string) (string, bool)
284
285// tunnelTo carries a test build's tunnel to a loopback upstream.
286func (p *Proxy) tunnelTo(ctx context.Context, c net.Conn, to string) {
287 upstream, e := p.deps.dial(ctx, "tcp", to)
288 if e != nil {
289 io.WriteString(c, "HTTP/1.1 502 Bad Gateway\r\n\r\n")
290 return
291 }
292 defer upstream.Close()
293 if _, e = io.WriteString(c, "HTTP/1.1 200 Connection Established\r\n\r\n"); e != nil {
294 return
295 }
296 Tunnel(c, upstream, p.deps.idle)
297}
298
299// Tunnel copies opaque TLS bytes. Traffic in either direction renews the idle
300// deadline for both sockets; closing either side releases both copying goroutines.
301func Tunnel(a, b net.Conn, idle time.Duration) {
302 touch := func() { deadline := time.Now().Add(idle); a.SetDeadline(deadline); b.SetDeadline(deadline) }
303 touch()
304 copyTo := func(dst, src net.Conn) {
305 buffer := make([]byte, 32*1024)
306 for {
307 n, e := src.Read(buffer)
308 if n > 0 {
309 touch()
310 if _, writeErr := dst.Write(buffer[:n]); writeErr != nil {
311 return
312 }
313 }
314 if e != nil {
315 return
316 }
317 }
318 }
319 done := make(chan struct{})
320 go func() { defer close(done); copyTo(a, b); a.Close(); b.Close() }()
321 copyTo(b, a)
322 a.Close()
323 b.Close()
324 <-done
325}
326