### Setting up a MITM Proxy with Slinger-Mitm (Rust) Source: https://github.com/emo-crab/slinger/blob/main/crates/slinger/README.md Illustrates how to set up and start a Man-in-the-Middle (MITM) proxy using the slinger-mitm crate in Rust. This example configures the proxy, adds a logging interceptor, and starts the proxy on a specified address. It requires 'slinger-mitm' and 'tokio' crates. ```rust use slinger_mitm::{MitmConfig, MitmProxy, Interceptor}; use std::sync::Arc; #[tokio::main] async fn main() -> Result<(), Box> { let config = MitmConfig::default(); let proxy = MitmProxy::new(config).await?; // Add logging interceptor let handler = proxy.interceptor_handler(); let mut h = handler.write().await; h.add_request_interceptor(Arc::new(Interceptor::logging())); drop(h); proxy.start("127.0.0.1:8080").await?; Ok(()) } ``` -------------------------------- ### Run Slinger MITM Proxy Example Source: https://github.com/emo-crab/slinger/blob/main/crates/slinger-mitm/README.md Command-line instructions to run example configurations of the Slinger MITM proxy using Cargo. This includes a basic logging proxy and a proxy with upstream support. ```bash cargo run --example simple_proxy cargo run --example proxy_chain ``` -------------------------------- ### Basic Proxy Setup with Logging Interceptors (Rust) Source: https://github.com/emo-crab/slinger/blob/main/crates/slinger-mitm/README.md This snippet demonstrates how to set up a basic MITM proxy using Slinger MITM. It configures default settings, adds logging interceptors for both requests and responses, and starts the proxy on a specified address. It requires the `slinger-mitm` and `tokio` crates. ```rust use slinger_mitm::{MitmConfig, MitmProxy, Interceptor}; use std::sync::Arc; #[tokio::main] async fn main() -> Result<(), Box> { // Create proxy with default configuration let config = MitmConfig::default(); let proxy = MitmProxy::new(config).await?; // Add logging interceptor let interceptor_handler = proxy.interceptor_handler(); let mut handler = interceptor_handler.write().await; handler.add_request_interceptor(Arc::new(Interceptor::logging())); handler.add_response_interceptor(Arc::new(Interceptor::logging())); drop(handler); // Start the proxy proxy.start("127.0.0.1:8080").await?; Ok(()) } ``` -------------------------------- ### Slinger Rust: Simple GET Request Source: https://context7.com/emo-crab/slinger/llms.txt Demonstrates a basic GET request using the `get` shortcut function in Slinger. This function internally creates a client, sends the request, and returns the response. It's suitable for single, straightforward HTTP requests. ```rust use slinger; #[tokio::main] async fn main() -> Result<(), Box> { // Simple GET request let resp = slinger::get("https://httpbin.org/get").await?; // Access response data println!("Status: {}", resp.status_code()); println!("Headers: {:?}", resp.headers()); println!("Body: {}", resp.text()?); Ok(()) } ``` -------------------------------- ### Basic HTTP GET Request with Slinger (Rust) Source: https://github.com/emo-crab/slinger/blob/main/crates/slinger/README.md Demonstrates a simple GET request using the Slinger HTTP client library in Rust. It shows how to make a request and print the response text. Requires the 'tokio' runtime and 'slinger' crate with optional features like 'serde', 'cookie', 'charset', 'tls', 'rustls', and 'gzip' enabled in Cargo.toml. ```rust #[tokio::main] async fn main() -> Result<(), Box> { let resp = slinger::get("https://httpbin.org/get").await?; println!("{:?}", resp.text()); Ok(()) } ``` -------------------------------- ### Basic MITM Proxy Setup in Rust Source: https://context7.com/emo-crab/slinger/llms.txt Sets up a basic Man-in-the-Middle proxy server using Slinger. It logs all HTTP/HTTPS traffic and prints the CA certificate path for browser configuration. Dependencies include the `slinger-mitm` and `tokio` crates. ```rust use slinger_mitm::{MitmConfig, MitmProxy, InterceptorFactory}; use std::sync::Arc; #[tokio::main] async fn main() -> Result<(), Box> { // Create proxy with default configuration let config = MitmConfig::default(); let proxy = MitmProxy::new(config).await?; // Add logging interceptor to see traffic let interceptor_handler = proxy.interceptor_handler(); let mut handler = interceptor_handler.write().await; handler.add_interceptor(Arc::new(InterceptorFactory::logging())); drop(handler); // Release write lock // Print CA certificate path for browser installation println!("CA certificate: {}", proxy.ca_cert_path().display()); println!("Starting MITM proxy on 127.0.0.1:8080"); // Start the proxy (blocks until shutdown) proxy.start("127.0.0.1:8080").await?; Ok(()) } ``` -------------------------------- ### Slinger Cargo.toml Dependencies for HTTP Client (TOML) Source: https://github.com/emo-crab/slinger/blob/main/crates/slinger/README.md Example Cargo.toml configuration for the Slinger HTTP client, enabling several optional features. This includes support for serialization/deserialization, cookie handling, character encoding, TLS with Rustls, and gzip compression. ```toml [dependencies] slinger = { version = "0.2.9", features = ["serde", "cookie", "charset", "tls", "rustls", "gzip"] } ``` -------------------------------- ### Slinger Cargo.toml Dependencies Source: https://context7.com/emo-crab/slinger/llms.txt These TOML snippets show how to add the slinger crate as a dependency in your Cargo.toml file. It includes examples for basic HTTP client usage, enabling common features like TLS, HTTP/2, and cookie support, and a minimal TLS setup. ```toml [dependencies] # Basic HTTP client slinger = "0.2.12" ``` ```toml # With all common features slinger = { version = "0.2.12", features = [ "tls", # Base TLS support "rustls", # Rustls TLS backend (recommended) "http2", # HTTP/2 protocol support "cookie", # Cookie jar support "charset", # Character encoding support "serde", # Serialization support "gzip", # Gzip decompression "dns", # Custom DNS resolver ]} ``` ```toml # Minimal TLS setup slinger = { version = "0.2.12", features = ["tls", "rustls"] } ``` -------------------------------- ### Enable HTTP/2 Support in Rust Source: https://context7.com/emo-crab/slinger/llms.txt Enables HTTP/2 protocol support for connections that negotiate it via ALPN, requiring the `http2` and `tls` features. The example demonstrates how to build a client with HTTP/2 enabled and then make a request, checking the response status, HTTP version, and body length. ```rust use slinger::ClientBuilder; #[tokio::main] async fn main() -> Result<(), Box> { // Enable HTTP/2 support let client = ClientBuilder::default() .enable_http2(true) .build()?; let resp = client.get("https://httpbin.org/").send().await?; println!("Status: {}", resp.status_code()); println!("HTTP Version: {:?}", resp.version()); // HTTP/2 if negotiated let body_len = resp.body().as_ref().map(|b| b.len()).unwrap_or(0); println!("Body length: {} bytes", body_len); Ok(()) } ``` -------------------------------- ### Configure Custom DNS Resolution in Rust Source: https://context7.com/emo-crab/slinger/llms.txt Allows specifying custom DNS servers for hostname resolution, requiring the `dns` feature. The example shows how to create a `DnsResolver` with custom servers (e.g., Google's public DNS) and then build a `Client` that utilizes this resolver for all its network requests. ```rust use slinger::Client; use slinger::dns::DnsResolver; #[tokio::main] async fn main() -> Result<(), Box> { // Create DNS resolver with Google's public DNS servers let resolver = DnsResolver::new(vec![ "8.8.8.8:53".parse()?, "8.8.4.4:53".parse()?, ])?; // Create client with custom DNS resolver let client = Client::builder() .dns_resolver(resolver) .build()?; // Requests will use the custom DNS servers let resp = client.get("http://httpbin.org/get").send().await?; println!("Status: {}", resp.status_code()); println!("Body: {}", resp.text()?); Ok(()) } ``` -------------------------------- ### HTTP Smuggling Example (CVE-2020-11724) in Rust Source: https://github.com/emo-crab/slinger/blob/main/crates/slinger/README.md This Rust code snippet demonstrates an HTTP smuggling attack, specifically targeting CVE-2020-11724. It requires the 'slinger' crate and 'tokio' for asynchronous operations. The input is a raw byte string representing a crafted HTTP request designed to exploit discrepancies in how front-end and back-end servers process requests. The output is a vector of HTTPRecord structures parsed from the response. ```rust use std::io::BufRead; use slinger::{ClientBuilder, HTTPRecord}; /// CVE-2020-11724 /// when you're using BurpSuite proxy need **disabled** "set **Connection** header on incoming request" const RAW: &[u8] = b"GET /test1 HTTP/1.1 Host: 192.168.83.196:8081 Content-Length: 42 Transfer-Encoding: chunked 0 GET /test1 HTTP/1.1 Host: 192.168.83.196:8081 X: GET http://192.168.83.1:8080/admin.jsp HTTP/1.0 "; #[tokio::main] async fn main() -> Result<(), Box> { // let proxy = slinger::Proxy::parse("http://127.0.0.1:8080").unwrap(); let client = ClientBuilder::default().build().unwrap(); let mut raw = Vec::new(); // replace \n to \r\n for line in RAW.lines() { match line { Ok(l) => { raw.extend(l.as_bytes()); raw.extend(b"\r\n") } Err(err) => { println!("{:?}", err); } } } let resp = client.raw("http://127.0.0.1:9015/", raw, true).send().await?; let record = resp.extensions().get::>().unwrap(); println!("{:?}", record); Ok(()) } ``` -------------------------------- ### Configure MITM Proxy with Upstream Proxy Chain (Rust) Source: https://context7.com/emo-crab/slinger/llms.txt This Rust code snippet demonstrates how to configure and start a MITM proxy using the slinger-mitm crate. It shows how to set up an upstream proxy (e.g., SOCKS5h for Tor) and add logging interceptors. The proxy listens on port 8080 and forwards traffic through the specified upstream proxy. ```rust use slinger_mitm::{MitmConfig, MitmProxy, InterceptorFactory}; use std::sync::Arc; #[tokio::main] async fn main() -> Result<(), Box> { // Configure upstream proxy (SOCKS5h for Tor with remote DNS) let upstream_proxy = slinger::Proxy::parse("socks5h://127.0.0.1:9050")?; let config = MitmConfig { ca_storage_path: std::path::PathBuf::from(".slinger-mitm"), enable_https_interception: true, enable_tcp_interception: false, max_connections: 1000, connection_timeout: 30, upstream_proxy: Some(upstream_proxy), }; let proxy = MitmProxy::new(config).await?; // Add logging let interceptor_handler = proxy.interceptor_handler(); let mut handler = interceptor_handler.write().await; handler.add_interceptor(Arc::new(InterceptorFactory::logging())); drop(handler); println!("Proxy chain: Browser -> MITM (8080) -> Tor (9050) -> Internet"); println!("CA certificate: {}", proxy.ca_cert_path().display()); proxy.start("127.0.0.1:8080").await?; Ok(()) } ``` -------------------------------- ### Send Raw HTTP Requests for Smuggling in Rust Source: https://context7.com/emo-crab/slinger/llms.txt Enables sending raw, non-RFC-compliant HTTP requests to test vulnerabilities like HTTP request smuggling. This bypasses normal request parsing. The example demonstrates constructing a smuggling payload, formatting it correctly, sending it using `unsafe_raw=true`, and accessing request/response details. ```rust use slinger::ClientBuilder; #[tokio::main] async fn main() -> Result<(), Box> { let client = ClientBuilder::default().build()?; // HTTP request smuggling payload (CVE-2020-11724) let smuggling_payload = r#"GET /test1 HTTP/1.1 Host: target.example.com Content-Length: 42 Transfer-Encoding: chunked 0 GET /admin HTTP/1.1 Host: target.example.com X: "#; // Replace \n with \r\n for proper HTTP formatting let raw = smuggling_payload.replace('\n', "\r\n"); // Send raw request (unsafe_raw=true bypasses parsing) let resp = client .raw("http://target.example.com/", raw, true) .send() .await?; println!("Response: {:?}", resp.text()); // Get the curl/ncat command equivalent for the request if let Some(request) = resp.request() { println!("Command: {}", request.get_command()); } // Access HTTP records for full request/response chain if let Some(records) = resp.http_record() { for record in records { println!("Request: {:?}", record.request); println!("Response: {:?}", record.response); } } Ok(()) } ``` -------------------------------- ### Configure TLS Settings in Rust Source: https://context7.com/emo-crab/slinger/llms.txt Demonstrates how to configure TLS settings for a client, including certificate verification, custom CA certificates, and TLS version constraints. Requires the `tls` and `rustls` features. It shows how to build a basic TLS client, handle peer certificates, accept invalid certificates (for testing), set minimum TLS versions, add custom root certificates, and disable TLS SNI. ```rust use slinger::{ClientBuilder, tls}; #[tokio::main] async fn main() -> Result<(), Box> { // Basic TLS client let client = ClientBuilder::default().build()?; let resp = client.get("https://httpbin.org/get").send().await?; // Access peer certificate information if let Some(certs) = resp.certificate() { println!("Server certificates: {:?}", certs); } // Accept invalid certificates (DANGEROUS - for testing only) let insecure_client = ClientBuilder::default() .danger_accept_invalid_certs(true) .danger_accept_invalid_hostnames(true) .build()?; let resp = insecure_client.get("https://self-signed.badssl.com/").send().await?; println!("Self-signed cert response: {}", resp.status_code()); // Set minimum TLS version let client = ClientBuilder::default() .min_tls_version(Some(tls::Version::TLS_1_2)) .build()?; // Add custom root certificate let der_cert = std::fs::read("my-ca.der")?; let cert = tls::Certificate::from_der(&der_cert)?; let client = ClientBuilder::default() .add_root_certificate(cert) .build()?; // Disable TLS SNI (Server Name Indication) let client = ClientBuilder::default() .tls_sni(false) .build()?; Ok(()) } ``` -------------------------------- ### Slinger Rust: Reusable Client with Customization Source: https://context7.com/emo-crab/slinger/llms.txt Shows how to create and configure a reusable `Client` instance using `ClientBuilder` for multiple HTTP requests. This approach leverages connection pooling and allows for detailed customization of client behavior, such as setting user agents, timeouts, and TCP options. ```rust use slinger::{Client, ClientBuilder}; use http::HeaderValue; use std::time::Duration; #[tokio::main] async fn main() -> Result<(), Box> { // Build a configured client let client = ClientBuilder::default() .user_agent(HeaderValue::from_static( "Mozilla/5.0 (X11; Linux x86_64; rv:123.0) Gecko/20100101 Firefox/123.0" )) .timeout(Some(Duration::from_secs(30))) .connect_timeout(Some(Duration::from_secs(10))) .tcp_nodelay(true) .keepalive(true) .build()?; // Reuse client for multiple requests let resp1 = client.get("https://httpbin.org/get").send().await?; println!("GET Response: {:?}", resp1.text()); let resp2 = client.get("https://httpbin.org/headers").send().await?; println!("Headers Response: {:?}", resp2.text()); Ok(()) } ``` -------------------------------- ### Configure HTTP, HTTPS, and SOCKS5 Proxies in Rust Source: https://context7.com/emo-crab/slinger/llms.txt Demonstrates how to configure HTTP, HTTPS, and SOCKS5 proxies for routing traffic through intermediary servers using the Slinger client. Supports SOCKS5h for remote DNS resolution and proxy authentication. ```rust use slinger::{ClientBuilder, Proxy}; #[tokio::main] async fn main() -> Result<(), Box> { // HTTP proxy let http_proxy = Proxy::parse("http://127.0.0.1:8080")?; let client = ClientBuilder::default() .proxy(http_proxy) .build()?; let resp = client.get("https://httpbin.org/get").send().await?; println!("Via HTTP proxy: {:?}", resp.text()); // SOCKS5 proxy (local DNS resolution) let socks5_proxy = Proxy::parse("socks5://127.0.0.1:1080")?; let client = ClientBuilder::default() .proxy(socks5_proxy) .build()?; let resp = client.get("https://httpbin.org/get").send().await?; println!("Via SOCKS5 proxy: {:?}", resp.text()); // SOCKS5h proxy with remote DNS resolution (useful for Tor) let socks5h_proxy = Proxy::parse("socks5h://127.0.0.1:9050")?; let client = ClientBuilder::default() .proxy(socks5h_proxy) .build()?; let resp = client.get("https://httpbin.org/get").send().await?; println!("Via SOCKS5h proxy: {:?}", resp.text()); // Proxy with authentication let auth_proxy = Proxy::parse("socks5://user:password@127.0.0.1:1080")?; let client = ClientBuilder::default() .proxy(auth_proxy) .build()?; Ok(()) } ``` -------------------------------- ### Slinger Rust: Building Custom HTTP Requests Source: https://context7.com/emo-crab/slinger/llms.txt Details how to construct and send custom HTTP requests using the `Request::builder`. This method allows for specifying the HTTP method, headers, URI, and request body, providing granular control over the request details before execution. ```rust use slinger::{Client, ClientBuilder, Request}; #[tokio::main] async fn main() -> Result<(), Box> { let client = ClientBuilder::default().build()?; // Build a custom HEAD request let req = Request::builder() .uri("http://httpbin.org/head") .method("HEAD") .header("pragma", "akamai-x-cache-on") .header("X-Custom-Header", "custom-value") .body(None)?; let resp = client.execute(req).await?; println!("Status: {}", resp.status_code()); println!("Headers: {:?}", resp.headers()); // Access the original request from response if let Some(original_req) = resp.request() { println!("Request method: {:?}", original_req.method()); } Ok(()) } ``` -------------------------------- ### Slinger TLS Feature Combinations (TOML) Source: https://github.com/emo-crab/slinger/blob/main/crates/slinger/README.md Demonstrates different ways to configure TLS support for the Slinger HTTP client in Cargo.toml. It shows how to enable the base 'tls' feature along with the 'rustls' backend or how to prepare for a custom TLS backend implementation. ```toml # Using rustls backend slinger = { version = "0.2.8", features = ["tls", "rustls"] } # Using custom TLS backend (requires implementing CustomTlsConnector) slinger = { version = "0.2.8", features = ["tls"] } ``` -------------------------------- ### Slinger-Mitm Cargo.toml Dependencies (TOML) Source: https://github.com/emo-crab/slinger/blob/main/crates/slinger/README.md Specifies the necessary dependencies in Cargo.toml for using the slinger-mitm crate, including the 'slinger-mitm' library itself and the 'tokio' runtime with its 'full' features enabled. ```toml [dependencies] slinger-mitm = { version = "0.2.9" } tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### Slinger-MITM Cargo.toml Dependencies Source: https://context7.com/emo-crab/slinger/llms.txt This TOML snippet illustrates the necessary dependencies to include the slinger-mitm crate in your project's Cargo.toml file. It specifies slinger-mitm itself, the tokio runtime with full features, and the async-trait crate required for custom interceptors. ```toml [dependencies] slinger-mitm = "0.0.3" tokio = { version = "1", features = ["full"] } async-trait = "0.1" # Required for custom interceptors ``` -------------------------------- ### Slinger Rust: POST Requests with Different Bodies Source: https://context7.com/emo-crab/slinger/llms.txt Illustrates how to perform POST requests with various types of request bodies, including strings, byte vectors, and JSON payloads with custom content types. This demonstrates the flexibility of Slinger in handling different data formats for POST requests. ```rust use slinger::{Client, ClientBuilder}; #[tokio::main] async fn main() -> Result<(), Box> { let client = ClientBuilder::default().build()?; // POST with string body let resp = client .post("http://httpbin.org/post") .body("the exact body that is sent") .send() .await?; println!("String body response: {:?}", resp.text()); // POST with byte vector body let resp = client .post("http://httpbin.org/post") .body(b"binary data here".to_vec()) .send() .await?; println!("Binary body response: {:?}", resp.text()); // POST with custom headers let resp = client .post("http://httpbin.org/post") .header("Content-Type", "application/json") .body(r#"{"key": "value"}"#) .send() .await?; println!("JSON body response: {:?}", resp.text()); Ok(()) } ``` -------------------------------- ### Cargo.toml Dependencies for Slinger MITM Source: https://github.com/emo-crab/slinger/blob/main/crates/slinger-mitm/README.md This TOML snippet lists the necessary dependencies to use the `slinger-mitm` library in a Rust project. It includes `slinger-mitm` itself and `tokio` for asynchronous operations, specifying the path for the local `slinger-mitm` crate. ```toml [dependencies] slinger-mitm = { path = "../slinger-mitm" } tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### Configure Slinger MITM Proxy Source: https://github.com/emo-crab/slinger/blob/main/crates/slinger-mitm/README.md Sets up the `MitmConfig` for the Slinger MITM proxy. Key parameters include the CA storage path, HTTPS interception enablement, maximum connections, connection timeout, and an optional upstream proxy. ```rust use slinger_mitm::MitmConfig; use std::path::PathBuf; let config = MitmConfig { // Directory to store CA certificates ca_storage_path: PathBuf::from(".slinger-mitm"), // Enable HTTPS interception (requires CA cert installation) enable_https_interception: true, // Maximum concurrent connections max_connections: 1000, // Connection timeout in seconds connection_timeout: 30, // Optional upstream proxy (supports HTTP, HTTPS, SOCKS5, SOCKS5h) // Example: Some(slinger::Proxy::parse("socks5h://127.0.0.1:1080")?) upstream_proxy: None, }; ``` -------------------------------- ### Configure HTTP Redirect Policies in Rust Source: https://context7.com/emo-crab/slinger/llms.txt Shows how to configure the Slinger client's behavior when encountering HTTP redirects. This includes limiting the number of redirects, disabling redirects, following only redirects to the same host, and implementing custom redirect logic. ```rust use slinger::{ClientBuilder, redirect}; use slinger::record::HTTPRecord; #[tokio::main] async fn main() -> Result<(), Box> { // Limit redirects to 3 hops let limited_policy = redirect::Policy::Limit(3); let client = ClientBuilder::default() .redirect(limited_policy) .build()?; let resp = client.get("http://httpbin.org/redirect/10").send().await?; let record = resp.extensions().get::>().unwrap(); println!("Followed {} redirects (limited to 3)", record.len()); // Disable redirects entirely let no_redirect = redirect::Policy::None; let client = ClientBuilder::default() .redirect(no_redirect) .build()?; // Only follow redirects to same host let same_host_policy = redirect::Policy::Custom(redirect::only_same_host); let client = ClientBuilder::default() .redirect(same_host_policy) .build()?; let resp = client .get("http://httpbin.org/redirect-to?url=http://www.example.com/") .send() .await?; // Check redirect info if let Some(redirect_record) = resp.redirect_record() { println!("Should redirect: {}", redirect_record.should_redirect); println!("Next URL: {:?}", redirect_record.next); } // Custom redirect policy let custom_policy = redirect::Policy::custom(|attempt| { if attempt.previous().len() > 5 { attempt.none() } else if attempt.url().host() == Some("blocked.domain") { attempt.none() } else { match attempt.default_redirect() { Some(next) => attempt.follow(next), None => attempt.none() } } }); let client = ClientBuilder::default() .redirect(custom_policy) .build()?; Ok(()) } ``` -------------------------------- ### Configure Slinger MITM Proxy with Upstream Proxy Source: https://github.com/emo-crab/slinger/blob/main/crates/slinger-mitm/README.md Demonstrates configuring the Slinger MITM proxy to use an upstream proxy, supporting various protocols like SOCKS5h for remote DNS resolution. This allows chaining proxies or adding authentication. ```rust use slinger_mitm::MitmConfig; // Configure with SOCKS5h proxy (remote DNS resolution) let proxy = slinger::Proxy::parse("socks5h://127.0.0.1:9050")?; let config = MitmConfig { upstream_proxy: Some(proxy), ..Default::default() }; // Supported proxy types: // - HTTP: "http://proxy.example.com:8080" // - HTTPS: "https://proxy.example.com:8443" // - SOCKS5: "socks5://127.0.0.1:1080" // - SOCKS5h: "socks5h://127.0.0.1:1080" (with remote DNS) // - With auth: "socks5h://user:pass@127.0.0.1:1080" ``` -------------------------------- ### Custom Traffic Interceptor in Rust Source: https://context7.com/emo-crab/slinger/llms.txt Demonstrates creating a custom interceptor in Rust to modify HTTP requests and responses. The `SecurityHeaderInterceptor` adds custom headers and modifies the User-Agent for requests, and adds a security header to responses. It requires `async-trait`, `http`, `slinger-mitm`, and `tokio`. ```rust use async_trait::async_trait; use http::HeaderValue; use slinger_mitm::{ Interceptor, MitmConfig, MitmProxy, MitmRequest, MitmResponse, Result }; use std::sync::Arc; // Unified interceptor for both requests and responses struct SecurityHeaderInterceptor; #[async_trait] impl Interceptor for SecurityHeaderInterceptor { async fn intercept_request(&self, mut request: MitmRequest) -> Result> { // Log request details with session correlation println!( "[REQ] Session {} -> {}", request.session_id(), request.destination() ); if request.is_http() { // Add custom tracking header request.request_mut().headers_mut().insert( "X-Proxy-Session", HeaderValue::from_str(&request.session_id().to_string())?, ); // Modify User-Agent request.request_mut().headers_mut().insert( "User-Agent", HeaderValue::from_static("Custom-MITM-Agent/1.0"), ); } Ok(Some(request)) } async fn intercept_response(&self, mut response: MitmResponse) -> Result> { // Session ID correlates with the original request println!( "[RESP] Session {} <- {} (Status: {})", response.session_id(), response.source(), if response.is_http() { response.response().status_code().to_string() } else { "N/A".to_string() } ); if response.is_http() { // Add security headers to response response.response_mut().headers_mut().insert( "X-Proxy-Inspected", HeaderValue::from_static("true"), ); } Ok(Some(response)) } } #[tokio::main] async fn main() -> Result<(), Box> { let config = MitmConfig { ca_storage_path: std::path::PathBuf::from(".slinger-mitm"), enable_https_interception: true, enable_tcp_interception: false, max_connections: 1000, connection_timeout: 30, upstream_proxy: None, }; let proxy = MitmProxy::new(config).await?; // Register custom interceptor let interceptor_handler = proxy.interceptor_handler(); let mut handler = interceptor_handler.write().await; handler.add_interceptor(Arc::new(SecurityHeaderInterceptor)); drop(handler); println!("Custom interceptor proxy on 127.0.0.1:8888"); proxy.start("127.0.0.1:8888").await?; Ok(()) } ``` -------------------------------- ### Enable Automatic Cookie Handling in Rust Source: https://context7.com/emo-crab/slinger/llms.txt Configures the Slinger client to automatically handle cookies for session management. This feature requires the `cookie` feature to be enabled in the Slinger crate. It demonstrates setting cookies with one request and verifying they are sent in subsequent requests. ```rust use slinger::ClientBuilder; #[tokio::main] async fn main() -> Result<(), Box> { // Enable cookie store for session management let client = ClientBuilder::default() .cookie_store(true) .build()?; // First request sets cookies let resp = client .get("http://httpbin.org/cookies/set/session_id/abc123") .send() .await?; println!("Set cookie response: {:?}", resp.text()); // Subsequent requests automatically include cookies let resp = client .get("http://httpbin.org/cookies") .send() .await?; println!("Cookies sent: {:?}", resp.text()); // Access HTTP record for debugging if let Some(record) = resp.http_record() { println!("Number of requests in chain: {}", record.len()); } Ok(()) } ``` -------------------------------- ### Custom Request and Response Interceptors (Rust) Source: https://github.com/emo-crab/slinger/blob/main/crates/slinger-mitm/README.md This code defines a custom interceptor struct that implements both `RequestInterceptor` and `ResponseInterceptor` traits from `slinger-mitm`. It shows how to modify request headers by adding 'X-Custom-Header' and response headers by adding 'X-Modified'. This allows for custom logic to be applied to traffic passing through the proxy. ```rust use async_trait::async_trait; use bytes::Bytes; use http::{Request, Response, HeaderValue}; use slinger_mitm::{RequestInterceptor, ResponseInterceptor, Result}; struct CustomInterceptor; #[async_trait] impl RequestInterceptor for CustomInterceptor { async fn intercept_request(&self, mut request: Request) -> Result>> { // Modify request headers request.headers_mut().insert( "X-Custom-Header", HeaderValue::from_static("value"), ); Ok(Some(request)) } } #[async_trait] impl ResponseInterceptor for CustomInterceptor { async fn intercept_response(&self, mut response: Response) -> Result>> { // Modify response response.headers_mut().insert( "X-Modified", HeaderValue::from_static("true"), ); Ok(Some(response)) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.