Skip to content

Commit fa17485

Browse files
authored
Merge pull request #277 from OpenIPC/feat/network-web-password
feat: debug page password in Network, web port always 8085, black snapshot cells told (2.24.0)
2 parents 7f936e4 + 9f7eff8 commit fa17485

15 files changed

Lines changed: 411 additions & 17 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,21 @@ Versions after 2.17 are `MAJOR.MINOR.PATCH` (2.17 is followed by 2.17.1 or 2.18.
1212
`docs/testing.md`, "Versions and releases"); the headings below keep the numbers as they
1313
were released.
1414

15+
## 2.24.0 — 2026-11-17
16+
17+
- **Network** has a **Web page password** (the last field, empty by default): when set, the page
18+
on port 8085 and everything under it (`/stats.json`, `/snapshot.jpg`, `/log`, `/report.txt`)
19+
asks for it (HTTP Basic, any user name), from the local network and through the tunnel alike.
20+
A wrong one is answered after a second. Kept sealed, like the camera URLs (Android 6.0+); a
21+
stored password that cannot be read keeps the pages locked until it can be read again, is
22+
entered again or is removed in Network.
23+
- The **Web port** field is gone: Decoder always tells the camex server its page is on 8085 (it
24+
needs a camex server 3.19.0 or later).
25+
- The debug page's snapshot says "black in the copy: a dark picture, or video this device does
26+
not let be copied" in a live cell whose copy comes out black, instead of a black cell: on the SberBox (Amlogic) the screen
27+
shows two of four cells on hardware video planes, which neither the snapshot nor `screencap`
28+
can read; which two is up to the device.
29+
1530
## 2.23.0 — 2026-11-17
1631

