| 1 | package cage |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "crypto/tls" |
| 8 | "encoding/base64" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "net" |
| 13 | "net/http" |
| 14 | "net/netip" |
| 15 | "net/url" |
| 16 | "strings" |
| 17 | "time" |
| 18 | |
| 19 | "github.com/miekg/dns" |
| 20 | "github.com/sylvinus/agent-vm/internal/netguard" |
| 21 | "github.com/sylvinus/agent-vm/internal/usererror" |
| 22 | "golang.org/x/net/proxy" |
| 23 | ) |
| 24 | |
| 25 | |
| 26 | |
| 27 | type Egress struct { |
| 28 | upstream *url.URL |
| 29 | dnsURL string |
| 30 | client *http.Client |
| 31 | public netguard.Policy |
| 32 | connect proxyConnector |
| 33 | } |
| 34 | |
| 35 | type proxyConnector interface { |
| 36 | Dial(string, string) (net.Conn, error) |
| 37 | DialContext(context.Context, string, string) (net.Conn, error) |
| 38 | } |
| 39 | |
| 40 | func NewEgress(c Config) (*Egress, error) { |
| 41 | if err := c.Validate(); err != nil { |
| 42 | return nil, err |
| 43 | } |
| 44 | u, _ := url.Parse(c.ProxyURL) |
| 45 | e := &Egress{upstream: u, dnsURL: c.DNSURL, connect: &net.Dialer{Timeout: 20 * time.Second, KeepAlive: 30 * time.Second}} |
| 46 | e.client = &http.Client{Timeout: 20 * time.Second, Transport: &http.Transport{Proxy: nil, DialContext: e.DialContext, ForceAttemptHTTP2: true}, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("DNS redirect refused") }} |
| 47 | return e, nil |
| 48 | } |
| 49 | |
| 50 | func (e *Egress) Allows(network string, dst netip.AddrPort) bool { |
| 51 | |
| 52 | return network == "tcp" && dst.Addr().Unmap().Is4() && e.public.Allows(network, dst) |
| 53 | } |
| 54 | |
| 55 | type bufferedConn struct { |
| 56 | net.Conn |
| 57 | reader *bufio.Reader |
| 58 | } |
| 59 | |
| 60 | func (c *bufferedConn) Read(p []byte) (int, error) { return c.reader.Read(p) } |
| 61 | |
| 62 | func proxyConnectionError(ctx context.Context, action string, err error) error { |
| 63 | |
| 64 | |
| 65 | if ctx.Err() != nil { |
| 66 | err = ctx.Err() |
| 67 | } else if deadline, ok := ctx.Deadline(); ok && !time.Now().Before(deadline) { |
| 68 | |
| 69 | var timeout net.Error |
| 70 | if errors.As(err, &timeout) && timeout.Timeout() { |
| 71 | err = errors.Join(context.DeadlineExceeded, err) |
| 72 | } |
| 73 | } |
| 74 | return usererror.Wrap(action, err, "请检查代理;请求不会改为直连。") |
| 75 | } |
| 76 | |
| 77 | |
| 78 | |
| 79 | func (e *Egress) DialContext(ctx context.Context, network, addr string) (net.Conn, error) { |
| 80 | if network != "tcp" && network != "tcp4" && network != "tcp6" { |
| 81 | return nil, errors.New("cage permits TCP only") |
| 82 | } |
| 83 | ctx, cancel := context.WithTimeout(ctx, 20*time.Second) |
| 84 | defer cancel() |
| 85 | if strings.HasPrefix(e.upstream.Scheme, "socks5") { |
| 86 | var auth *proxy.Auth |
| 87 | if e.upstream.User != nil { |
| 88 | p, _ := e.upstream.User.Password() |
| 89 | auth = &proxy.Auth{User: e.upstream.User.Username(), Password: p} |
| 90 | } |
| 91 | d, err := proxy.SOCKS5("tcp", e.upstream.Host, auth, e.connect) |
| 92 | if err != nil { |
| 93 | return nil, errors.New("invalid SOCKS5 configuration") |
| 94 | } |
| 95 | c, err := d.(proxy.ContextDialer).DialContext(ctx, "tcp", addr) |
| 96 | if err != nil { |
| 97 | return nil, proxyConnectionError(ctx, "连接指定 SOCKS5 代理", err) |
| 98 | } |
| 99 | return c, nil |
| 100 | } |
| 101 | conn, err := e.connect.DialContext(ctx, "tcp", e.upstream.Host) |
| 102 | if err != nil { |
| 103 | return nil, proxyConnectionError(ctx, "连接指定代理", err) |
| 104 | } |
| 105 | |
| 106 | |
| 107 | upstreamConn := conn |
| 108 | stopCancel := context.AfterFunc(ctx, func() { _ = upstreamConn.Close() }) |
| 109 | defer stopCancel() |
| 110 | ok := false |
| 111 | defer func() { |
| 112 | if !ok { |
| 113 | conn.Close() |
| 114 | } |
| 115 | }() |
| 116 | if deadline, yes := ctx.Deadline(); yes { |
| 117 | conn.SetDeadline(deadline) |
| 118 | } |
| 119 | if e.upstream.Scheme == "https" { |
| 120 | t := tls.Client(conn, &tls.Config{ServerName: e.upstream.Hostname(), MinVersion: tls.VersionTLS12}) |
| 121 | if err = t.HandshakeContext(ctx); err != nil { |
| 122 | return nil, proxyConnectionError(ctx, "验证 HTTPS 代理的加密连接", err) |
| 123 | } |
| 124 | conn = t |
| 125 | } |
| 126 | req := &http.Request{Method: http.MethodConnect, URL: &url.URL{Opaque: addr}, Host: addr, Header: make(http.Header)} |
| 127 | if e.upstream.User != nil { |
| 128 | p, _ := e.upstream.User.Password() |
| 129 | req.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(e.upstream.User.Username()+":"+p))) |
| 130 | } |
| 131 | if err = req.Write(conn); err != nil { |
| 132 | return nil, proxyConnectionError(ctx, "发送代理 CONNECT 请求", err) |
| 133 | } |
| 134 | r := bufio.NewReader(conn) |
| 135 | resp, err := http.ReadResponse(r, req) |
| 136 | if err != nil { |
| 137 | return nil, proxyConnectionError(ctx, "读取代理 CONNECT 响应", err) |
| 138 | } |
| 139 | if resp.StatusCode != http.StatusOK { |
| 140 | return nil, fmt.Errorf("代理拒绝 CONNECT 请求(HTTP %d);请求不会改为直连", resp.StatusCode) |
| 141 | } |
| 142 | conn.SetDeadline(time.Time{}) |
| 143 | ok = true |
| 144 | return &bufferedConn{Conn: conn, reader: r}, nil |
| 145 | } |
| 146 | |
| 147 | |
| 148 | |
| 149 | func (e *Egress) ExchangeDNS(ctx context.Context, q *dns.Msg) (*dns.Msg, error) { |
| 150 | for _, question := range q.Question { |
| 151 | |
| 152 | |
| 153 | if question.Qtype == dns.TypeAAAA { |
| 154 | r := new(dns.Msg) |
| 155 | r.SetReply(q) |
| 156 | return r, nil |
| 157 | } |
| 158 | n := strings.ToLower(strings.TrimSuffix(question.Name, ".")) |
| 159 | if n == "localhost" || strings.HasSuffix(n, ".localhost") || strings.HasSuffix(n, ".internal") || strings.HasSuffix(n, ".local") { |
| 160 | r := new(dns.Msg) |
| 161 | r.SetRcode(q, dns.RcodeNameError) |
| 162 | return r, nil |
| 163 | } |
| 164 | } |
| 165 | wire, err := q.Pack() |
| 166 | if err != nil { |
| 167 | return nil, err |
| 168 | } |
| 169 | |
| 170 | |
| 171 | |
| 172 | ctx, cancel := context.WithTimeout(ctx, 20*time.Second) |
| 173 | defer cancel() |
| 174 | for attempt := 0; attempt < 3; attempt++ { |
| 175 | if ctx.Err() != nil { |
| 176 | return nil, ctx.Err() |
| 177 | } |
| 178 | attemptCtx, done := context.WithTimeout(ctx, 6*time.Second) |
| 179 | var answer *dns.Msg |
| 180 | var retry bool |
| 181 | answer, retry, err = e.exchangeDNSOnce(attemptCtx, q, wire) |
| 182 | done() |
| 183 | if err == nil || !retry { |
| 184 | return answer, err |
| 185 | } |
| 186 | if attempt < 2 { |
| 187 | select { |
| 188 | case <-ctx.Done(): |
| 189 | return nil, ctx.Err() |
| 190 | case <-time.After(time.Duration(attempt+1) * 150 * time.Millisecond): |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | return nil, err |
| 195 | } |
| 196 | |
| 197 | func (e *Egress) exchangeDNSOnce(ctx context.Context, q *dns.Msg, wire []byte) (*dns.Msg, bool, error) { |
| 198 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, e.dnsURL, bytes.NewReader(wire)) |
| 199 | if err != nil { |
| 200 | return nil, false, errors.New("invalid DNS request") |
| 201 | } |
| 202 | req.Header.Set("Content-Type", "application/dns-message") |
| 203 | req.Header.Set("Accept", "application/dns-message") |
| 204 | resp, err := e.client.Do(req) |
| 205 | if err != nil { |
| 206 | return nil, true, errors.New("cage DNS upstream unavailable; check the configured DoH endpoint through the selected proxy") |
| 207 | } |
| 208 | defer resp.Body.Close() |
| 209 | if resp.StatusCode != 200 { |
| 210 | return nil, resp.StatusCode == 429 || resp.StatusCode >= 500, fmt.Errorf("cage DNS upstream returned HTTP %d", resp.StatusCode) |
| 211 | } |
| 212 | body, err := io.ReadAll(io.LimitReader(resp.Body, 65536)) |
| 213 | if err != nil { |
| 214 | return nil, true, errors.New("incomplete DNS upstream response") |
| 215 | } |
| 216 | r := new(dns.Msg) |
| 217 | if err = r.Unpack(body); err != nil { |
| 218 | return nil, false, errors.New("invalid DNS upstream response") |
| 219 | } |
| 220 | if !r.Response || r.Id != q.Id { |
| 221 | return nil, false, errors.New("mismatched DNS upstream response") |
| 222 | } |
| 223 | return r, false, nil |
| 224 | } |