Skip to content

Commit 2725f40

Browse files
committed
fix(forward): validate TCP targets before local bind
Normalize supported loopback targets and reject invalid hosts or ports before client lookup and binding while retaining gateway authority. Closes #5112 Signed-off-by: Shiju <[email protected]>
1 parent c92c2c7 commit 2725f40

6 files changed

Lines changed: 135 additions & 26 deletions

File tree

‎crates/openshell-cli/src/run.rs‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2166,6 +2166,13 @@ pub async fn service_forward_tcp(
21662166
tls: &TlsOptions,
21672167
workspace: &str,
21682168
) -> Result<()> {
2169+
let target_host = openshell_core::net::normalize_tcp_forward_host(target_host)
2170+
.map_err(|message| miette::miette!(message))?;
2171+
if target_port == 0 {
2172+
return Err(miette::miette!(
2173+
"tcp target port must be between 1 and 65535"
2174+
));
2175+
}
21692176
let (bind_addr, bind_port) = parse_tcp_forward_spec(local, target_port)?;
21702177
let mut client = grpc_client(server, tls).await?;
21712178

@@ -2214,7 +2221,7 @@ pub async fn service_forward_tcp(
22142221
let mut client = client.clone();
22152222
let sandbox_name = sandbox_name.clone();
22162223
let sandbox_workspace = sandbox_workspace.clone();
2217-
let target_host = target_host.to_string();
2224+
let target_host = target_host.clone();
22182225
let service_id = format!("service-forward:{name}:{target_host}:{target_port}");
22192226
let fatal_tx = fatal_tx.clone();
22202227
let legacy_session_tokens = legacy_session_tokens.clone();
@@ -7135,6 +7142,36 @@ mod tests {
71357142
};
71367143
use openshell_core::proto::TcpForwardFrame;
71377144

7145+
#[tokio::test]
7146+
async fn forward_rejects_invalid_target_before_gateway_or_local_bind() {
7147+
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
7148+
let local = listener.local_addr().unwrap().to_string();
7149+
for (host, port, message) in [
7150+
("example.com", 8080, "tcp target host must be loopback"),
7151+
("192.0.2.1", 8080, "tcp target host must be loopback"),
7152+
("::ffff:127.0.0.1", 8080, "tcp target host must be loopback"),
7153+
("", 8080, "tcp target host is required"),
7154+
(
7155+
"127.0.0.1",
7156+
0,
7157+
"tcp target port must be between 1 and 65535",
7158+
),
7159+
] {
7160+
let error = super::service_forward_tcp(
7161+
"invalid gateway",
7162+
"sandbox",
7163+
Some(&local),
7164+
host,
7165+
port,
7166+
&crate::tls::TlsOptions::default(),
7167+
"default",
7168+
)
7169+
.await
7170+
.unwrap_err();
7171+
assert_eq!(error.to_string(), message);
7172+
}
7173+
}
7174+
71387175
#[test]
71397176
fn lifecycle_wait_fails_fast_on_phases_that_block_the_target() {
71407177
use super::lifecycle_phase_blocks_target;

‎crates/openshell-core/src/net.rs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,31 @@ use ipnet::{IpNet, Ipv4Net, Ipv6Net};
1919
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
2020
use tokio::net::TcpStream;
2121

22+
/// Normalize a TCP forward destination without DNS resolution.
23+
///
24+
/// Forward targets must be sandbox loopback addresses. `localhost` uses IPv4
25+
/// loopback consistently across clients and the gateway.
26+
///
27+
/// # Errors
28+
/// Returns an error for an empty host or a non-loopback destination.
29+
pub fn normalize_tcp_forward_host(host: &str) -> Result<String, &'static str> {
30+
let host = host.trim();
31+
if host.is_empty() {
32+
return Err("tcp target host is required");
33+
}
34+
if host.eq_ignore_ascii_case("localhost") {
35+
return Ok("127.0.0.1".to_string());
36+
}
37+
let ip: IpAddr = host
38+
.parse()
39+
.map_err(|_| "tcp target host must be loopback")?;
40+
if ip.is_loopback() {
41+
Ok(ip.to_string())
42+
} else {
43+
Err("tcp target host must be loopback")
44+
}
45+
}
46+
2247
/// Check if a hostname is a known cloud metadata hostname that resolves to an
2348
/// always-blocked metadata service.
2449
///

‎crates/openshell-server/src/grpc/sandbox.rs‎

Lines changed: 14 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,6 @@ use openshell_core::{GetResourceVersion, ObjectId, ObjectName, ObjectWorkspace};
5151
use prost::Message;
5252
use prost_types::{Struct, Value, value::Kind};
5353
use std::collections::{HashMap, HashSet};
54-
use std::net::IpAddr;
5554
use std::pin::Pin;
5655
use std::sync::Arc;
5756
use std::sync::atomic::{AtomicBool, Ordering};
@@ -3111,28 +3110,12 @@ fn validate_tcp_forward_target(target: &TcpRelayTarget) -> Result<TcpRelayTarget
31113110
));
31123111
}
31133112