1732
- **Network** takes camex 3.19.0 (`bundles/camex` moves to the 3.19.0 release): two optional

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,11 +89,11 @@ Every item, the remote, sharing a URL from another app and **Reset**: [Usage](do
8989

9090
## Network (a tunnel to the cameras)
9191

92-
Decoder has a tunnel built in, [OpenIPC camex](https://github.com/OpenIPC/camex) 3.19.0: cameras that are clients of the same camex server are watched from anywhere, without a separate VPN app. **Network** in the menu (a row under the grid) holds the server (`host:port`), the client name (the box's ID on the server), UDP or TCP, the server's public key, the pre-shared key, the server timeout, the web port for nginx on the server (a camex server 3.19.0 or later) and **On**: connect now and at every start. Off by default. The server gives the address, MTU and routes; only the tunnel network and the server's routes (none wider than a /8) go through it, the local network is reached as before. The state is shown in the dialog (Connecting, Connected with the address, VPN consent needed, Failed) and in a notification. A camera reached through the tunnel plays over TCP with Auto.
92+
Decoder has a tunnel built in, [OpenIPC camex](https://github.com/OpenIPC/camex) 3.19.0: cameras that are clients of the same camex server are watched from anywhere, without a separate VPN app. **Network** in the menu (a row under the grid) holds the server (`host:port`), the client name (the box's ID on the server), UDP or TCP, the server's public key, the pre-shared key, the server timeout, the password of the debug page and **On**: connect now and at every start. Off by default. The server gives the address, MTU and routes; only the tunnel network and the server's routes (none wider than a /8) go through it, the local network is reached as before. The state is shown in the dialog (Connecting, Connected with the address, VPN consent needed, Failed) and in a notification. A camera reached through the tunnel plays over TCP with Auto. Decoder tells the server its web page is on port 8085 (for nginx there; a camex server 3.19.0 or later). The password, when set, guards that page from the local network and through the tunnel alike; empty (the default), the page is open.
9393

9494
<p align="center">
9595
<img src="screenshots/network.jpg" alt="The Network dialog on a TV box: connected, the server and the client name" width="400">
96-
<img src="screenshots/network_more.jpg" alt="The end of the dialog: keepalive, server timeout, web port and On" width="400">
96+
<img src="screenshots/network_more.jpg" alt="The end of the dialog: keepalive, server timeout, web port and On (2.23.0)" width="400">
9797
</p>
9898

9999
The first connection asks Android for the VPN consent once (a system dialog). A device without a person at it gets the consent over adb while it is set up, with no dialog ever, and it survives reboots (no root needed):

‎README.ru.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,11 +89,11 @@
8989

9090
## Network (туннель к камерам)
9191

92-
В Decoder встроен туннель [OpenIPC camex](https://github.com/OpenIPC/camex) 3.19.0: камеры, подключённые клиентами к тому же серверу camex, видны откуда угодно, без отдельного VPN-приложения. Пункт **Network** в меню (ряд под сеткой): сервер (`host:port`), имя клиента (идентификатор приставки на сервере), UDP или TCP, открытый ключ сервера, общий ключ (psk), таймаут сервера, веб-порт для nginx на сервере (сервер camex 3.19.0 или новее) и **On** — подключиться сейчас и при каждом запуске. По умолчанию выключено. Адрес, MTU и маршруты выдаёт сервер; через туннель идут только его сеть и маршруты сервера (не шире /8), локальная сеть доступна как прежде. Состояние видно в окне (Connecting, Connected с адресом, VPN consent needed, Failed) и в уведомлении. Камера за туннелем в режиме Auto идёт по TCP.
92+
В Decoder встроен туннель [OpenIPC camex](https://github.com/OpenIPC/camex) 3.19.0: камеры, подключённые клиентами к тому же серверу camex, видны откуда угодно, без отдельного VPN-приложения. Пункт **Network** в меню (ряд под сеткой): сервер (`host:port`), имя клиента (идентификатор приставки на сервере), UDP или TCP, открытый ключ сервера, общий ключ (psk), таймаут сервера, пароль отладочной страницы и **On** — подключиться сейчас и при каждом запуске. По умолчанию выключено. Адрес, MTU и маршруты выдаёт сервер; через туннель идут только его сеть и маршруты сервера (не шире /8), локальная сеть доступна как прежде. Состояние видно в окне (Connecting, Connected с адресом, VPN consent needed, Failed) и в уведомлении. Камера за туннелем в режиме Auto идёт по TCP. Decoder сообщает серверу, что его веб-страница на порту 8085 (для nginx на сервере; нужен сервер camex 3.19.0 или новее). Пароль, если задан, закрывает эту страницу одинаково из локальной сети и через туннель; пустой (по умолчанию) — страница открыта.
9393

9494
<p align="center">
9595
<img src="screenshots/network.jpg" alt="Окно Network на ТВ-приставке: подключено, сервер и имя клиента" width="400">
96-
<img src="screenshots/network_more.jpg" alt="Конец окна: keepalive, таймаут сервера, веб-порт и On" width="400">
96+
<img src="screenshots/network_more.jpg" alt="Конец окна: keepalive, таймаут сервера, веб-порт и On (2.23.0)" width="400">
9797
</p>
9898

9999
При первом подключении Android один раз спрашивает согласие на VPN (системное окно). Устройству без человека рядом согласие дают через adb при настройке, без окна; оно сохраняется после перезагрузки (root не нужен):

‎README.zh-CN.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,11 +89,11 @@
8989

9090
## Network(通往摄像头的隧道)
9191

92-
Decoder 内置 [OpenIPC camex](https://github.com/OpenIPC/camex) 3.19.0 隧道:作为客户端接入同一台 camex 服务器的摄像头,可以在任何地方观看,无需另装 VPN 应用。菜单中的 **Network**(网格下方一行)包含:服务器(`host:port`)、客户端名称(设备在服务器上的 ID)、UDP 或 TCP、服务器公钥、预共享密钥、服务器超时、供服务器上 nginx 使用的 Web 端口(需 camex 服务器 3.19.0 或更新版本),以及 **On**:立即连接并在每次启动时连接。默认关闭。地址、MTU 和路由由服务器下发;只有隧道网络和服务器的路由(不宽于 /8)经过隧道,本地网络照常访问。状态显示在对话框(Connecting、Connected 及地址、VPN consent needed、Failed)和通知中。经隧道访问的摄像头在 Auto 模式下走 TCP。
92+
Decoder 内置 [OpenIPC camex](https://github.com/OpenIPC/camex) 3.19.0 隧道:作为客户端接入同一台 camex 服务器的摄像头,可以在任何地方观看,无需另装 VPN 应用。菜单中的 **Network**(网格下方一行)包含:服务器(`host:port`)、客户端名称(设备在服务器上的 ID)、UDP 或 TCP、服务器公钥、预共享密钥、服务器超时、调试页面密码,以及 **On**:立即连接并在每次启动时连接。默认关闭。地址、MTU 和路由由服务器下发;只有隧道网络和服务器的路由(不宽于 /8)经过隧道,本地网络照常访问。状态显示在对话框(Connecting、Connected 及地址、VPN consent needed、Failed)和通知中。经隧道访问的摄像头在 Auto 模式下走 TCP。Decoder 告知服务器其网页位于 8085 端口(供服务器上的 nginx 使用;需 camex 服务器 3.19.0 或更新版本)。设置密码后,无论从本地网络还是经隧道访问,该页面都需要密码;为空(默认)时页面开放。
9393

9494
<p align="center">
9595
<img src="screenshots/network.jpg" alt="电视盒子上的 Network 对话框:已连接、服务器和客户端名称" width="400">
96-
<img src="screenshots/network_more.jpg" alt="对话框末尾:keepalive、服务器超时、Web 端口和 On" width="400">
96+
<img src="screenshots/network_more.jpg" alt="对话框末尾:keepalive、服务器超时、Web 端口和 On(2.23.0)" width="400">
9797
</p>
9898

9999
首次连接时 Android 会请求一次 VPN 授权(系统对话框)。无人值守的设备可在部署时通过 adb 授权,不弹对话框,重启后仍然有效(无需 root):

‎android/app/build.gradle‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ android {
2626
applicationId "com.openipc.decoder"
2727
minSdk 21
2828
targetSdk 36
29-
versionCode 56
30-
versionName "2.23.0"
29+
versionCode 57
30+
versionName "2.24.0"
3131
// Keep only these locales of the libraries' resources, as in the other OpenIPC apps
3232
resourceConfigurations += ['en', 'ru', 'zh-rCN']
3333

‎android/app/src/main/java/com/openipc/decoder/DebugServer.java‎

Lines changed: 103 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,9 @@
3232
/**
3333
* Serves what the decoder knows about itself on port 8085, for a browser or curl:
3434
* {@code /} a page refreshing itself, {@code /stats.json} the same as JSON, {@code /log} the
35-
* app's recent log, {@code /report.txt} both in one file to download (#207). Always on; a client outside the local network gets 403. GET only, one
35+
* app's recent log, {@code /report.txt} both in one file to download (#207). Always on; a client outside the local network gets 403. With a password set in
36+
* Network, every request needs it (HTTP Basic, any user name), from the local network and the
37+
* tunnel alike; without one the pages are open, as before. GET only, one
3638
* request per connection, short timeouts and a few workers: it must never get in the way of
3739
* decoding. Logins and passwords never leave the device (redacted like the log, #55).
3840
*/
@@ -52,6 +54,8 @@ final class DebugServer {
5254
private static final long REBIND_DELAY_MS = 10_000;
5355
/** A snapshot this young is served again: several viewers cost one capture (#98). */
5456
private static final long SNAPSHOT_REUSE_MS = 1000;
57+
/** The answer to a wrong password waits this long: about two guesses a second at most. */
58+
private static final long WRONG_PASSWORD_DELAY_MS = 1000;
5559

5660
/** What the server reports; called on a server thread. */
5761
interface Source {
@@ -167,8 +171,24 @@ private void handle(Socket s) {
167171
reply(out, 403, "text/plain", "Forbidden: local network only\n");
168172
return;
169173
}
170-
String requestLine = readRequestHead(socket.getInputStream());
174+
StringBuilder headers = new StringBuilder();
175+
String requestLine = readRequestHead(socket.getInputStream(), headers);
171176
if (requestLine == null) return;
177+
if (!authorized(headers.toString(), WebPassword.get())) {
178+
// a wrong password (not the browser's first try without one) costs a second:
179+
// guessing goes slowly
180+
if (hasAuthorization(headers.toString())) {
181+
try {
182+
Thread.sleep(WRONG_PASSWORD_DELAY_MS);
183+
} catch (InterruptedException e) {
184+
Thread.currentThread().interrupt();
185+
return;
186+
}
187+
}
188+
reply(out, 401, "text/plain", "Password needed\n".getBytes(StandardCharsets.UTF_8),
189+
"WWW-Authenticate: Basic realm=\"OpenIPC Decoder\", charset=\"UTF-8\"\r\n");
190+
return;
191+
}
172192
String[] parts = requestLine.split(" ");
173193
if (parts.length < 2) {
174194
reply(out, 400, "text/plain", "Bad request\n");
@@ -332,6 +352,11 @@ private byte[] snapshotJpeg(boolean labels) {
332352

333353
/** The request line; the headers are read and dropped. Null on a closed connection. */
334354
static String readRequestHead(InputStream in) throws IOException {
355+
return readRequestHead(in, null);
356+
}
357+
358+
/** The request line; the header lines after it go to {@code headers}, when given. */
359+
static String readRequestHead(InputStream in, StringBuilder headers) throws IOException {
335360
ByteArrayOutputStream head = new ByteArrayOutputStream();
336361
int matched = 0;
337362
while (head.size() < MAX_HEADER_BYTES) {
@@ -348,9 +373,84 @@ static String readRequestHead(InputStream in) throws IOException {
348373
String text = head.toString("ISO-8859-1");
349374
int eol = text.indexOf('\n');
350375
String line = (eol >= 0 ? text.substring(0, eol) : text).trim();
376+
if (headers != null && eol >= 0) headers.append(text.substring(eol + 1));
351377
return line.isEmpty() ? null : line;
352378
}
353379

380+
/**
381+
* Whether a request with these header lines may be served: always without a password
382+
* (empty), never when the stored one cannot be read (null: locked until it is entered again
383+
* in Network), otherwise when its Basic credentials carry the password, whatever the user
384+
* name (the browser asks for both).
385+
*/
386+
static boolean authorized(String headers, String password) {
387+
if (password == null) return false;
388+
if (password.isEmpty()) return true;
389+
for (String line : headers.split("\n")) {
390+
int colon = line.indexOf(':');
391+
if (colon < 0 || !line.substring(0, colon).trim().equalsIgnoreCase("Authorization")) {
392+
continue;
393+
}
394+
String value = line.substring(colon + 1).trim();
395+
int space = value.indexOf(' ');
396+
if (space < 0 || !value.substring(0, space).equalsIgnoreCase("Basic")) return false;
397+
byte[] pair = base64(value.substring(space + 1).trim());
398+
if (pair == null) return false;
399+
String userPass = new String(pair, StandardCharsets.UTF_8);
400+
int sep = userPass.indexOf(':');
401+
if (sep < 0) return false;
402+
// the same time for a wrong password of any length
403+
return java.security.MessageDigest.isEqual(
404+
sha256(userPass.substring(sep + 1)), sha256(password));
405+
}
406+
return false;
407+
}
408+
409+
/** Whether the request carries an Authorization header. */
410+
static boolean hasAuthorization(String headers) {
411+
for (String line : headers.split("\n")) {
412+
int colon = line.indexOf(':');
413+
if (colon > 0 && line.substring(0, colon).trim().equalsIgnoreCase("Authorization")) {
414+
return true;
415+
}
416+
}
417+
return false;
418+
}
419+
420+
private static byte[] sha256(String s) {
421+
try {
422+
return java.security.MessageDigest.getInstance("SHA-256")
423+
.digest(s.getBytes(StandardCharsets.UTF_8));
424+
} catch (java.security.NoSuchAlgorithmException e) {
425+
throw new IllegalStateException(e);
426+
}
427+
}
428+
429+
/**
430+
* Standard base64 with or without padding, null when it is not base64 (java.util.Base64
431+
* needs API 26, android.util.Base64 is a stub in the unit tests).
432+
*/
433+
static byte[] base64(String s) {
434+
final String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
435+
int end = s.length();
436+
while (end > 0 && s.charAt(end - 1) == '=') end--;
437+
if (s.length() - end > 2) return null;
438+
ByteArrayOutputStream out = new ByteArrayOutputStream();
439+
int bits = 0, n = 0;
440+
for (int i = 0; i < end; i++) {
441+
int d = abc.indexOf(s.charAt(i));
442+
if (d < 0) return null;
443+
bits = (bits << 6) | d;
444+
n += 6;
445+
if (n >= 8) {
446+
n -= 8;
447+
out.write((bits >> n) & 0xFF);
448+
}
449+
}
450+
if (n >= 6) return null; // a lone last character carries no byte
451+
return out.toByteArray();
452+
}
453+
354454
private static void reply(OutputStream out, int code, String type, String body)
355455
throws IOException {
356456
reply(out, code, type, body.getBytes(StandardCharsets.UTF_8));
@@ -380,6 +480,7 @@ private static String reason(int code) {
380480
switch (code) {
381481
case 200: return "OK";
382482
case 400: return "Bad Request";
483+
case 401: return "Unauthorized";
383484
case 403: return "Forbidden";
384485
case 404: return "Not Found";
385486
case 405: return "Method Not Allowed";

0 commit comments

Comments
 (0)