diff --git a/CHANGELOG.md b/CHANGELOG.md index 52e0b1a..bcf90b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,21 @@ Versions after 2.17 are `MAJOR.MINOR.PATCH` (2.17 is followed by 2.17.1 or 2.18. `docs/testing.md`, "Versions and releases"); the headings below keep the numbers as they were released. +## 2.24.0 — 2026-11-17 + +- **Network** has a **Web page password** (the last field, empty by default): when set, the page + on port 8085 and everything under it (`/stats.json`, `/snapshot.jpg`, `/log`, `/report.txt`) + asks for it (HTTP Basic, any user name), from the local network and through the tunnel alike. + A wrong one is answered after a second. Kept sealed, like the camera URLs (Android 6.0+); a + stored password that cannot be read keeps the pages locked until it can be read again, is + entered again or is removed in Network. +- The **Web port** field is gone: Decoder always tells the camex server its page is on 8085 (it + needs a camex server 3.19.0 or later). +- The debug page's snapshot says "black in the copy: a dark picture, or video this device does + not let be copied" in a live cell whose copy comes out black, instead of a black cell: on the SberBox (Amlogic) the screen + shows two of four cells on hardware video planes, which neither the snapshot nor `screencap` + can read; which two is up to the device. + ## 2.23.0 — 2026-11-17 - **Network** takes camex 3.19.0 (`bundles/camex` moves to the 3.19.0 release): two optional diff --git a/README.md b/README.md index 6abd191..b295d84 100644 --- a/README.md +++ b/README.md @@ -89,11 +89,11 @@ Every item, the remote, sharing a URL from another app and **Reset**: [Usage](do ## Network (a tunnel to the cameras) -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. +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.

The Network dialog on a TV box: connected, the server and the client name - The end of the dialog: keepalive, server timeout, web port and On + The end of the dialog: keepalive, server timeout, web port and On (2.23.0)

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): diff --git a/README.ru.md b/README.ru.md index b4de5f5..7617e54 100644 --- a/README.ru.md +++ b/README.ru.md @@ -89,11 +89,11 @@ ## Network (туннель к камерам) -В 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. +В 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 или новее). Пароль, если задан, закрывает эту страницу одинаково из локальной сети и через туннель; пустой (по умолчанию) — страница открыта.

Окно Network на ТВ-приставке: подключено, сервер и имя клиента - Конец окна: keepalive, таймаут сервера, веб-порт и On + Конец окна: keepalive, таймаут сервера, веб-порт и On (2.23.0)

При первом подключении Android один раз спрашивает согласие на VPN (системное окно). Устройству без человека рядом согласие дают через adb при настройке, без окна; оно сохраняется после перезагрузки (root не нужен): diff --git a/README.zh-CN.md b/README.zh-CN.md index 12b4bac..267aff6 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -89,11 +89,11 @@ ## Network(通往摄像头的隧道) -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。 +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 或更新版本)。设置密码后,无论从本地网络还是经隧道访问,该页面都需要密码;为空(默认)时页面开放。

电视盒子上的 Network 对话框:已连接、服务器和客户端名称 - 对话框末尾:keepalive、服务器超时、Web 端口和 On + 对话框末尾:keepalive、服务器超时、Web 端口和 On(2.23.0)