3114-
validate_tcp_target_parts(target.host.trim(), target.port).map(|host| TcpRelayTarget {
3115-
host,
3116-
port: target.port,
3117-
})
3118-
}
3119-
3120-
fn validate_tcp_target_parts(host: &str, _port: u32) -> Result<String, Status> {
3121-
if host.is_empty() {
3122-
return Err(Status::invalid_argument("tcp target host is required"));
3123-
}
3124-
if host.eq_ignore_ascii_case("localhost") {
3125-
return Ok("127.0.0.1".to_string());
3126-
}
3127-
3128-
let ip: IpAddr = host
3129-
.parse()
3130-
.map_err(|_| Status::invalid_argument("tcp target host must be loopback"))?;
3131-
if ip.is_loopback() {
3132-
Ok(ip.to_string())
3133-
} else {
3134-
Err(Status::invalid_argument("tcp target host must be loopback"))
3135-
}
3113+
openshell_core::net::normalize_tcp_forward_host(&target.host)
3114+
.map_err(Status::invalid_argument)
3115+
.map(|host| TcpRelayTarget {
3116+
host,
3117+
port: target.port,
3118+
})
31363119
}
31373120

31383121
async fn bridge_forward_tcp_stream<S>(
@@ -4972,7 +4955,14 @@ mod tests {
49724955

49734956
#[test]
49744957
fn tcp_forward_init_allows_loopback_targets() {
4975-
for host in ["127.0.0.1", "::1", "localhost"] {
4958+
for host in [
4959+
"127.0.0.1",
4960+
"127.2.3.4",
4961+
"::1",
4962+
"0:0:0:0:0:0:0:1",
4963+
" localhost ",
4964+
"LOCALHOST",
4965+
] {
49764966
let init = TcpForwardInit {
49774967
sandbox: "sbx".to_string(),
49784968
workspace: String::new(),

‎docs/how-it-works/sandboxes/overview.mdx‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -873,6 +873,18 @@ openshell sandbox create --from registry.example.com/your-org/claude-agent:lates
873873
874874
</Tip>
875875
876+
### Forward a TCP service through the gateway
877+
878+
Use the gateway's TCP relay to forward a loopback service:
879+
880+
```shell
881+
openshell forward service my-sandbox --target-host 127.0.0.1 --target-port 8080 --local 0
882+
```
883+
884+
The target host must be a loopback IP address or `localhost`, and the target
885+
port must be between 1 and 65535. The CLI and TypeScript SDK reject invalid
886+
targets before opening a local listener. The gateway also validates each target.
887+
876888
## SSH Config
877889
878890
Each sandbox has its own SSH host key. The key stays the same when the

‎sdk/typescript/src/client.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2167,6 +2167,38 @@ describe('ssh sessions', () => {
21672167
});
21682168

21692169
describe('forward', () => {
2170+
it('rejects invalid targets before gateway access or binding a local port', async () => {
2171+
let reads = 0;
2172+
const sandbox = client({
2173+
getSandbox: () => {
2174+
reads++;
2175+
return readySandbox('sb', 'id');
2176+
},
2177+
});
2178+
for (const targetHost of ['example.com', '192.0.2.1', '::ffff:127.0.0.1', '::1%lo0', '[::1]', '']) {
2179+
await expect(sandbox.forward('sb', { targetHost, targetPort: 9000 })).rejects.toMatchObject({
2180+
code: 'invalid_config',
2181+
message: expect.stringContaining('tcp target host'),
2182+
});
2183+
}
2184+
for (const targetPort of [0, -1, 65536, 1.5, Number.NaN]) {
2185+
await expect(sandbox.forward('sb', { targetPort })).rejects.toMatchObject({
2186+
code: 'invalid_config',
2187+
message: '[invalid_config] tcp target port must be between 1 and 65535',
2188+
});
2189+
}
2190+
expect(reads).toBe(0);
2191+
for (const [targetHost, normalized] of [
2192+
[' LOCALHOST ', '127.0.0.1'],
2193+
['127.2.3.4', '127.2.3.4'],
2194+
['0:0:0:0:0:0:0:1', '::1'],
2195+
]) {
2196+
const handle = await sandbox.forward('sb', { targetHost, targetPort: 9000 });
2197+
expect(handle.targetHost).toBe(normalized);
2198+
await handle.close();
2199+
}
2200+
});
2201+
21702202
it('binds a local port and relays bytes both ways, minting + revoking a token', async () => {
21712203
let sshReq: ScopedRequest = {};
21722204
let revokedToken: string | undefined;

‎sdk/typescript/src/client.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,16 @@ import { ProviderClient } from './providers.js';
4343
import { validateSshResponse } from './ssh-validate.js';
4444
import { buildTransport, type ConnectOptions } from './transport.js';
4545

46+
// Match the gateway's loopback-only forward target contract without DNS.
47+
function normalizeForwardHost(value: string): string {
48+
const host = value.trim();
49+
if (!host) throw new SdkError('invalid_config', 'tcp target host is required');
50+
if (host.toLowerCase() === 'localhost') return '127.0.0.1';
51+
if (net.isIPv4(host) && host.startsWith('127.')) return host;
52+
if (net.isIPv6(host) && !host.includes('%') && new URL(`http://[${host}]`).hostname === '[::1]') return '::1';
53+
throw new SdkError('invalid_config', 'tcp target host must be loopback');
54+
}
55+
4656
function durationFromSeconds(seconds: number) {
4757
if (!Number.isFinite(seconds) || seconds < 0) {
4858
throw new RangeError('timeoutSecs must be a finite, non-negative number');
@@ -1707,8 +1717,11 @@ export class SandboxClient {
17071717
// the `init` (TCP target + token), relay bytes both ways in ~64 KiB chunks,
17081718
// and revoke the token on close. Process-lifetime only.
17091719
async forward(name: string, opts: ForwardOptions): Promise<ForwardHandle> {
1710-
const targetHost = opts.targetHost ?? '127.0.0.1';
1720+
const targetHost = normalizeForwardHost(opts.targetHost ?? '127.0.0.1');
17111721
const targetPort = opts.targetPort;
1722+
if (!Number.isInteger(targetPort) || targetPort < 1 || targetPort > 65535) {
1723+
throw new SdkError('invalid_config', 'tcp target port must be between 1 and 65535');
1724+
}
17121725
const localHost = opts.localHost ?? '127.0.0.1';
17131726
const localPort = opts.localPort ?? 0;
17141727

0 commit comments

Comments
 (0)