| 1 | package cage |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "crypto/ecdsa" |
| 7 | "crypto/elliptic" |
| 8 | "crypto/rand" |
| 9 | "crypto/tls" |
| 10 | "crypto/x509" |
| 11 | "encoding/binary" |
| 12 | "encoding/json" |
| 13 | "encoding/pem" |
| 14 | "errors" |
| 15 | "fmt" |
| 16 | "io" |
| 17 | "math/big" |
| 18 | "net" |
| 19 | "net/http" |
| 20 | "net/http/httptest" |
| 21 | "net/netip" |
| 22 | "os" |
| 23 | "os/exec" |
| 24 | "path/filepath" |
| 25 | "strings" |
| 26 | "sync/atomic" |
| 27 | "testing" |
| 28 | "time" |
| 29 | ) |
| 30 | |
| 31 | func TestExitProbeClassifiesProxyTimeout(t *testing.T) { |
| 32 | listener, err := net.Listen("tcp", "127.0.0.1:0") |
| 33 | if err != nil { |
| 34 | t.Fatal(err) |
| 35 | } |
| 36 | defer listener.Close() |
| 37 | var connections atomic.Int32 |
| 38 | go func() { |
| 39 | for { |
| 40 | conn, err := listener.Accept() |
| 41 | if err != nil { |
| 42 | return |
| 43 | } |
| 44 | connections.Add(1) |
| 45 | go func() { defer conn.Close(); _, _ = io.Copy(io.Discard, conn) }() |
| 46 | } |
| 47 | }() |
| 48 | cfg := DefaultConfig() |
| 49 | cfg.ProxyURL = "http://" + listener.Addr().String() |
| 50 | ctx, cancel := context.WithTimeout(context.Background(), 14*time.Second) |
| 51 | defer cancel() |
| 52 | ip, err := ProbeExitIP(ctx, cfg) |
| 53 | if ip != "" || !errors.Is(err, context.DeadlineExceeded) || connections.Load() != 2 { |
| 54 | t.Fatalf("two timed-out proxy probes = %q, %v, connections=%d", ip, err, connections.Load()) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | |
| 59 | |
| 60 | func TestExitProbeChild(t *testing.T) { |
| 61 | proxy := os.Getenv("CAGE_EXIT_PROBE_TEST_PROXY") |
| 62 | if proxy == "" { |
| 63 | t.Skip("subprocess fixture") |
| 64 | } |
| 65 | certificate, err := os.ReadFile(os.Getenv("CAGE_EXIT_PROBE_TEST_CA")) |
| 66 | if err != nil { |
| 67 | t.Fatal(err) |
| 68 | } |
| 69 | roots := x509.NewCertPool() |
| 70 | if !roots.AppendCertsFromPEM(certificate) { |
| 71 | t.Fatal("invalid test CA") |
| 72 | } |
| 73 | x509.SetFallbackRoots(roots) |
| 74 | cfg := DefaultConfig() |
| 75 | cfg.ProxyURL = proxy |
| 76 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 77 | defer cancel() |
| 78 | want := os.Getenv("CAGE_EXIT_PROBE_TEST_IP") |
| 79 | ip, err := ProbeExitIP(ctx, cfg) |
| 80 | if want != "" { |
| 81 | if err != nil || ip != want { |
| 82 | t.Fatalf("host probe = %q, %v; want %q", ip, err, want) |
| 83 | } |
| 84 | } else if err == nil || ip != "" || strings.Contains(err.Error(), "private-value") || strings.Contains(err.Error(), "test-password") { |
| 85 | t.Fatalf("failed host probe returned an address or leaked a response: %q, %v", ip, err) |
| 86 | } |
| 87 | gate, err := NewEgressGate(cfg) |
| 88 | if err != nil { |
| 89 | t.Fatal(err) |
| 90 | } |
| 91 | defer gate.Close("test complete") |
| 92 | if err := gate.BeginCheck(); err != nil { |
| 93 | t.Fatal(err) |
| 94 | } |
| 95 | connection, err := gate.DialContext(ctx, "tcp", DiagnosticAddress) |
| 96 | if err != nil { |
| 97 | t.Fatal(err) |
| 98 | } |
| 99 | defer connection.Close() |
| 100 | _ = connection.SetDeadline(time.Now().Add(5 * time.Second)) |
| 101 | _, err = io.WriteString(connection, "GET /egress HTTP/1.1\r\nHost: 198.18.0.254\r\nCookie: private-value\r\nAuthorization: private-value\r\n\r\n") |
| 102 | if err != nil { |
| 103 | t.Fatal(err) |
| 104 | } |
| 105 | response, err := http.ReadResponse(bufio.NewReader(connection), nil) |
| 106 | if err != nil { |
| 107 | t.Fatal(err) |
| 108 | } |
| 109 | defer response.Body.Close() |
| 110 | var result struct{ IP, Error string } |
| 111 | if err := json.NewDecoder(response.Body).Decode(&result); err != nil { |
| 112 | t.Fatal(err) |
| 113 | } |
| 114 | if want != "" { |
| 115 | if response.StatusCode != 200 || result.IP != want { |
| 116 | t.Fatalf("guest diagnostic lost IPv4 JSON contract: %d %+v", response.StatusCode, result) |
| 117 | } |
| 118 | } else if response.StatusCode != 503 || result.IP != "" || result.Error != "proxy_unavailable" { |
| 119 | t.Fatalf("failed guest diagnostic did not retain its fixed error contract: %d %+v", response.StatusCode, result) |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | func TestExitProbeUsesIPv4ServiceThroughProxy(t *testing.T) { |
| 124 | key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 125 | if err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | template := &x509.Certificate{SerialNumber: big.NewInt(1), DNSNames: []string{"ipv4.icanhazip.com", "api.ipify.org"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| 129 | certificate, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) |
| 130 | if err != nil { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | caFile := filepath.Join(t.TempDir(), "ca.pem") |
| 134 | if err := os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certificate}), 0600); err != nil { |
| 135 | t.Fatal(err) |
| 136 | } |
| 137 | for _, scheme := range []string{"http", "socks5"} { |
| 138 | for _, tc := range []struct { |
| 139 | name, body, want string |
| 140 | status int |
| 141 | }{ |
| 142 | {"public-ipv4", "8.8.8.8\n", "8.8.8.8", 200}, |
| 143 | {"fallback-after-unavailable", "8.8.8.8\n", "8.8.8.8", 503}, |
| 144 | {"fallback-after-invalid", "8.8.8.8\n", "8.8.8.8", 200}, |
| 145 | {"whitespace", " \r\n1.1.1.1\r\n", "1.1.1.1", 200}, |
| 146 | {"ipv6", "2606:4700:4700::1111\n", "", 200}, |
| 147 | {"mapped-ipv4", "::ffff:8.8.8.8", "", 200}, |
| 148 | {"private-ipv4", "192.168.1.1", "", 200}, |
| 149 | {"loopback", "127.0.0.1", "", 200}, |
| 150 | {"link-local", "169.254.1.1", "", 200}, |
| 151 | {"multicast", "224.0.0.1", "", 200}, |
| 152 | {"empty", "", "", 200}, |
| 153 | {"json-response", `{"ip":"8.8.8.8","secret":"private-value"}`, "", 200}, |
| 154 | {"multiple-addresses", "8.8.8.8\n1.1.1.1", "", 200}, |
| 155 | {"oversized", "8.8.8.8" + strings.Repeat(" ", 4096), "", 200}, |
| 156 | {"short-read", "8.8.8.8", "", 200}, |
| 157 | {"unavailable", "private-value", "", 503}, |
| 158 | {"redirect", "private-value", "", 302}, |
| 159 | } { |
| 160 | t.Run(scheme+"/"+tc.name, func(t *testing.T) { |
| 161 | var requests atomic.Int32 |
| 162 | upstream := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { |
| 163 | requests.Add(1) |
| 164 | if (request.Host != "ipv4.icanhazip.com" && request.Host != "api.ipify.org") || request.URL.RequestURI() != "/" || request.Method != "GET" || request.Header.Get("User-Agent") != "Cage-network-check/1" || request.Header.Get("Cookie") != "" || request.Header.Get("Authorization") != "" || request.Header.Get("Proxy-Authorization") != "" { |
| 165 | t.Error("probe request changed destination or forwarded guest/proxy data") |
| 166 | } |
| 167 | if request.Host == "api.ipify.org" { |
| 168 | if strings.HasPrefix(tc.name, "fallback-") { |
| 169 | _, _ = io.WriteString(w, tc.body) |
| 170 | return |
| 171 | } |
| 172 | _, _ = io.WriteString(w, `{"ip":"2606:4700:4700::1111"}`) |
| 173 | return |
| 174 | } |
| 175 | if tc.name == "fallback-after-invalid" { |
| 176 | _, _ = io.WriteString(w, "192.168.1.1") |
| 177 | return |
| 178 | } |
| 179 | w.Header().Set("Content-Type", "text/plain") |
| 180 | if tc.name == "redirect" { |
| 181 | w.Header().Set("Location", "https://private-value.invalid/") |
| 182 | } |
| 183 | if tc.name == "short-read" { |
| 184 | w.Header().Set("Content-Length", "50") |
| 185 | } |
| 186 | w.WriteHeader(tc.status) |
| 187 | _, _ = io.WriteString(w, tc.body) |
| 188 | })) |
| 189 | upstream.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{certificate}, PrivateKey: key}}} |
| 190 | upstream.StartTLS() |
| 191 | defer upstream.Close() |
| 192 | proxy, connects := exitProbeProxy(t, scheme, upstream.Listener.Addr().String()) |
| 193 | command := exec.Command(os.Args[0], "-test.run=^TestExitProbeChild$", "-test.timeout=15s") |
| 194 | command.Env = append(os.Environ(), "GODEBUG=x509usefallbackroots=1", "CAGE_EXIT_PROBE_TEST_PROXY="+proxy, "CAGE_EXIT_PROBE_TEST_CA="+caFile, "CAGE_EXIT_PROBE_TEST_IP="+tc.want) |
| 195 | if output, err := command.CombinedOutput(); err != nil { |
| 196 | t.Fatalf("real probe entry failed: %v\n%s", err, output) |
| 197 | } |
| 198 | wantRequests := int32(2) |
| 199 | if tc.want == "" || strings.HasPrefix(tc.name, "fallback-") { |
| 200 | wantRequests = 4 |
| 201 | } |
| 202 | if connects.Load() != wantRequests || requests.Load() != wantRequests { |
| 203 | t.Fatalf("host and guest probes must use only the configured proxy: connects=%d requests=%d", connects.Load(), requests.Load()) |
| 204 | } |
| 205 | }) |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | func TestExitProbeProxyRejectionDoesNotFallbackOrLeakResponse(t *testing.T) { |
| 211 | var requests atomic.Int32 |
| 212 | proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) { |
| 213 | requests.Add(1) |
| 214 | w.WriteHeader(http.StatusBadGateway) |
| 215 | _, _ = io.WriteString(w, "private-proxy-response") |
| 216 | })) |
| 217 | defer proxy.Close() |
| 218 | cfg := DefaultConfig() |
| 219 | cfg.ProxyURL = proxy.URL |
| 220 | ip, err := ProbeExitIP(context.Background(), cfg) |
| 221 | if err == nil || ip != "" || requests.Load() != 2 || strings.Contains(err.Error(), "private-proxy-response") { |
| 222 | t.Fatalf("proxy rejection escaped the configured route or leaked its response: IP=%q error=%v requests=%d", ip, err, requests.Load()) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | func TestExitProbePublicIPv4Service(t *testing.T) { |
| 227 | if os.Getenv("CAGE_EXIT_PROBE_LIVE") != "1" { |
| 228 | t.Skip("requires the public IPv4 service through an isolated local proxy") |
| 229 | } |
| 230 | for _, scheme := range []string{"http", "socks5"} { |
| 231 | t.Run(scheme, func(t *testing.T) { |
| 232 | proxy, requests := exitProbeProxy(t, scheme, "ipv4.icanhazip.com:443") |
| 233 | cfg := DefaultConfig() |
| 234 | cfg.ProxyURL = proxy |
| 235 | ip, err := ProbeExitIP(context.Background(), cfg) |
| 236 | if err != nil { |
| 237 | t.Fatal(err) |
| 238 | } |
| 239 | address, err := netip.ParseAddr(ip) |
| 240 | if err != nil || !address.Is4() || !address.IsGlobalUnicast() || address.IsPrivate() || requests.Load() != 1 { |
| 241 | t.Fatal("public service did not return IPv4 through the selected proxy") |
| 242 | } |
| 243 | t.Log("public endpoint returned a public IPv4 through the isolated proxy") |
| 244 | }) |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | |
| 249 | |
| 250 | func exitProbeProxy(t *testing.T, scheme, upstream string) (string, *atomic.Int32) { |
| 251 | t.Helper() |
| 252 | listener, err := net.Listen("tcp", "127.0.0.1:0") |
| 253 | if err != nil { |
| 254 | t.Fatal(err) |
| 255 | } |
| 256 | count := new(atomic.Int32) |
| 257 | t.Cleanup(func() { _ = listener.Close() }) |
| 258 | go func() { |
| 259 | for { |
| 260 | connection, err := listener.Accept() |
| 261 | if err != nil { |
| 262 | return |
| 263 | } |
| 264 | go func() { |
| 265 | defer connection.Close() |
| 266 | _ = connection.SetDeadline(time.Now().Add(10 * time.Second)) |
| 267 | reader := bufio.NewReader(connection) |
| 268 | var target string |
| 269 | if scheme == "http" { |
| 270 | request, err := http.ReadRequest(reader) |
| 271 | if err != nil || request.Method != "CONNECT" { |
| 272 | t.Error("expected HTTP CONNECT") |
| 273 | return |
| 274 | } |
| 275 | if request.Header.Get("Proxy-Authorization") != "Basic dGVzdC11c2VyOnRlc3QtcGFzc3dvcmQ=" { |
| 276 | t.Error("HTTP proxy authentication was lost") |
| 277 | return |
| 278 | } |
| 279 | target = request.Host |
| 280 | _, _ = io.WriteString(connection, "HTTP/1.1 200 Connection Established\r\n\r\n") |
| 281 | } else { |
| 282 | var header [4]byte |
| 283 | if _, err := io.ReadFull(reader, header[:2]); err != nil { |
| 284 | return |
| 285 | } |
| 286 | if _, err := io.CopyN(io.Discard, reader, int64(header[1])); err != nil { |
| 287 | return |
| 288 | } |
| 289 | _, _ = connection.Write([]byte{5, 2}) |
| 290 | if _, err := io.ReadFull(reader, header[:2]); err != nil { |
| 291 | return |
| 292 | } |
| 293 | username := make([]byte, int(header[1])) |
| 294 | if _, err := io.ReadFull(reader, username); err != nil { |
| 295 | return |
| 296 | } |
| 297 | passwordLength, err := reader.ReadByte() |
| 298 | if err != nil { |
| 299 | return |
| 300 | } |
| 301 | password := make([]byte, int(passwordLength)) |
| 302 | if _, err := io.ReadFull(reader, password); err != nil { |
| 303 | return |
| 304 | } |
| 305 | if string(username) != "test-user" || string(password) != "test-password" { |
| 306 | t.Error("SOCKS proxy authentication was lost") |
| 307 | return |
| 308 | } |
| 309 | _, _ = connection.Write([]byte{1, 0}) |
| 310 | if _, err := io.ReadFull(reader, header[:]); err != nil { |
| 311 | return |
| 312 | } |
| 313 | if header[0] != 5 || header[1] != 1 || header[3] != 3 { |
| 314 | t.Error("SOCKS probe resolved its hostname outside the proxy") |
| 315 | return |
| 316 | } |
| 317 | length, err := reader.ReadByte() |
| 318 | if err != nil { |
| 319 | return |
| 320 | } |
| 321 | host := make([]byte, length) |
| 322 | if _, err := io.ReadFull(reader, host); err != nil { |
| 323 | return |
| 324 | } |
| 325 | if _, err := io.ReadFull(reader, header[:2]); err != nil { |
| 326 | return |
| 327 | } |
| 328 | target = net.JoinHostPort(string(host), fmt.Sprint(binary.BigEndian.Uint16(header[:2]))) |
| 329 | _, _ = connection.Write([]byte{5, 0, 0, 1, 127, 0, 0, 1, 0, 80}) |
| 330 | } |
| 331 | if target != "ipv4.icanhazip.com:443" && target != "api.ipify.org:443" { |
| 332 | t.Error("probe followed a redirect or changed destination") |
| 333 | return |
| 334 | } |
| 335 | count.Add(1) |
| 336 | remote, err := net.DialTimeout("tcp", upstream, time.Second) |
| 337 | if err != nil { |
| 338 | t.Error(err) |
| 339 | return |
| 340 | } |
| 341 | defer remote.Close() |
| 342 | go func() { _, _ = io.Copy(remote, reader); _ = remote.Close() }() |
| 343 | _, _ = io.Copy(connection, remote) |
| 344 | }() |
| 345 | } |
| 346 | }() |
| 347 | return scheme + "://test-user:test-password@" + listener.Addr().String(), count |
| 348 | } |