Skip to content

Commit 86d5389

Browse files
ly85206559steipete
andauthored
fix(android): block loopback canvas navigation (#99874)
* fix(android): block loopback canvas navigation * fix(android): reject Unicode canvas hosts * chore(android): sync app changelog * style(android): format canvas navigation policy * chore(docs): sync generated docs map * chore(ci): sync hosted gate verifier --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent e66f43e commit 86d5389

4 files changed

Lines changed: 345 additions & 2 deletions

File tree

‎apps/android/app/src/main/java/ai/openclaw/app/node/CanvasController.kt‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,7 @@ class CanvasController {
8282

8383
/** Navigates the canvas to a remote URL or back to the bundled scaffold for blank/root input. */
8484
fun navigate(url: String) {
85-
val trimmed = url.trim()
86-
this.url = if (trimmed.isBlank() || trimmed == "/") null else trimmed
85+
this.url = CanvasNavigationPolicy.normalize(url).ifBlank { null }
8786
_currentUrl.value = this.url
8887
reload()
8988
}
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
package ai.openclaw.app.node
2+
3+
import java.net.InetAddress
4+
import java.net.URI
5+
6+
/** Shared policy for gateway-driven loads and WebView main-frame navigations. */
7+
internal object CanvasNavigationPolicy {
8+
fun normalize(rawUrl: String): String {
9+
val trimmed = rawUrl.trim()
10+
if (trimmed.isBlank() || trimmed == "/") return ""
11+
return trimmed.takeUnless(::shouldBlock).orEmpty()
12+
}
13+
14+
fun shouldBlock(rawUrl: String): Boolean {
15+
val trimmed = rawUrl.trim()
16+
if (trimmed.isBlank() || trimmed == "/") return false
17+
val target = parseTarget(trimmed)
18+
val isWebUrl = target.scheme == "http" || target.scheme == "https"
19+
if (isWebUrl && (target.host.isEmpty() || isMalformedWebHost(target.host))) return true
20+
return target.host.isNotEmpty() && isDeviceLocalHost(target.host)
21+
}
22+
23+
/** WebView does not expose POST redirects to shouldOverrideUrlLoading; fail closed before dispatch. */
24+
fun shouldBlockNonGetMainFrame(
25+
method: String,
26+
isForMainFrame: Boolean,
27+
): Boolean = isForMainFrame && !method.equals("GET", ignoreCase = true)
28+
29+
private data class Target(
30+
val scheme: String,
31+
val host: String,
32+
)
33+
34+
private fun parseTarget(rawUrl: String): Target {
35+
val parsed = runCatching { URI(rawUrl) }.getOrNull()
36+
val scheme =
37+
parsed
38+
?.scheme
39+
?.trim()
40+
?.lowercase()
41+
.orEmpty()
42+
.ifBlank { rawScheme(rawUrl) }
43+
val host =
44+
parsed
45+
?.host
46+
?.trim()
47+
.orEmpty()
48+
.ifBlank { authorityHost(parsed?.rawAuthority ?: rawAuthority(rawUrl)) }
49+
return Target(scheme = scheme, host = percentDecodeAscii(host))
50+
}
51+
52+
private fun rawScheme(rawUrl: String): String {
53+
val schemeSeparator = rawUrl.indexOf("://")
54+
val colonSeparator = rawUrl.indexOf(':')
55+
val end =
56+
when {
57+
schemeSeparator > 0 -> schemeSeparator
58+
colonSeparator > 0 -> colonSeparator
59+
else -> return ""
60+
}
61+
val candidate = rawUrl.substring(0, end).trim().lowercase()
62+
return candidate
63+
.takeIf {
64+
it.all { char ->
65+
char in 'a'..'z' || char in '0'..'9' || char == '+' || char == '-' || char == '.'
66+
}
67+
}.orEmpty()
68+
}
69+
70+
private fun rawAuthority(rawUrl: String): String? {
71+
val schemeSeparator = rawUrl.indexOf("://")
72+
if (schemeSeparator < 0) return null
73+
val authorityStart = schemeSeparator + 3
74+
val authorityEnd =
75+
rawUrl
76+
.indexOfAny(charArrayOf('/', '\\', '?', '#'), startIndex = authorityStart)
77+
.takeIf { it >= 0 }
78+
?: rawUrl.length
79+
return rawUrl.substring(authorityStart, authorityEnd)
80+
}
81+
82+
private fun authorityHost(rawAuthority: String?): String {
83+
val authority = rawAuthority?.trim().orEmpty()
84+
if (authority.isEmpty()) return ""
85+
val hostPort = authority.substringAfterLast('@')
86+
if (hostPort.startsWith("[")) {
87+
return hostPort.substringAfter('[').substringBefore(']')
88+
}
89+
return if (hostPort.count { it == ':' } == 1) hostPort.substringBefore(':') else hostPort
90+
}
91+
92+
private fun percentDecodeAscii(value: String): String {
93+
if (!value.contains('%')) return value
94+
val out = StringBuilder(value.length)
95+
var index = 0
96+
while (index < value.length) {
97+
if (value[index] == '%' && index + 2 < value.length) {
98+
val byte = value.substring(index + 1, index + 3).toIntOrNull(16)
99+
if (byte != null) {
100+
out.append(byte.toChar())
101+
index += 3
102+
continue
103+
}
104+
}
105+
out.append(value[index])
106+
index += 1
107+
}
108+
return out.toString()
109+
}
110+
111+
private fun isMalformedWebHost(rawHost: String): Boolean =
112+
// Chromium applies UTS #46 before resolving special-scheme hosts. Reject raw Unicode here so
113+
// compatibility characters cannot become localhost or a loopback IP after this check.
114+
rawHost.any { char ->
115+
char <= ' ' ||
116+
char.code > 0x7f ||
117+
char == '/' ||
118+
char == '\\' ||
119+
char == '?' ||
120+
char == '#' ||
121+
char == '@'
122+
} ||
123+
rawHost.contains('%')
124+
125+
private fun isDeviceLocalHost(rawHost: String): Boolean {
126+
var host =
127+
rawHost
128+
.trim()
129+
.lowercase()
130+
.trim('[', ']')
131+
.trimEnd('.')
132+
host = host.substringBefore('%')
133+
if (host == "localhost" || host.endsWith(".localhost")) return true
134+
135+
parseWebViewIpv4Address(host)?.let { address ->
136+
return address == 0L || ((address ushr 24) and 0xffL) == 127L
137+
}
138+
139+
if (!host.contains(':') || !host.all(::isIpv6LiteralChar)) return false
140+
val address = runCatching { InetAddress.getByName(host).address }.getOrNull() ?: return false
141+
if (address.size == 4) {
142+
return address.all { it == 0.toByte() } || address[0] == 127.toByte()
143+
}
144+
if (address.size != 16) return false
145+
if (address.all { it == 0.toByte() }) return true
146+
if (address.copyOfRange(0, 15).all { it == 0.toByte() } && address[15] == 1.toByte()) return true
147+
148+
val mappedPrefix =
149+
address.copyOfRange(0, 10).all { it == 0.toByte() } &&
150+
address[10] == 0xff.toByte() &&
151+
address[11] == 0xff.toByte()
152+
val compatiblePrefix = address.copyOfRange(0, 12).all { it == 0.toByte() }
153+
return (mappedPrefix || compatiblePrefix) &&
154+
(address[12] == 127.toByte() || address.copyOfRange(12, 16).all { it == 0.toByte() })
155+
}
156+
157+
private fun isIpv6LiteralChar(char: Char): Boolean = char == ':' || char == '.' || char in '0'..'9' || char.lowercaseChar() in 'a'..'f'
158+
159+
/** Matches Chromium/WebView's accepted decimal, octal, hex, and shorthand IPv4 forms. */
160+
private fun parseWebViewIpv4Address(rawHost: String): Long? {
161+
val host = rawHost.trim().lowercase().trimEnd('.')
162+
if (host.isEmpty() || host.contains(':') || host.contains('%')) return null
163+
val parts = host.split('.')
164+
if (parts.size !in 1..4 || parts.any { it.isEmpty() }) return null
165+
val numbers = parts.map { parseWebViewIpv4Number(it) ?: return null }
166+
if (numbers.dropLast(1).any { it > 255L }) return null
167+
val lastMax =
168+
when (numbers.size) {
169+
1 -> 0xffffffffL
170+
2 -> 0x00ffffffL
171+
3 -> 0x0000ffffL
172+
else -> 0xffL
173+
}
174+
val last = numbers.last()
175+
if (last > lastMax) return null
176+
return when (numbers.size) {
177+
1 -> last
178+
2 -> (numbers[0] shl 24) or last
179+
3 -> (numbers[0] shl 24) or (numbers[1] shl 16) or last
180+
else -> (numbers[0] shl 24) or (numbers[1] shl 16) or (numbers[2] shl 8) or last
181+
}
182+
}
183+
184+
private fun parseWebViewIpv4Number(raw: String): Long? {
185+
val normalized = raw.trim().lowercase()
186+
if (normalized.isEmpty()) return null
187+
val (digits, radix) =
188+
when {
189+
normalized.startsWith("0x") -> normalized.drop(2) to 16
190+
normalized.length > 1 && normalized.startsWith("0") -> normalized.drop(1) to 8
191+
else -> normalized to 10
192+
}
193+
if (digits.isEmpty()) return 0L
194+
return digits.toLongOrNull(radix)
195+
}
196+
}

‎apps/android/app/src/main/java/ai/openclaw/app/ui/CanvasScreen.kt‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package ai.openclaw.app.ui
22

33
import ai.openclaw.app.MainViewModel
4+
import ai.openclaw.app.node.CanvasNavigationPolicy
45
import android.annotation.SuppressLint
56
import android.net.Uri
67
import android.util.Log
@@ -24,6 +25,7 @@ import androidx.webkit.WebMessageCompat
2425
import androidx.webkit.WebSettingsCompat
2526
import androidx.webkit.WebViewCompat
2627
import androidx.webkit.WebViewFeature
28+
import java.io.ByteArrayInputStream
2729
import java.util.concurrent.atomic.AtomicReference
2830

2931
/** Hosts the gateway canvas WebView and attaches it to the runtime canvas controller. */
@@ -86,6 +88,31 @@ fun CanvasScreen(
8688
webView.isHorizontalScrollBarEnabled = true
8789
webView.webViewClient =
8890
object : WebViewClient() {
91+
override fun shouldOverrideUrlLoading(
92+
view: WebView,
93+
request: WebResourceRequest,
94+
): Boolean {
95+
if (!request.isForMainFrame) return false
96+
return blockUnsafeCanvasNavigation(viewModel, currentPageUrlRef, request.url.toString())
97+
}
98+
99+
override fun shouldInterceptRequest(
100+
view: WebView,
101+
request: WebResourceRequest,
102+
): WebResourceResponse? {
103+
val shouldBlock =
104+
CanvasNavigationPolicy.shouldBlockNonGetMainFrame(
105+
method = request.method,
106+
isForMainFrame = request.isForMainFrame,
107+
)
108+
if (!shouldBlock) return null
109+
// shouldOverrideUrlLoading excludes POST navigations and their redirects. WebView does
110+
// not expose those redirect targets, so non-GET main-frame loads fail closed here.
111+
currentPageUrlRef.set(null)
112+
view.post { viewModel.canvas.navigate("") }
113+
return blockedCanvasResponse()
114+
}
115+
89116
override fun onPageStarted(
90117
view: WebView,
91118
url: String?,
@@ -187,6 +214,28 @@ fun CanvasScreen(
187214
)
188215
}
189216

217+
private fun blockUnsafeCanvasNavigation(
218+
viewModel: MainViewModel,
219+
currentPageUrlRef: AtomicReference<String?>,
220+
rawUrl: String,
221+
): Boolean {
222+
val url = rawUrl.trim()
223+
if (!CanvasNavigationPolicy.shouldBlock(url)) return false
224+
currentPageUrlRef.set(null)
225+
viewModel.canvas.navigate("")
226+
return true
227+
}
228+
229+
private fun blockedCanvasResponse(): WebResourceResponse =
230+
WebResourceResponse(
231+
"text/plain",
232+
"UTF-8",
233+
403,
234+
"Blocked",
235+
mapOf("Cache-Control" to "no-store"),
236+
ByteArrayInputStream(ByteArray(0)),
237+
)
238+
190239
/** Filters WebView postMessage payloads before they enter the A2UI action handler. */
191240
internal class CanvasA2UIActionBridge(
192241
private val isTrustedPage: () -> Boolean,
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
package ai.openclaw.app.node
2+
3+
import org.junit.Assert.assertEquals
4+
import org.junit.Assert.assertNull
5+
import org.junit.Test
6+
7+
class CanvasNavigationPolicyTest {
8+
@Test
9+
fun blocksDeviceLocalWebUrls() {
10+
listOf(
11+
"http://127.0.0.1:18789",
12+
"https://localhost",
13+
"https://canvas.localhost/path",
14+
"http://0.0.0.0:18789",
15+
"http://0/canvas",
16+
"http://[::]/canvas",
17+
"http://[::1]/canvas",
18+
"http://[::1%25lo]/canvas",
19+
"http://[::ffff:127.0.0.1]/canvas",
20+
"http://2130706433/canvas",
21+
"http://0x7f000001/canvas",
22+
"http://017700000001/canvas",
23+
"http://127.1/canvas",
24+
"http://0x7f.1/canvas",
25+
"http://127.0.0.1/a raw space",
26+
"http://127.0.0.1/#raw space",
27+
"http://127.0.0.1\\@example.com/",
28+
"http://%31%32%37.0.0.1:18789/",
29+
"http://%6c%6f%63%61%6c%68%6f%73%74/",
30+
"http://localhost:18789/",
31+
"http://127.0.0.1:18789/",
32+
"http:\\127.0.0.1:18789/",
33+
"http:127.0.0.1:18789/",
34+
).forEach { url ->
35+
assertEquals(url, true, CanvasNavigationPolicy.shouldBlock(url))
36+
assertEquals(url, "", CanvasNavigationPolicy.normalize(url))
37+
}
38+
}
39+
40+
@Test
41+
fun blocksMalformedWebHosts() {
42+
listOf(
43+
"http:///missing-host",
44+
"https://double%252dencoded.example/",
45+
"http://example.com%00.evil/",
46+
).forEach { url -> assertEquals(url, true, CanvasNavigationPolicy.shouldBlock(url)) }
47+
}
48+
49+
@Test
50+
fun keepsRemoteEmulatorBridgeAndBundledUrls() {
51+
val accepted =
52+
listOf(
53+
"https://example.com/canvas",
54+
"https://xn--mnich-kva.example/canvas",
55+
"http://gateway.local:18789/__openclaw__/canvas/",
56+
"http://10.0.2.2:18789/__openclaw__/canvas/",
57+
CanvasActionTrust.scaffoldAssetUrl,
58+
)
59+
accepted.forEach { url ->
60+
assertEquals(url, false, CanvasNavigationPolicy.shouldBlock(url))
61+
assertEquals(url, url, CanvasNavigationPolicy.normalize(" $url "))
62+
}
63+
}
64+
65+
@Test
66+
fun blankAndRootSelectBundledCanvasWithoutBeingSecurityBlocks() {
67+
listOf("", " / ").forEach { url ->
68+
assertEquals(url, false, CanvasNavigationPolicy.shouldBlock(url))
69+
assertEquals(url, "", CanvasNavigationPolicy.normalize(url))
70+
}
71+
}
72+
73+
@Test
74+
fun controllerUsesSharedPolicyForDirectLoads() {
75+
val controller = CanvasController()
76+
77+
controller.navigate("http://127.0.0.1:18789")
78+
assertNull(controller.currentUrl())
79+
80+
controller.navigate("http://10.0.2.2:18789/__openclaw__/canvas/")
81+
assertEquals("http://10.0.2.2:18789/__openclaw__/canvas/", controller.currentUrl())
82+
}
83+
84+
@Test
85+
fun nonGetMainFrameRequestsFailClosedBeforeRedirects() {
86+
assertEquals(
87+
true,
88+
CanvasNavigationPolicy.shouldBlockNonGetMainFrame("POST", isForMainFrame = true),
89+
)
90+
assertEquals(
91+
false,
92+
CanvasNavigationPolicy.shouldBlockNonGetMainFrame("GET", isForMainFrame = true),
93+
)
94+
assertEquals(
95+
false,
96+
CanvasNavigationPolicy.shouldBlockNonGetMainFrame("POST", isForMainFrame = false),
97+
)
98+
}
99+
}

0 commit comments

Comments
 (0)