首次连接时 Android 会请求一次 VPN 授权(系统对话框)。无人值守的设备可在部署时通过 adb 授权,不弹对话框,重启后仍然有效(无需 root): diff --git a/android/app/build.gradle b/android/app/build.gradle index f7e9b32..4b368ae 100755 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -26,8 +26,8 @@ android { applicationId "com.openipc.decoder" minSdk 21 targetSdk 36 - versionCode 56 - versionName "2.23.0" + versionCode 57 + versionName "2.24.0" // Keep only these locales of the libraries' resources, as in the other OpenIPC apps resourceConfigurations += ['en', 'ru', 'zh-rCN'] diff --git a/android/app/src/main/java/com/openipc/decoder/DebugServer.java b/android/app/src/main/java/com/openipc/decoder/DebugServer.java index 9423405..71680bf 100644 --- a/android/app/src/main/java/com/openipc/decoder/DebugServer.java +++ b/android/app/src/main/java/com/openipc/decoder/DebugServer.java @@ -32,7 +32,9 @@ /** * Serves what the decoder knows about itself on port 8085, for a browser or curl: * {@code /} a page refreshing itself, {@code /stats.json} the same as JSON, {@code /log} the - * 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 + * 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 + * Network, every request needs it (HTTP Basic, any user name), from the local network and the + * tunnel alike; without one the pages are open, as before. GET only, one * request per connection, short timeouts and a few workers: it must never get in the way of * decoding. Logins and passwords never leave the device (redacted like the log, #55). */ @@ -52,6 +54,8 @@ final class DebugServer { private static final long REBIND_DELAY_MS = 10_000; /** A snapshot this young is served again: several viewers cost one capture (#98). */ private static final long SNAPSHOT_REUSE_MS = 1000; + /** The answer to a wrong password waits this long: about two guesses a second at most. */ + private static final long WRONG_PASSWORD_DELAY_MS = 1000; /** What the server reports; called on a server thread. */ interface Source { @@ -167,8 +171,24 @@ private void handle(Socket s) { reply(out, 403, "text/plain", "Forbidden: local network only\n"); return; } - String requestLine = readRequestHead(socket.getInputStream()); + StringBuilder headers = new StringBuilder(); + String requestLine = readRequestHead(socket.getInputStream(), headers); if (requestLine == null) return; + if (!authorized(headers.toString(), WebPassword.get())) { + // a wrong password (not the browser's first try without one) costs a second: + // guessing goes slowly + if (hasAuthorization(headers.toString())) { + try { + Thread.sleep(WRONG_PASSWORD_DELAY_MS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + reply(out, 401, "text/plain", "Password needed\n".getBytes(StandardCharsets.UTF_8), + "WWW-Authenticate: Basic realm=\"OpenIPC Decoder\", charset=\"UTF-8\"\r\n"); + return; + } String[] parts = requestLine.split(" "); if (parts.length < 2) { reply(out, 400, "text/plain", "Bad request\n"); @@ -332,6 +352,11 @@ private byte[] snapshotJpeg(boolean labels) { /** The request line; the headers are read and dropped. Null on a closed connection. */ static String readRequestHead(InputStream in) throws IOException { + return readRequestHead(in, null); + } + + /** The request line; the header lines after it go to {@code headers}, when given. */ + static String readRequestHead(InputStream in, StringBuilder headers) throws IOException { ByteArrayOutputStream head = new ByteArrayOutputStream(); int matched = 0; while (head.size() < MAX_HEADER_BYTES) { @@ -348,9 +373,84 @@ static String readRequestHead(InputStream in) throws IOException { String text = head.toString("ISO-8859-1"); int eol = text.indexOf('\n'); String line = (eol >= 0 ? text.substring(0, eol) : text).trim(); + if (headers != null && eol >= 0) headers.append(text.substring(eol + 1)); return line.isEmpty() ? null : line; } + /** + * Whether a request with these header lines may be served: always without a password + * (empty), never when the stored one cannot be read (null: locked until it is entered again + * in Network), otherwise when its Basic credentials carry the password, whatever the user + * name (the browser asks for both). + */ + static boolean authorized(String headers, String password) { + if (password == null) return false; + if (password.isEmpty()) return true; + for (String line : headers.split("\n")) { + int colon = line.indexOf(':'); + if (colon < 0 || !line.substring(0, colon).trim().equalsIgnoreCase("Authorization")) { + continue; + } + String value = line.substring(colon + 1).trim(); + int space = value.indexOf(' '); + if (space < 0 || !value.substring(0, space).equalsIgnoreCase("Basic")) return false; + byte[] pair = base64(value.substring(space + 1).trim()); + if (pair == null) return false; + String userPass = new String(pair, StandardCharsets.UTF_8); + int sep = userPass.indexOf(':'); + if (sep < 0) return false; + // the same time for a wrong password of any length + return java.security.MessageDigest.isEqual( + sha256(userPass.substring(sep + 1)), sha256(password)); + } + return false; + } + + /** Whether the request carries an Authorization header. */ + static boolean hasAuthorization(String headers) { + for (String line : headers.split("\n")) { + int colon = line.indexOf(':'); + if (colon > 0 && line.substring(0, colon).trim().equalsIgnoreCase("Authorization")) { + return true; + } + } + return false; + } + + private static byte[] sha256(String s) { + try { + return java.security.MessageDigest.getInstance("SHA-256") + .digest(s.getBytes(StandardCharsets.UTF_8)); + } catch (java.security.NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + /** + * Standard base64 with or without padding, null when it is not base64 (java.util.Base64 + * needs API 26, android.util.Base64 is a stub in the unit tests). + */ + static byte[] base64(String s) { + final String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + int end = s.length(); + while (end > 0 && s.charAt(end - 1) == '=') end--; + if (s.length() - end > 2) return null; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int bits = 0, n = 0; + for (int i = 0; i < end; i++) { + int d = abc.indexOf(s.charAt(i)); + if (d < 0) return null; + bits = (bits << 6) | d; + n += 6; + if (n >= 8) { + n -= 8; + out.write((bits >> n) & 0xFF); + } + } + if (n >= 6) return null; // a lone last character carries no byte + return out.toByteArray(); + } + private static void reply(OutputStream out, int code, String type, String body) throws IOException { reply(out, code, type, body.getBytes(StandardCharsets.UTF_8)); @@ -380,6 +480,7 @@ private static String reason(int code) { switch (code) { case 200: return "OK"; case 400: return "Bad Request"; + case 401: return "Unauthorized"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; diff --git a/android/app/src/main/java/com/openipc/decoder/NetworkPanel.java b/android/app/src/main/java/com/openipc/decoder/NetworkPanel.java index 29be055..b93d923 100644 --- a/android/app/src/main/java/com/openipc/decoder/NetworkPanel.java +++ b/android/app/src/main/java/com/openipc/decoder/NetworkPanel.java @@ -37,6 +37,8 @@ * The camex tunnel (the library of bundles/camex): the Network screen is built from its fields, * the values are kept in Decoder's settings as {@code tunnel_camex_} (the psk sealed with * {@link CredentialStore}), and {@code tunnel_on} connects now and at every start of the app. + * The web port is not asked: it is always the debug page's {@link DebugServer#PORT}. The same + * dialog holds the password of that page ({@link WebPassword}). * Android's VPN consent: a person confirms the system dialog once; a box without a person gets * it while it is prepared: adb shell appops set com.openipc.decoder ACTIVATE_VPN allow. */ @@ -69,6 +71,7 @@ private static Map load(Context c, Map unreadabl Map v = new HashMap<>(); CredentialStore store = null; for (Field f : CamexTunnel.fields()) { + if (fixed(f)) continue; String stored = prefs(c).getString(PREFIX + f.key, null); String s = stored; if (s != null && f.kind == Field.Kind.SECRET && !s.isEmpty()) { @@ -81,14 +84,22 @@ private static Map load(Context c, Map unreadabl } v.put(f.key, s != null ? s : f.initial); } + // nginx on the server reaches the box's web page there (camex 3.19.0, needs that server) + v.put(CamexTunnel.WEB_PORT, String.valueOf(DebugServer.PORT)); return v; } + /** A field of the library that Decoder sets itself, not shown: the web port. */ + private static boolean fixed(Field f) { + return CamexTunnel.WEB_PORT.equals(f.key); + } + private static void save(Context c, Map v, Map unreadable, boolean on) { SharedPreferences.Editor e = prefs(c).edit(); CredentialStore store = CredentialStore.create(); for (Field f : CamexTunnel.fields()) { + if (fixed(f)) continue; String s = v.get(f.key); if (f.kind == Field.Kind.SECRET) { // an unreadable secret left as the form showed it (empty) is kept as it was @@ -230,6 +241,7 @@ static void show(Activity a) { content.addView(state); Map views = new HashMap<>(); for (Field f : CamexTunnel.fields()) { + if (fixed(f)) continue; String v = values.get(f.key); View view; switch (f.kind) { @@ -266,6 +278,20 @@ static void show(Activity a) { content.addView(view); views.put(f.key, view); } + // the web page on port 8085, from the local network and the tunnel alike + String webPassword = WebPassword.read(a); + final String keepWebPassword = webPassword == null ? WebPassword.stored(a) : null; + content.addView(label(a, webPassword != null + ? "Web page password (port " + DebugServer.PORT + "; empty: open)" + : "Web page password: the stored one cannot be read, the page is locked;" + + " enter it again or a new one")); + EditText web = field(a, webPassword != null ? webPassword : "", + InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); + content.addView(web); + // only then: a way back to an open page (an empty field keeps the unreadable one) + CheckBox removeWeb = keepWebPassword != null + ? check(a, "Remove the stored password: the page is open", false) : null; + if (removeWeb != null) content.addView(removeWeb); CheckBox on = check(a, "On: connect now and at every start", isOn(a)); content.addView(on); @@ -311,6 +337,8 @@ protected void onMeasure(int widthSpec, int heightSpec) { return; } save(a, n, unreadable, on.isChecked()); + WebPassword.save(a, web.getText().toString(), + removeWeb != null && removeWeb.isChecked() ? null : keepWebPassword); // on: (re)connect with the saved values (a running tunnel restarts); off: stop if (on.isChecked()) connect(a); else CamexTunnel.stop(); diff --git a/android/app/src/main/java/com/openipc/decoder/Snapshots.java b/android/app/src/main/java/com/openipc/decoder/Snapshots.java index 1b89ef0..1a4a345 100644 --- a/android/app/src/main/java/com/openipc/decoder/Snapshots.java +++ b/android/app/src/main/java/com/openipc/decoder/Snapshots.java @@ -164,13 +164,21 @@ static byte[] render(List cells, int side, int width, boolean labels) { int x = r.left, y = r.top, cw = r.width(), ch = r.height(); Bitmap frame = copies[i] != null ? copies[i].await(deadline) : null; if (copies[i] != null && frame != null) copied++; - boolean shown = c.live && frame != null; + // A copy that came out black: a dark picture, or (more likely) video the screen + // shows on a hardware plane no copy can read (two of four cells on the SberBox) + boolean blank = c.live && frame != null && blank(frame); + boolean shown = c.live && frame != null && !blank; if (shown) { canvas.drawBitmap(frame, null, dst[i], frames); } if (frame != null) frame.recycle(); + if (blank) { + // the page draws its labels over the picture, but cannot know this: said always + drawNote(canvas, NOT_COPIED, x, y, cw, ch, text); + } if (labels) { - drawLabel(canvas, c, shown, x, y, cw, ch, bandH, text, band); + if (!blank) drawLabel(canvas, c, shown, x, y, cw, ch, bandH, text, band); + else drawBand(canvas, c, x, y, cw, ch, bandH, text, band); canvas.drawRect(x, y, x + cw, y + 1, grid); canvas.drawRect(x, y, x + 1, y + ch, grid); if (c.onScreen && side > 1) { @@ -195,6 +203,61 @@ static byte[] render(List cells, int side, int width, boolean labels) { return jpeg.toByteArray(); } + /** Said in a cell whose copy came out black. */ + static final String NOT_COPIED = + "black in the copy: a dark picture, or video this device does not let be copied"; + + /** + * Whether a copied frame is black all over: at least 98 % of a sample of its pixels darker + * than 9 of 255 in every channel. A camera's picture, even at night, stays far below that + * (at most about 20 % on the lab's cameras); a copy of a hardware video plane is 99.5 %. + */ + static boolean blank(Bitmap b) { + int w = b.getWidth(), h = b.getHeight(); + if (w <= 0 || h <= 0) return false; + int stepX = Math.max(1, w / 64), stepY = Math.max(1, h / 64); + int n = 0, dark = 0; + for (int y = stepY / 2; y < h; y += stepY) { + for (int x = stepX / 2; x < w; x += stepX) { + n++; + if (dark(b.getPixel(x, y))) dark++; + } + } + return blank(dark, n); + } + + /** {@code dark} of {@code n} sampled pixels make a black frame. */ + static boolean blank(int dark, int n) { + return n > 0 && dark * 100L >= n * 98L; + } + + /** Darker than 9 of 255 in every channel. */ + static boolean dark(int argb) { + return ((argb >> 16) & 0xFF) <= 8 && ((argb >> 8) & 0xFF) <= 8 && (argb & 0xFF) <= 8; + } + + private static void drawNote(Canvas canvas, String note, int x, int y, int cw, int ch, + TextPaint text) { + float size = text.getTextSize(); + text.setTextSize(Math.max(12, size * 0.6f)); // a sentence, not a label + String line = TextUtils.ellipsize(note, text, cw - 8, TextUtils.TruncateAt.END).toString(); + text.setColor(0xFFB0B0B0); + float w = text.measureText(line); + canvas.drawText(line, x + Math.max(4, (cw - w) / 2), y + (ch + text.getTextSize()) / 2f, + text); + text.setTextSize(size); + } + + /** The cell's own label in the band at its bottom. */ + private static void drawBand(Canvas canvas, Cell c, int x, int y, int cw, int ch, int bandH, + TextPaint text, Paint band) { + String full = (c.slot > 0 ? c.slot + " \u00b7 " : "") + (c.label != null ? c.label : ""); + String label = TextUtils.ellipsize(full, text, cw - 8, TextUtils.TruncateAt.END).toString(); + canvas.drawRect(x, y + ch - bandH, x + cw, y + ch, band); + text.setColor(Color.WHITE); + canvas.drawText(label, x + 4, y + ch - 6, text); + } + private static void drawLabel(Canvas canvas, Cell c, boolean shown, int x, int y, int cw, int ch, int bandH, TextPaint text, Paint band) { String full = (c.slot > 0 ? c.slot + " \u00b7 " : "") + (c.label != null ? c.label : ""); diff --git a/android/app/src/main/java/com/openipc/decoder/WebPassword.java b/android/app/src/main/java/com/openipc/decoder/WebPassword.java new file mode 100644 index 0000000..58b2fc7 --- /dev/null +++ b/android/app/src/main/java/com/openipc/decoder/WebPassword.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) OpenIPC https://openipc.org Prosperity Public License 3.0.0 + * + * WebPassword.java — the password of the web page on port 8085, set in Network + * + */ + +package com.openipc.decoder; + +import android.content.Context; +import android.content.SharedPreferences; +import android.util.Log; + +/** + * The password {@link DebugServer} asks for, the same from the local network and the tunnel. + * Empty (the default): the pages are open. Kept sealed with {@link CredentialStore}, like the + * camera URLs and the psk (Android 6.0+; on 5.x, as those, it is stored as it is). Read by + * the server itself, so it holds from the first request, before any activity has started. + */ +final class WebPassword { + private static final String TAG = "OpenIPCDecoder"; + private static final String PREFS = "settings"; + static final String KEY = "web_password"; + + private static final Object lock = new Object(); + private static boolean loaded; + /** When an unreadable password was last tried: tried again after a while, not each time. */ + private static long triedMs; + private static final long RETRY_MS = 5000; + /** "" none, null stored but unreadable (the pages stay locked until it is entered again). */ + private static String cached; + + private WebPassword() { + } + + private static SharedPreferences prefs(Context c) { + return c.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } + + /** The password the server checks: "" none, null stored but unreadable. */ + static String get() { + synchronized (lock) { + long now = android.os.SystemClock.elapsedRealtime(); + // unreadable may be for now only (the Keystore early after a boot): tried again + if (!loaded || (cached == null && now - triedMs >= RETRY_MS)) { + Context c = App.context; + if (c == null) return null; // too early to know: nothing is served + cached = read(c); + loaded = true; + triedMs = now; + } + return cached; + } + } + + /** The stored value, opened: "" none, null stored but unreadable. */ + static String read(Context c) { + String stored = prefs(c).getString(KEY, ""); + if (stored == null || stored.isEmpty()) return ""; + String open = CredentialStore.create().open(stored); + if (open == null) Log.w(TAG, "Network: the web page password cannot be read, enter it again"); + return open; + } + + /** The sealed value as stored, for a Save that keeps an unreadable one. */ + static String stored(Context c) { + return prefs(c).getString(KEY, ""); + } + + /** + * Saves {@code password} ("" removes it); {@code keepStored}: an unreadable stored value + * the form left empty, kept as it is (null with {@code password} empty: removed). + */ + static void save(Context c, String password, String keepStored) { + String value; + if (password == null || password.isEmpty()) { + value = keepStored != null ? keepStored : ""; + } else { + value = CredentialStore.create().seal(password); + } + prefs(c).edit().putString(KEY, value).apply(); + synchronized (lock) { + cached = value.isEmpty() ? "" : (keepStored != null && value.equals(keepStored) + ? null : password); + loaded = true; + } + } +} diff --git a/android/app/src/test/java/com/openipc/decoder/DebugServerTest.java b/android/app/src/test/java/com/openipc/decoder/DebugServerTest.java index c1fdb45..b4767c5 100644 --- a/android/app/src/test/java/com/openipc/decoder/DebugServerTest.java +++ b/android/app/src/test/java/com/openipc/decoder/DebugServerTest.java @@ -289,4 +289,70 @@ public void pageLinksTheReport() throws IOException { assertTrue(page.contains("href=\"/report.txt\"")); assertFalse(page.substring(page.indexOf("\r\n\r\n") + 4).contains("\n")); } + + // ====================== Web page password ====================== + + private static String basic(String userPass) { + return "Authorization: Basic " + java.util.Base64.getEncoder() + .encodeToString(userPass.getBytes(StandardCharsets.UTF_8)) + "\r\n"; + } + + @Test + public void withoutPasswordEverythingIsOpen() { + assertTrue(DebugServer.authorized("Host: box\r\n", "")); + assertTrue(DebugServer.authorized(basic("a:b"), "")); + } + + @Test + public void passwordNeedsBasicCredentials() { + String pw = "s3cret:with colon"; + assertFalse(DebugServer.authorized("Host: box\r\n", pw)); + assertTrue(DebugServer.authorized("Host: box\r\n" + basic("admin:" + pw), pw)); + // any user name, even none + assertTrue(DebugServer.authorized(basic(":" + pw), pw)); + // the header name and the scheme in any case + assertTrue(DebugServer.authorized(basic("anyone:" + pw) + .replace("Authorization: Basic", "AUTHORIZATION: basic"), pw)); + assertFalse(DebugServer.authorized(basic("admin:wrong"), pw)); + assertFalse(DebugServer.authorized(basic("admin:" + pw + "x"), pw)); + assertFalse(DebugServer.authorized(basic("no colon"), pw)); + assertFalse(DebugServer.authorized("Authorization: Bearer abc\r\n", pw)); + assertFalse(DebugServer.authorized("Authorization: Basic ***\r\n", pw)); + // a non-ASCII password, as the browser sends it with charset="UTF-8" + assertTrue(DebugServer.authorized(basic("u:пароль"), "пароль")); + } + + @Test + public void onlyAWrongPasswordIsSlowedDown() { + assertFalse(DebugServer.hasAuthorization("Host: box\r\nAccept: */*\r\n")); + assertTrue(DebugServer.hasAuthorization("Host: box\r\n" + basic("u:p"))); + assertTrue(DebugServer.hasAuthorization("authorization: Basic xx\r\n")); + } + + @Test + public void unreadablePasswordLocksThePages() { + assertFalse(DebugServer.authorized("Host: box\r\n", null)); + assertFalse(DebugServer.authorized(basic("a:"), null)); + } + + @Test + public void base64WithAndWithoutPadding() { + assertEquals("a:b", new String(DebugServer.base64("YTpi"), StandardCharsets.UTF_8)); + assertEquals("ab", new String(DebugServer.base64("YWI="), StandardCharsets.UTF_8)); + assertEquals("ab", new String(DebugServer.base64("YWI"), StandardCharsets.UTF_8)); + assertEquals("a", new String(DebugServer.base64("YQ=="), StandardCharsets.UTF_8)); + assertNull(DebugServer.base64("Y")); + assertNull(DebugServer.base64("YQ===")); + assertNull(DebugServer.base64("a b")); + } + + @Test + public void headerLinesAfterTheRequestLine() throws IOException { + StringBuilder h = new StringBuilder(); + assertEquals("GET / HTTP/1.1", DebugServer.readRequestHead(new ByteArrayInputStream( + ("GET / HTTP/1.1\r\nHost: box\r\n" + basic("u:p") + "\r\n") + .getBytes(StandardCharsets.ISO_8859_1)), h)); + assertTrue(h.toString(), DebugServer.authorized(h.toString(), "p")); + assertFalse(DebugServer.authorized(h.toString(), "q")); + } } diff --git a/android/app/src/test/java/com/openipc/decoder/SnapshotsTest.java b/android/app/src/test/java/com/openipc/decoder/SnapshotsTest.java index 196f680..5ddb0ed 100644 --- a/android/app/src/test/java/com/openipc/decoder/SnapshotsTest.java +++ b/android/app/src/test/java/com/openipc/decoder/SnapshotsTest.java @@ -8,6 +8,8 @@ package com.openipc.decoder; import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.Test; @@ -34,4 +36,19 @@ public void fitPutsBarsAboveAndBelowAWiderPicture() { // 32:9 in a 16:9 cell assertArrayEquals(new int[] {0, 90, 640, 270}, Snapshots.fit(0, 0, 640, 360, 32f / 9)); } + + @Test + public void aBlackCopyIsTold() { + // 99.5 % dark: a hardware video plane copied on the SberBox + assertTrue(Snapshots.blank(4076, 4096)); + assertTrue(Snapshots.blank(98, 100)); + // a camera at night: about 18 % dark + assertFalse(Snapshots.blank(737, 4096)); + assertFalse(Snapshots.blank(97, 100)); + assertFalse(Snapshots.blank(0, 0)); + assertTrue(Snapshots.dark(0xFF000000)); + assertTrue(Snapshots.dark(0xFF080808)); + assertFalse(Snapshots.dark(0xFF000009)); + assertFalse(Snapshots.dark(0xFF102030)); + } } diff --git a/docs/debug.md b/docs/debug.md index 0a7bbc3..8ba55de 100644 --- a/docs/debug.md +++ b/docs/debug.md @@ -23,7 +23,7 @@ While the app runs it serves its debug information over HTTP on port **8085**, f | `/report.txt` | a header, `/stats.json` and `/log` in one file, downloaded as `report-YYYYMMDD-HHMMSS.txt`, see [Save report](#save-report) | | `/jieli-frame.jpg`, `/jieli-dropped.bin` | the last JPEG of a `jieli://` slot in the single view as the toy sent it, and the last frame that could not be put together ([toys.md](toys.md#hf--jieli-toys)) | -- Only clients on the local network are answered; others get `403`. The rule and what is hidden: [security.md](security.md#debug-server). +- Only clients on the local network are answered; others get `403`. With a password set in **Network** (**Web page password**) the browser asks for it (any user name; `curl -u :`). The rule and what is hidden: [security.md](security.md#debug-server). - `GET` only (`405` otherwise), one request per connection, `Cache-Control: no-store`. - Two worker threads at background priority, a short queue, a 20 s deadline per request: the server never gets in the way of decoding; a busy server drops the connection. - If port 8085 is taken, the server retries every 10 s; `server` in `/stats.json` says why. @@ -61,6 +61,8 @@ The device's addresses are in `addresses` of `/stats.json`, and the [U cell](usa A JPEG laid out like the screen, at the screen's resolution (at most 1920 wide, at least 640), made from the frames the app shows now. A cell without video is black with its status. With labels (the default) the text of each cell is drawn in; `?labels=0` gives the frames only, which is what the page uses. It is taken only when asked for and reused for 1 s, so several viewers cost one capture. `503` when there is nothing to show. Needs Android 7.0+ (PixelCopy). +A device may show some cells on a hardware video plane that no copy can read (on the SberBox, Amlogic, two of four cells, which two is up to the device; `adb shell screencap` sees them black too). Such a cell, live on the screen but black in the copy, says *black in the copy: a dark picture, or video this device does not let be copied*, labels or not. + ## Stream checks in the single view In the single view (and the U view) the page and the snapshot still show the whole grid ([#100](https://github.com/OpenIPC/decoder/issues/100)): the camera on screen is framed in blue, its picture fitted into the cell with its own aspect ratio, as on the screen (a turned slot is not stretched, [#248](https://github.com/OpenIPC/decoder/issues/248)), and every other configured slot gets a short stream check while the page is open. Its cell says what was found, for example `Stream OK · H.265 · 25 fps · 3.1 Mbit/s · checked 12 s ago`, or the error. diff --git a/docs/security.md b/docs/security.md index fb5d723..af29b1b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -33,9 +33,10 @@ Use the app on trusted networks only, or inside a secure channel of your own (a ## Debug server -The [debug server](debug.md) on port 8085 has no password and no encryption. It is always on while the app runs, and: +The [debug server](debug.md) on port 8085 has no encryption, and no password unless one is set in **Network** (**Web page password**). It is always on while the app runs, and: - answers only local-network clients: loopback, link-local (169.254/16, fe80::/10), the IPv4 private ranges 10/8, 172.16/12, 192.168/16, and IPv6 unique-local fc00::/7. Every other address gets `403 Forbidden: local network only`; +- with a password set, asks every request for it (HTTP Basic, any user name), from the local network and through the camex tunnel alike; a wrong one is answered after a second (about two guesses a second at most), so a long password is worth it; it is kept sealed like the camera URLs (Android 6.0+; on 5.x, as those, it is stored as it is), and one that cannot be read keeps the pages locked until it can be read again, is entered again or is removed in Network. Over the local network the password travels as plain HTTP, through the tunnel encrypted by camex; - is read-only (`GET` only) and has no setting that changes the app; - `/report.txt` (and the report the app saves, [Save report](debug.md#save-report)) is `/stats.json` and `/log` together, redacted once more as a whole; - never shows a login or password: URLs, statuses and log lines are [redacted](#log-redaction), and the snapshot shows the picture and the cell texts only. diff --git a/docs/testing.md b/docs/testing.md index c561212..9037b50 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -138,7 +138,7 @@ cd android The native code is built for arm64-v8a and armeabi-v7a by default; `-PdecoderAbis` takes a list of `arm64-v8a`, `armeabi-v7a`, `x86_64`, `x86` (an empty or unknown one fails the build). -`tests/e2e.sh [API]` plays a camera through a camex server and the tunnel on an x86_64 emulator in Docker (API 21 and 34 are checked): 13 checks, from no camera with Network off to a restart of the tunnel with Network → Save. Its output is in `tests/out/` (ignored by git). +`tests/e2e.sh [API]` plays a camera through a camex server and the tunnel on an x86_64 emulator in Docker (API 21 and 34 are checked): 14 checks, from no camera with Network off to the password of the debug page through the tunnel and a restart of the tunnel with Network → Save. Its output is in `tests/out/` (ignored by git). A release build needs a keystore at `android/key.jks` and `KEYSTORE_PASS`, `KEY_ALIAS`, `KEY_PASS` in the environment (`./gradlew assembleRelease`). Debug and release builds are signed with different keys: to switch, uninstall first, which removes the saved camera URLs. diff --git a/tests/e2e.sh b/tests/e2e.sh index 1c15cb8..7546c2e 100755 --- a/tests/e2e.sh +++ b/tests/e2e.sh @@ -15,7 +15,8 @@ # the camera's tunnel address into Decoder's settings # 5. checks: with Network off the camera has no viewer and the edge does not answer; with # Network on tun0 gets an address from the hub, ping through the tunnel, the camera is -# read from the box's tunnel address, Decoder gets the 1280x720 picture, no crash +# read from the box's tunnel address, Decoder gets the 1280x720 picture, the debug +# page through the tunnel asks for the password of Network, no crash # # Usage: tests/e2e.sh [API] (default 25; x86_64 "default" images: 21, 23, 25, 34) # @@ -168,12 +169,15 @@ $ADB shell appops set $PKG ACTIVATE_VPN allow 2>&1 | grep -q 'Unknown operation' $ADB shell appops set $PKG 47 allow [ "$API" -lt 33 ] || $ADB shell pm grant $PKG android.permission.POST_NOTIFICATIONS +# the password of the debug page (Network → Web page password), plain: read as it is +WEB_PASSWORD=e2e-pass # the tunnel's values as the Network screen keeps them (tunnel__) TUNNEL_SETTINGS="$HUB_IP:5800\ decoder\ UDP\ $CAMEX_PUBKEY\ -$KEY" +$KEY\ +$WEB_PASSWORD" # write_settings ON: Decoder's settings with slot 1 = the camera and the camex tunnel's values # (tunnel_camex_), on or off (debug builds allow run-as; a plain key and URL are read as # they are) @@ -287,6 +291,15 @@ else fi $ADB exec-out screencap -p > "$OUT/decoder.png" 2>/dev/null || true +# the debug page through the tunnel, from the Linux client: the password set in Network is asked +code() { docker exec "$PEER" curl -s -o /dev/null -m 10 -w '%{http_code}' "$@" "http://$TUN:8085/stats.json"; } +c0=$(code) c1=$(code -u "x:wrong") c2=$(code -u "anyone:$WEB_PASSWORD") +if [ "$c0" = 401 ] && [ "$c1" = 401 ] && [ "$c2" = 200 ]; then + ok "the debug page through the tunnel asks for the password (401, 401, 200)" +else + bad "debug page through the tunnel: no password $c0, wrong $c1, right $c2 (want 401 401 200)" +fi + if [ -n "$SHOTS" ]; then # the README's screenshots: the picture, the menu over it (OK), the Network dialog mkdir -p "$OUT/shots"