1 Commits

Author SHA1 Message Date
Louie
7455f76351 feat: match Go TLS fingerprint for MITM upstream (#11)
* feat: match Go TLS fingerprint for MITM upstream connections

Replace rustls with boring2 (BoringSSL) for all MITM→Google upstream
connections, configured with Go crypto/tls exact defaults:

- Cipher suites: TLS_AES_128_GCM_SHA256 + 14 others in Go order
- Curves: X25519, P-256, P-384
- Signature algorithms: ECDSA+SHA256, RSA-PSS+SHA256, etc.
- HTTP/2 SETTINGS: 4MB stream window, 1GB connection window, 10MB
  header list, no adaptive windowing

Local TLS (LS→MITM) still uses rustls for CA cert presentation.
boring2/tokio-boring2 were already compiled as transitive deps from
wreq — no new build time added.

* chore: fmt + update README TLS description
2026-02-18 16:15:08 -06:00
8 changed files with 141 additions and 55 deletions

2
Cargo.lock generated
View File

@@ -2366,6 +2366,7 @@ dependencies = [
"async-stream",
"axum",
"base64",
"boring2",
"brotli 7.0.0",
"bytes",
"chrono",
@@ -2386,6 +2387,7 @@ dependencies = [
"serde_json",
"time",
"tokio",
"tokio-boring2",
"tokio-rustls",
"tokio-stream",
"tower-http",

View File

@@ -40,6 +40,8 @@ rustls = { version = "0.23", features = ["ring"] }
tokio-rustls = "0.26"
rustls-native-certs = "0.8"
rustls-pemfile = "2"
boring2 = "5.0.0-alpha.12"
tokio-boring2 = "5.0.0-alpha.12"
time = "0.3"
base64 = "0.22"
httparse = "1"

View File

@@ -61,7 +61,7 @@ Explain to the user what this project unlocks — not what it _is_, but what bec
## How It Works
The LS or Language Server is Antigravity's closed source Go binary that talks to Google's API over gRPC. The Extension Server is what feeds it auth tokens and settings/configs, we fake it with a stub so the LS thinks it's inside a real Antigravity window. ZeroGravity turns your OpenAI-compatible requests into dummy prompts and tells the LS to make an API call. The MITM proxy intercepts that call before it leaves the machine, swaps in your real prompt, tools, images, and generation params, re-encrypts it with BoringSSL matching Chrome's exact TLS fingerprint, and forwards it to Google. Google sees what looks like a normal Antigravity session. The response streams back as SSE events which the MITM parses for text, thinking tokens, tool calls, and usage. The iptables redirect is a UID-scoped firewall rule that routes only the LS's traffic through the MITM without touching anything else.
The LS or Language Server is Antigravity's closed source Go binary that talks to Google's API over gRPC. The Extension Server is what feeds it auth tokens and settings/configs, we fake it with a stub so the LS thinks it's inside a real Antigravity window. ZeroGravity turns your OpenAI-compatible requests into dummy prompts and tells the LS to make an API call. The MITM proxy intercepts that call before it leaves the machine, swaps in your real prompt, tools, images, and generation params, re-encrypts it over TLS, and forwards it to Google. All proxy-to-LS communication uses BoringSSL with Chrome's exact TLS and HTTP/2 fingerprint so the LS can't tell it's not a real Antigravity window. Google sees what looks like a normal Antigravity session. The response streams back as SSE events which the MITM parses for text, thinking tokens, tool calls, and usage. The iptables redirect is a UID-scoped firewall rule that routes only the LS's traffic through the MITM without touching anything else.
```mermaid
%%{init: {'theme': 'dark', 'themeVariables': {'primaryColor': '#2a2a2a', 'primaryTextColor': '#d0d0d0', 'primaryBorderColor': '#888', 'lineColor': '#888', 'secondaryColor': '#333', 'tertiaryColor': '#3a3a3a', 'edgeLabelBackground': '#2a2a2a', 'nodeTextColor': '#d0d0d0'}}}%%

View File

@@ -325,9 +325,7 @@ fn svc_stop() -> bool {
}
#[cfg(not(windows))]
{
let _ = Command::new("pkill")
.args(["-f", "zerogravity"])
.status();
let _ = Command::new("pkill").args(["-f", "zerogravity"]).status();
}
true
}
@@ -517,9 +515,8 @@ fn do_test(msg: &str) {
.replace('\n', "\\n")
.replace('\r', "\\r")
.replace('\t', "\\t");
let body = format!(
r#"{{"model":"gemini-3-flash","input":"{escaped}","stream":false,"timeout":30}}"#
);
let body =
format!(r#"{{"model":"gemini-3-flash","input":"{escaped}","stream":false,"timeout":30}}"#);
match curl_post("/v1/responses", &body) {
Some(json) => jq_print(&json),
None => {

View File

@@ -42,15 +42,15 @@ use tracing::{debug, info, trace, warn};
/// We mirror this by maintaining a single upstream connection per domain.
struct UpstreamPool {
domain: String,
tls_config: Arc<rustls::ClientConfig>,
tls_connector: boring2::ssl::SslConnector,
sender: Mutex<Option<hyper::client::conn::http2::SendRequest<Full<Bytes>>>>,
}
impl UpstreamPool {
fn new(domain: String, tls_config: Arc<rustls::ClientConfig>) -> Self {
fn new(domain: String, tls_connector: boring2::ssl::SslConnector) -> Self {
Self {
domain,
tls_config,
tls_connector,
sender: Mutex::new(None),
}
}
@@ -82,17 +82,29 @@ impl UpstreamPool {
.await
.map_err(|e| format!("upstream TCP connect to {} failed: {e}", self.domain))?;
let connector = tokio_rustls::TlsConnector::from(self.tls_config.clone());
let server_name = rustls::pki_types::ServerName::try_from(self.domain.clone())
.map_err(|e| format!("invalid domain {}: {e}", self.domain))?;
let ssl = self
.tls_connector
.configure()
.map_err(|e| format!("SSL configure: {e}"))?
.into_ssl(&self.domain)
.map_err(|e| format!("SSL into_ssl: {e}"))?;
let upstream_tls = connector
.connect(server_name, upstream_tcp)
.await
let mut upstream_tls = tokio_boring2::SslStream::new(ssl, upstream_tcp)
.map_err(|e| format!("upstream TLS to {} failed: {e}", self.domain))?;
std::pin::Pin::new(&mut upstream_tls)
.connect()
.await
.map_err(|e| format!("TLS handshake to {} failed: {e}", self.domain))?;
let upstream_io = TokioIo::new(upstream_tls);
// Configure HTTP/2 SETTINGS to match Go's net/http2 defaults
// Source: golang.org/x/net/http2/transport.go
let (sender, conn) = hyper::client::conn::http2::Builder::new(TokioExecutor::new())
.initial_stream_window_size(4 << 20) // 4MB (Go: transportDefaultStreamFlow)
.initial_connection_window_size(1 << 30) // 1GB (Go: transportDefaultConnFlow)
.max_header_list_size(10 * 1024 * 1024) // 10MB (Go: defaultMaxHeaderListSize)
.adaptive_window(false) // Go doesn't use adaptive windowing
.handshake(upstream_io)
.await
.map_err(|e| format!("upstream h2 handshake to {} failed: {e}", self.domain))?;
@@ -140,22 +152,11 @@ where
{
info!(domain = %domain, "MITM H2: handling HTTP/2 connection");
// Build TLS config for upstream connections
let mut root_store = rustls::RootCertStore::empty();
let native_certs = rustls_native_certs::load_native_certs();
for cert in native_certs.certs {
let _ = root_store.add(cert);
}
let mut upstream_tls_config = rustls::ClientConfig::builder()
.with_root_certificates(root_store)
.with_no_client_auth();
upstream_tls_config.alpn_protocols = vec![b"h2".to_vec()];
// Build upstream TLS connector matching Go's crypto/tls fingerprint (with ALPN h2)
let upstream_connector = super::tls::build_go_tls_connector(Some(&[b"h2"]));
// Shared upstream connection pool (single connection, multiplexed)
let pool = Arc::new(UpstreamPool::new(
domain.clone(),
Arc::new(upstream_tls_config),
));
let pool = Arc::new(UpstreamPool::new(domain.clone(), upstream_connector));
let io = TokioIo::new(tls_stream);
let domain = Arc::new(domain);

View File

@@ -18,3 +18,4 @@ pub mod modify;
pub mod proto;
pub mod proxy;
pub mod store;
pub mod tls;

View File

@@ -368,20 +368,11 @@ async fn handle_http_over_tls(
) -> Result<(), String> {
let mut tmp = vec![0u8; 32768];
// Build upstream TLS connector once for this connection
let mut root_store = rustls::RootCertStore::empty();
let native_certs = rustls_native_certs::load_native_certs();
for cert in native_certs.certs {
let _ = root_store.add(cert);
}
let upstream_config = Arc::new(
rustls::ClientConfig::builder()
.with_root_certificates(root_store)
.with_no_client_auth(),
);
// Build upstream TLS connector matching Go's crypto/tls fingerprint
let upstream_connector = super::tls::build_go_tls_connector(None);
// Reusable upstream connection — created lazily, reconnected if stale
let mut upstream: Option<tokio_rustls::client::TlsStream<TcpStream>> = None;
let mut upstream: Option<tokio_boring2::SslStream<TcpStream>> = None;
// Keep-alive loop: handle multiple requests on this connection
loop {
@@ -575,7 +566,7 @@ async fn handle_http_over_tls(
let conn = match upstream.as_mut() {
Some(c) => c,
None => {
let c = connect_upstream(domain, &upstream_config).await?;
let c = connect_upstream(domain, &upstream_connector).await?;
upstream.insert(c)
}
};
@@ -583,7 +574,7 @@ async fn handle_http_over_tls(
// Forward the request — if write fails, reconnect and retry once
if let Err(e) = conn.write_all(&request_buf).await {
debug!(domain, error = %e, "MITM: upstream write failed, reconnecting");
let c = connect_upstream(domain, &upstream_config).await?;
let c = connect_upstream(domain, &upstream_connector).await?;
let conn = upstream.insert(c);
conn.write_all(&request_buf)
.await
@@ -905,15 +896,15 @@ async fn read_full_request(
/// Connect (or reconnect) to the real upstream via TLS.
///
/// Uses BoringSSL configured to match Go's `crypto/tls` fingerprint.
/// Bypasses /etc/hosts by resolving via direct DNS query (dig @8.8.8.8),
/// then falls back to cached IPs file, then to normal system resolution.
async fn connect_upstream(
domain: &str,
config: &Arc<rustls::ClientConfig>,
) -> Result<tokio_rustls::client::TlsStream<TcpStream>, String> {
let connector = tokio_rustls::TlsConnector::from(config.clone());
connector: &boring2::ssl::SslConnector,
) -> Result<tokio_boring2::SslStream<TcpStream>, String> {
let addr = resolve_upstream(domain).await;
info!(domain, addr = %addr, "MITM: connecting upstream");
info!(domain, addr = %addr, "MITM: connecting upstream (BoringSSL)");
let tcp = match tokio::time::timeout(
std::time::Duration::from_secs(15),
@@ -926,20 +917,26 @@ async fn connect_upstream(
Err(_) => return Err(format!("Connect to upstream {domain} ({addr}): timed out")),
};
let server_name = rustls::pki_types::ServerName::try_from(domain.to_string())
.map_err(|e| format!("Invalid server name: {e}"))?;
let ssl = connector
.configure()
.map_err(|e| format!("SSL configure: {e}"))?
.into_ssl(domain)
.map_err(|e| format!("SSL into_ssl: {e}"))?;
let mut stream = tokio_boring2::SslStream::new(ssl, tcp)
.map_err(|e| format!("SslStream::new for {domain}: {e}"))?;
match tokio::time::timeout(
std::time::Duration::from_secs(15),
connector.connect(server_name, tcp),
std::pin::Pin::new(&mut stream).connect(),
)
.await
{
Ok(Ok(s)) => {
info!(domain, "MITM: upstream TLS connected ✓");
Ok(s)
Ok(Ok(())) => {
info!(domain, "MITM: upstream TLS connected ✓ (BoringSSL)");
Ok(stream)
}
Ok(Err(e)) => Err(format!("TLS connect to upstream {domain}: {e}")),
Ok(Err(e)) => Err(format!("TLS handshake to upstream {domain}: {e}")),
Err(_) => Err(format!("TLS connect to upstream {domain}: timed out")),
}
}

86
src/mitm/tls.rs Normal file
View File

@@ -0,0 +1,86 @@
//! Upstream TLS configuration matching Go's `crypto/tls` defaults.
//!
//! The LS is a Go binary — its outbound TLS to Google uses Go's default
//! cipher suites, curves, and signature algorithms. This module configures
//! BoringSSL to produce a matching TLS ClientHello so Google sees the same
//! JA3/JA4 fingerprint regardless of whether our MITM is active.
use boring2::ssl::{SslConnector, SslMethod};
use tracing::debug;
/// Go's default cipher suites in the exact order Go's `crypto/tls` sends them.
///
/// TLS 1.3 ciphers (hardcoded in Go, not configurable):
/// TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384, TLS_CHACHA20_POLY1305_SHA256
///
/// TLS 1.2 ciphers (Go's default preference order):
/// ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256,
/// ECDHE-ECDSA-AES256-GCM-SHA384, ECDHE-RSA-AES256-GCM-SHA384,
/// ECDHE-ECDSA-CHACHA20-POLY1305, ECDHE-RSA-CHACHA20-POLY1305,
/// ECDHE-RSA-AES128-SHA, ECDHE-RSA-AES256-SHA,
/// AES128-GCM-SHA256, AES256-GCM-SHA384, AES128-SHA, AES256-SHA
const GO_CIPHER_LIST: &str = "\
TLS_AES_128_GCM_SHA256:\
TLS_AES_256_GCM_SHA384:\
TLS_CHACHA20_POLY1305_SHA256:\
ECDHE-ECDSA-AES128-GCM-SHA256:\
ECDHE-RSA-AES128-GCM-SHA256:\
ECDHE-ECDSA-AES256-GCM-SHA384:\
ECDHE-RSA-AES256-GCM-SHA384:\
ECDHE-ECDSA-CHACHA20-POLY1305:\
ECDHE-RSA-CHACHA20-POLY1305:\
ECDHE-RSA-AES128-SHA:\
ECDHE-RSA-AES256-SHA:\
AES128-GCM-SHA256:\
AES256-GCM-SHA384:\
AES128-SHA:\
AES256-SHA";
/// Go's default signature algorithms.
const GO_SIGALGS: &str = "\
ECDSA+SHA256:\
RSA-PSS+SHA256:\
RSA+SHA256:\
ECDSA+SHA384:\
RSA-PSS+SHA384:\
RSA+SHA384:\
RSA-PSS+SHA512:\
RSA+SHA512:\
RSA+SHA1";
/// Build an `SslConnector` that mimics Go's `crypto/tls` defaults.
///
/// If `alpn` is provided, sets ALPN protocols (e.g. `&[b"h2"]` for HTTP/2).
pub fn build_go_tls_connector(alpn: Option<&[&[u8]]>) -> SslConnector {
let mut builder =
SslConnector::builder(SslMethod::tls_client()).expect("SslConnector::builder");
// Set Go's cipher list
builder
.set_cipher_list(GO_CIPHER_LIST)
.expect("set_cipher_list");
// Set Go's signature algorithms
builder
.set_sigalgs_list(GO_SIGALGS)
.expect("set_sigalgs_list");
// Set Go's default curves: X25519, P-256, P-384
// BoringSSL uses set_curves_list with colon-separated names
builder
.set_curves_list("X25519:P-256:P-384")
.expect("set_curves_list");
// ALPN if requested (for HTTP/2)
if let Some(protos) = alpn {
let mut wire = Vec::new();
for proto in protos {
wire.push(proto.len() as u8);
wire.extend_from_slice(proto);
}
builder.set_alpn_protos(&wire).expect("set_alpn_protos");
}
debug!("Built Go-matching TLS connector (BoringSSL)");
builder.build()
}