webcontolpanel_web_logo

WebControlPanelTemplate

v3.0.0

Table of contents

Overview

WebControlPanelTemplate is a template of the embedded WEB interface of a Linux device without WEB frameworks (version 3 replaces the template based on Linux Cockpit, see Versions). The template has the infrastructure of the RapidPixel based projects: a CMake project without sub-repositories, the libraries of the RapidPixel SDK are the modules of the SDK or their folders copied next to it (see Build). The WEB interface is two processes:

browser ──HTTPS──► webpanel (service) ──UNIX socket──► ApplicationTemplate (application)
   │                   └──HTTPS 127.0.0.1 (WHEP)──────► MServer of the application
   └───────────── UDP, DTLS-SRTP (media) ─────────────► MServer of the application
  • WebControlPanel - the service webpanel and the WEB interface: the WebServer library (HTTPS server, HTTP/1.1 over TLS 1.2 or TLS 1.3, and HTTP on a UNIX socket for the API of the application; taken from version 2 of the template, Linux only, depends on OpenSSL only), the service (login with the system accounts by the PAM helper webpanel-auth, sessions and rights of the roles, pages, information and metrics of the system, system journal, connection to the application, proxy of the WebRTC signalling, self-signed certificate, systemd units), the pages of the interface (HTML, CSS and JavaScript without build, WebRTC player) and pages.json. The users of an LDAP server log in through SSSD of the system (see Login).
  • ApplicationTemplate - the application with the parameters of the page and the video: test source, hardware H264 encoder (VCodecLibva - VA-API of an Intel GPU, VCodecV4L2 - V4L2 of Raspberry Pi 4, NVIDIA Jetson, i.MX) and video server MServer with WebRTC. It has no network port of its own for the interface: its API (GetConfig, GetParameters, Command and the state of the video) is on a UNIX socket for the service only; the remote control without the interface (External Protocol) is off by default.

The threats of the WEB interface, the measures against them, the checks which test them, the residual risks and what the manufacturer of a device adds are in ThreatModel.md.

webcontolpanel_web_parameters_page

Versions

Table 1 - Application versions.

Version Release date What’s new
1.0.0 12.04.2026 - First version.
1.0.1 25.04.2026 - Updated installation instructions.
1.0.2 20.06.2026 - Updated parameters control according to new VStreamer interface.
1.0.3 13.10.2026 - GasLeakDetector replaced by MotionMagnificator.
2.0.0 28.10.2026 - Rewrite the application.
3.0.0 13.11.2026 - New template without Linux Cockpit, Node.js and React: the service webpanel with its own HTTPS server (WebServer library) and the WEB pages in HTML, CSS and JavaScript without build.
- Login with the system accounts (PAM helper webpanel-auth, LDAP users through SSSD), roles admin, operator and viewer, sessions with CSRF tokens, protection against password guessing, limit of the request rate.
- Pages of pages.json: Dashboard, parameters pages, video page (WebRTC through the service), module pages (example: Logs); light and dark themes, English and Russian.
- ApplicationTemplate: API on a UNIX socket for the service only, hardware H264 encoders VCodecLibva and VCodecV4L2 instead of VCodecLibav (FFmpeg is not used), External Protocol off by default.
- Certificate of the HTTPS server, settings and factory reset in the interface, security events in the system journal, FIPS mode, installation with systemd units, SBOM, threat model (ThreatModel.md), unit tests, system checks and fuzzers.

Quick start

Three ways to start the panel, from the quickest one. All of them need Ubuntu 22.04/24.04 or Debian 12 (x86_64 or aarch64) with the packages for the build:

sudo apt-get update
sudo apt-get install -y build-essential cmake git libssl-dev libva-dev libpam0g-dev
cp -r <RapidPixel SDK>/modules/ExamplesTemplates/WebControlPanelTemplate .
for LIBRARY in Service/Frame Service/ConfigReader Service/Logger Service/CryptoProvider \
               Service/ImageResizer VideoCoding/VCodec Service/VOverlay Service/FormatConverter \
               VideoStreaming/VStreamer VideoStreaming/MServer VideoCoding/VCodecLibva VideoCoding/VCodecV4L2; do
    cp -r "<RapidPixel SDK>/modules/$LIBRARY" .
done
cd WebControlPanelTemplate

The folder of the template and the folders of the libraries are copied from the RapidPixel SDK: a stand alone build (see Build). The build of the RapidPixel SDK builds the template too, see Build in the RapidPixel SDK in Build.

1. Try the interface with the test accounts (a computer of development, nothing is installed). The build gets the accounts of users.json (Table 11); the configuration file of the service needs only the mode of the accounts, the other params keep their default values:

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DWEB_CONTROL_PANEL_TEST_ACCOUNTS=ON
cmake --build build -j$(nproc)
cd build/bin
echo '{"Params": {"auth": {"mode": "file"}}}' > webpanel.json
./ApplicationTemplate -v    # terminal 1; in WSL2: GALLIUM_DRIVER=d3d12 LIBVA_DRIVER_NAME=d3d12 ./ApplicationTemplate -v
./webpanel -v               # terminal 2

Open https://localhost:9000/, accept the self-signed certificate of the first start and log in as admin with the password Admin#2026 (operator and viewer: Table 11). Ctrl+C stops each program. The test accounts are for this computer only: the service listens on 127.0.0.1; a build for a device is made without the option.

2. The system accounts from the build folder (PAM, as on a device, without the installation). You log in with the name and the password of your Linux account, which gets the role admin by the group webpanel-admin:

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j$(nproc)
rm -f build/bin/webpanel.json               # the file of the way 1 has the mode file
sudo cp WebControlPanel/pam/webpanel /etc/pam.d/webpanel
sudo groupadd --system webpanel-admin; sudo groupadd --system webpanel-operator; sudo groupadd --system webpanel-viewer
sudo usermod -aG webpanel-admin $USER
# terminal 1: the PAM helper (Ctrl+C stops it)
sudo systemd-socket-activate -a --inetd -l /run/webpanel-auth.sock build/bin/webpanel-auth --user $USER
# terminal 2: the helper answers only the user of --user
sudo chmod 666 /run/webpanel-auth.sock
cd build/bin && ./ApplicationTemplate -v    # in WSL2 with the variables of the way 1
# terminal 3
cd build/bin && ./webpanel -v

Open https://localhost:9000/. For the other computers of the network set "webServer": {"address": "0.0.0.0"} in build/bin/webpanel.json and restart the service. To remove the changes of the system after the trial:

sudo rm -f /etc/pam.d/webpanel /run/webpanel-auth.sock
sudo gpasswd -d $USER webpanel-admin
sudo groupdel webpanel-admin; sudo groupdel webpanel-operator; sudo groupdel webpanel-viewer

3. A device (installation with systemd, port 443): the service runs as the user webpanel in the sandbox of systemd, the PAM helper is started by its socket (see Installation):

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr
cmake --build build -j$(nproc)
sudo cmake --install build
sudo systemd-sysusers webpanel.conf
sudo systemd-tmpfiles --create webpanel.conf
sudo usermod -aG webpanel-admin <user>      # the administrators; webpanel-operator, webpanel-viewer - the other roles
sudo systemctl daemon-reload
sudo systemctl enable --now webpanel-auth.socket webpanel

Open https://<address of the device>/ (http://<address> goes to HTTPS). The application is the program of the device and is not installed by the template: it listens to the socket /run/ApplicationTemplate/control.sock of /etc/webpanel/config.json (see the end of Installation). sudo systemctl stop webpanel webpanel-auth.socket stops the service, the removal is in Installation.

Setup. What is usually set first:

What Where
Address and port of the panel webServer.address and webServer.port of the configuration of the service (webpanel.json of the build folder, /etc/webpanel/config.json of the installation; restart the service), see Table 13.
Users and roles The Linux groups webpanel-admin, webpanel-operator, webpanel-viewer (sudo usermod -aG <group> <user>); other groups: the params auth.adminGroup, auth.operatorGroup, auth.viewerGroup and –groups of the helper. LDAP users: SSSD, see Login.
Certificate Created at the first start (self-signed). Your certificate and key: the user menu of admin, “Certificate…”, see Certificate of Service webpanel.
Timeouts of the sessions, groups of the roles, journal The user menu of admin, “Settings…” (they are kept in settingsFile).
Pages and cards pages.json (WebControlPanel/config/pages.json, the installed /etc/webpanel/pages.json; restart the service), see WEB interface. The parameters of a parameters page are described by the application (ApplicationTemplate/WebTableContent.cpp).
Video ApplicationConfig.json of the application: video.encoder, the size, the frame rate and the bitrate; video.publicAddress on a device with several network interfaces (Table 16, Video).
Firewall of a device Open TCP 443 and 80 (the redirect) and UDP video.webRtcMediaPort (7001); close TCP video.webRtcPort (7000, the signalling of the video server: sudo nft add rule inet filter input tcp dport 7000 iif != lo drop).
FIPS mode cryptoMode and fips.* of the service, video.securityProfile and fips.* of the application, see FIPS mode.
Remote control without the interface The External Protocol of the application, off by default (no authentication and no encryption).
Factory reset The user menu of admin, “Factory reset…”, or webpanel --factory-reset -c <configuration> for the stopped service.

Screenshots

The interface of a Raspberry Pi 4 (Debian 12) with ApplicationTemplate (the test source, the hardware encoder V4L2) in Chrome: a build for the checks (the test accounts, the user admin), 1440x900 and a phone of 390x844. The images are in the folder static.

Login page (login.html): the name of the device and the language; every failure gives the same message.

webcontolpanel_login_page

Dashboard: the cards System, Load (CPU, memory and network for 5 minutes, cores, memory and disks, temperatures, network interfaces), Application (connection, version, video streams), Security (cryptography of the service and of the video server, External Protocol, certificate, last logins) and Video.

webcontolpanel_dashboard_page

Dashboard in the dark theme (the user menu: Auto - as the system, Light, Dark).

webcontolpanel_dashboard_page_dark

Parameters: the groups of the parameters of the application (GetConfig) with all kinds of elements - text field, dropdown, switch, slider, command button and push/release button; the read only values are grey. Every change is a command of the application; the card Commands shows them with the answers.

webcontolpanel_web_parameters_page

Advanced: a parameters page of the role admin only (numbers, a divider of the elements).

webcontolpanel_advanced_page

Video: WebRTC (WHEP through the service) with the state and the statistics of the stream, the buttons of the zoom and of the capture over the frame, a snapshot (PNG) and the full screen; a click on the frame sends the point to the application.

webcontolpanel_video_page

Logs (a page of the type module, role admin): the system journal with the filter of the priority; a record opens in a dialog.

webcontolpanel_logs_page

Security events (the tab of admin): the events of the service from the journal - logins, failed logins, commands, ended sessions, changes of the certificate and of the settings.

webcontolpanel_security_events

User menu: the user and the role, the theme, the language and, for admin, the settings, the certificate, the factory reset; the logout.

webcontolpanel_user_menu

Settings of admin: the timeouts of the sessions, the period of the check of the accounts, the groups of the roles, the journal; a change needs the password of the account. In the build for the checks (mode file) the roles are in users.json, so the groups are not editable; in the mode pam of a device they are.

webcontolpanel_settings_dialog

Certificate of the HTTPS server: the current certificate (subject, issuer, validity, names, key, SHA-256 fingerprint) and the upload of a chain and its key.

webcontolpanel_certificate_dialog

Russian: the language of the menu or of the login page; the texts of the interface are in the dictionaries www/i18n (the names of the parameters come from the application).

webcontolpanel_dashboard_page_ru

Phone: the cards in one column, the side menu opens by the button in the top bar.

webcontolpanel_mobile_dashboard webcontolpanel_mobile_menu

Repository structure

CMakeLists.txt ------------- Main CMake file.
README.md ------------------ This file.
ThreatModel.md ------------- Threat model of the WEB interface: assets, attackers, threats, measures, residual risks.
.clang-tidy ---------------- Checks of clang-tidy: bugs and the coding standards of the SDK.
cmake ---------------------- Folder with CMake scripts.
    Sbom.cmake ------------- Target sbom: SBOM of the build in the format CycloneDX.
static --------------------- Folder with images for README.
ApplicationTemplate -------- Folder with the application.
    CMakeLists.txt --------- CMake file of the application.
    ApplicationConfig.h ---- Params of the configuration file and global objects.
    ApplicationTemplateVersion.h.in File for CMake to generate version header (in the build folder).
    WebTableContent.h ------ Description of the parameters (GetConfig).
    WebTableContent.cpp ---- Text of the description of the parameters.
    WebParameters.h -------- WebParameters class header file: values and check of the commands.
    WebParameters.cpp ------ WebParameters class implementation file.
    Control.cpp ------------ API of the application for the service on the UNIX socket, the handler of the commands.
    ExternalProtocol.cpp --- External Protocol: UDP and TCP ports of the remote control.
    Video.h ---------------- Video: test source, H264 encoder and video server (declarations).
    Video.cpp -------------- Video: implementation.
    RecoveringEncoder.h ---- RecoveringEncoder class header file: encoder replaced after a failure.
    RecoveringEncoder.cpp -- RecoveringEncoder class implementation file.
    main.cpp --------------- Application source code file.
    tests ------------------ Folder with the tests of the application.
        CMakeLists.txt ----- CMake file of the tests (ctest).
        EncoderTest.cpp ---- Test of RecoveringEncoder with encoders of the test.
        WebParametersTest.cpp Test of the parameters of the WEB page: values of each element, access, commands.
WebControlPanel ------------ Folder with the service and the WEB interface.
    CMakeLists.txt --------- CMake file of the WEB interface.
    src -------------------- Folder with the source code of the service.
        CMakeLists.txt ----- CMake file of the library WebControlPanelCore.
        Pages.h ------------ Pages class header file: pages.json and rights of the roles.
        Pages.cpp ---------- Pages class implementation file.
        SystemInfo.h ------- SystemInfo class header file: information and metrics for the Dashboard.
        SystemInfo.cpp ----- SystemInfo class implementation file.
        Users.h ------------ Users class header file: the test accounts of users.json (a build for the checks).
        Users.cpp ---------- Users class implementation file.
        Sessions.h --------- Sessions class header file: sessions and CSRF tokens.
        Sessions.cpp ------- Sessions class implementation file.
        LoginGuard.h ------- LoginGuard class header file: protection against password guessing.
        LoginGuard.cpp ----- LoginGuard class implementation file.
        AuthClient.h ------- AuthClient class header file: client of the PAM helper, roles of the groups.
        AuthClient.cpp ----- AuthClient class implementation file.
        AppBridge.h -------- AppBridge class header file: connection to the application (UNIX socket).
        AppBridge.cpp ------ AppBridge class implementation file.
        HttpsClient.h ------ HttpsClient class header file: HTTPS client of the video server (digest, pinned certificate).
        HttpsClient.cpp ---- HttpsClient class implementation file.
        VideoProxy.h ------- VideoProxy class header file: proxy of the WebRTC signalling (WHEP).
        VideoProxy.cpp ----- VideoProxy class implementation file.
        WebFiles.h --------- WebFiles class header file: files of the WEB pages.
        WebFiles.cpp ------- WebFiles class implementation file.
        Certificate.h ------ Self-signed certificate of the first start.
        Certificate.cpp ---- Implementation of the self-signed certificate.
        RateLimiter.h ------ Limit of the request rate of the client addresses.
        RateLimiter.cpp ---- Implementation of the limit of the request rate.
        ConfigFile.h ------- Configuration files: the params which a file doesn't have keep their defaults.
        ConfigFile.cpp ----- Implementation of the reading of the configuration files.
        FactoryReset.h ----- Factory reset: removal of the files, lock of the log folder.
        FactoryReset.cpp --- Implementation of the factory reset.
        WebControlPanelVersion.h.in File for CMake to generate version header of the template.
        ApiRequests.h ------ Parsers of the requests of the API: cookie, bodies, paths (fuzzed).
        ApiRequests.cpp ---- Implementation of the parsers of the requests.
        CryptoContext.h ---- Cryptography of the service in the library context of CryptoProvider.
        CryptoContext.cpp -- Implementation: the context, FIPS mode, random bytes, SHA-256, reading of a certificate.
        Settings.h --------- Settings of admin: check, changes, file.
        Settings.cpp ------- Implementation of the settings of admin.
        ExternalProtocol.h - External Protocol: parsing of the messages and the answers.
        ExternalProtocol.cpp Implementation of the External Protocol.
        Secrets.h ---------- Secrets in memory: wiping, secret values of JSON texts without the JSON parser.
        Secrets.cpp -------- Implementation of the wiping and of the secret values of JSON texts.
        SystemJournal.h ---- System journal: reading (journalctl), records of the security events (journald).
        SystemJournal.cpp -- Implementation of the reading of the system journal and of the records.
        WebServer ---------- Folder with WebServer library.
        Service ------------ Folder with the executable of the service webpanel.
            CMakeLists.txt - CMake file of the service: build, copy of the WEB pages, installation.
            EmbedWww.cmake - Script of the build: C++ source of the WEB pages built into the service.
            EmbeddedWww.h -- Files of the WEB pages built into the service (declaration).
            ServiceConfig.h  Params of the configuration file and global objects.
            ServiceApi.cpp - HTTPS API of the service and WEB pages.
            main.cpp ------- Service source code file.
    auth ------------------- Folder of the PAM helper webpanel-auth.
        CMakeLists.txt ----- CMake file of the helper (built with libpam0g-dev), its units and the PAM configuration.
        main.cpp ----------- Helper: pam_authenticate and pam_acct_mgmt for one connection.
    config ----------------- Folder with the configuration.
        config.json.in ----- Configuration of the installed service (paths of the installation).
        users.json --------- Test accounts of a build for the checks (one per role, WEB_CONTROL_PANEL_TEST_ACCOUNTS).
        pages.json --------- Pages of the interface.
    tests ------------------ Folder with tests.
        CMakeLists.txt ----- CMake file of the tests (ctest).
        PagesTest.cpp ------ Test of the check of pages.json and the rights of the roles.
        AuthTest.cpp ------- Test of the accounts, the sessions and the protection against guessing.
        BridgeTest.cpp ----- Test of the UNIX socket of WebServer and of the connection to the application.
        PamTest.cpp -------- Test of the PAM helper and its client with a test PAM configuration (no root).
        I18nTest.cpp ------- Test of the dictionaries: every text of the pages, the same texts in every language.
        ResetTest.cpp ------ Test of the factory reset: new certificate, log files, lock of the log folder, sessions.
        CertificateTest.cpp  Test of an uploaded certificate: check of the chain and the key, description, installation.
        RateLimitTest.cpp -- Test of the limit of the request rate: burst, rate, reports, number of the addresses.
        JournalTest.cpp ---- Test of the records of the system journal (native protocol of journald).
        WebServerTest.cpp -- Test of the HTTPS server: requests over TLS, requests which are not valid, redirect of plain HTTP
                             to HTTPS (also of the redirect port).
        WebFilesTest.cpp --- Test of the files of the WEB pages: paths, types, entity tags, If-None-Match.
        ConfigTest.cpp ----- Test of the configuration files: defaults of the missing params, unknown params.
        SettingsTest.cpp --- Test of the settings of admin: limits, groups of the roles, file, changes.
        ExternalProtocolTest.cpp Test of the External Protocol: syntax, answers, refusals.
        SecretsTest.cpp ---- Test of the secrets in memory: wiping, secret values of JSON texts, bodies, cookie.
        ApiRequestsTest.cpp  Test of the requests of the API: the body of a command, the paths of the video signalling.
        VideoTest.cpp ------ Test of the certificate, the WHEP proxy and its HTTPS client with the video server.
        VideoTest.h264 ----- Short H264 stream of the test (64x64, 10 frames).
        TestWebTableContent.json Test description of the parameters page with all elements.
        system ------------- System checks of a build: the HTTP API and the interface in a browser.
            run_checks.py -- Runner: a copy of the programs for each check, the results, the summary.
            checks.py ------ Common part: the copy, the service and the application, requests, login.
            api ------------ Checks of the API: auth, roles, video, video_off, app_config, external_protocol, restart,
                             rate_limit, hsts, headers, journal, reset, audit, certificate, settings, embedded_www, fips.
            e2e ------------ Pages of the checks in a browser: shell, ui, video, reset, audit, language, certificate,
                             settings, recover.
        fuzz --------------- Fuzzers of the parsers (libFuzzer with AddressSanitizer and UndefinedBehaviorSanitizer).
            CMakeLists.txt - CMake file of the fuzzers (option WEB_CONTROL_PANEL_FUZZERS).
            Fuzz*.cpp ------ Fuzzers: FuzzHttpRequest, FuzzHttpResponse, FuzzJson, FuzzPages, FuzzApiRequests,
                             FuzzExternalProtocol.
            run.sh --------- Builds and runs the fuzzers in Docker from a copy of the sources.
            Dockerfile ----- Image: Ubuntu 24.04 with Clang 18.
            inside.sh ------ Build, run and summary in the container.
        ldap --------------- Stand of the login of LDAP users through SSSD (Docker): OpenLDAP, SSSD, the checks.
            run.sh --------- Builds the image, starts the stand with the programs of a build, runs the checks.
            Dockerfile ----- Image: Ubuntu 24.04 with slapd, SSSD and the PAM stack.
            setup.sh ------- Setup in the container: certificates, slapd with TLS, the directory, SSSD, the service.
            sssd_mode.sh --- SSSD of the stand: LDAPS, StartTLS, without TLS, another CA.
            check.py ------- Checks of the login of LDAP users.
    www -------------------- Folder with WEB pages (HTML, CSS and JS without build).
        index.html --------- Shell of the interface.
        login.html --------- Login page.
        css ---------------- Styles: tokens.css, theme.css, layout.css, components.css.
        js ----------------- Scripts: app.js (shell, routing), login.js, api.js (requests), charts.js (SVG charts), i18n.js (languages), ui/ (components: dom.js, format.js, hold.js, tabs.js, dialog.js, toast.js, spinner.js, menu.js, template.js - HTML templates of the pages), video/whep.js (WebRTC player).
        pages -------------- Pages: dashboard/, parameters/, video/, logs/ (example of a module page with a template).
        icons -------------- SVG sprite of the icons: sprite.svg (32 icons).
        img ---------------- Images: logo.svg (top bar and login page), favicon.svg.
        i18n --------------- Languages: languages.json (list), en.json (all texts), ru.json.
    systemd ---------------- Folder of the systemd units (paths of the installation).
        webpanel.service.in  Unit of the service.
        webpanel-auth.socket.in Socket of the PAM helper.
        webpanel-auth@.service.in Unit of the PAM helper (one connection).
        webpanel.sysusers -- User of the service and groups of the roles (sysusers.d).
        webpanel.tmpfiles.in Mode and group of the configuration files (tmpfiles.d).
    pam -------------------- Folder of the PAM configuration.
        webpanel ----------- /etc/pam.d/webpanel: common-auth, common-account, delay of a failure.

Build

Install the dependencies (Ubuntu Linux). OpenSSL must be 3.0 or newer:

sudo apt-get update
sudo apt-get install -y build-essential cmake libssl-dev libva-dev libpam0g-dev

libpam0g-dev is needed for the PAM helper webpanel-auth (login with the system accounts): without it the helper is not built (CMake writes “PAM headers not found”) and nobody logs in to the service of the build, except with the test accounts of a build for the checks (below).

The video of ApplicationTemplate needs a hardware H264 encoder: VCodecLibva (VA-API, PC with an Intel GPU) is built if libva-dev is installed, VCodecV4L2 (V4L2 memory to memory devices: Raspberry Pi 4, NVIDIA Jetson, i.MX) is built on Linux with the V4L2 headers of the kernel (always there). Without a working encoder the application works without video. On Raspberry Pi 4 the encoder is /dev/video11 (bcm2835-codec), the user of the application must be a member of the group video. Raspberry Pi 5 has no hardware H264 encoder: no video there. For VA-API the computer needs a VA-API driver of its GPU (Intel: package intel-media-va-driver-non-free or intel-media-va-driver, check with vainfo) and the user of the application must be a member of the group render.

In WSL2 the GPU is not a DRM device (/dev/dri is the virtual driver vgem), so the Intel driver of VA-API doesn’t work there. The GPU of Windows is used by the D3D12 driver of Mesa (package mesa-va-drivers): run vainfo and the application with two variables:

export GALLIUM_DRIVER=d3d12 LIBVA_DRIVER_NAME=d3d12
vainfo --display drm --device /dev/dri/renderD128    # H264: VAEntrypointEncSlice
./ApplicationTemplate -v

The application opens the DRM device, as the vainfo above. A plain vainfo opens the display of WSLg (Wayland or X11) and can fail with “resource allocation failed” while the encoder works, e.g. without the folder of XDG_RUNTIME_DIR; without GALLIUM_DRIVER=d3d12 the driver fails the same way (“d3d12_drv_video.so init failed”).

The video of WSL2 is reached from Windows by the virtual adapter of WSL: Edge and Chrome of Windows play it, Firefox doesn’t (it gathers the ICE candidates of the interface of the default route only, the address of WSL is not reachable from it). On a device of the network (e.g. Raspberry Pi 4) Firefox plays the video like the other browsers.

Build in the RapidPixel SDK. The template is an example of the RapidPixel SDK (folder modules/ExamplesTemplates/WebControlPanelTemplate): the build of the SDK adds it after the libraries of the SDK which it uses (the template is excluded if one of them is not built, e.g. MServer without OpenSSL 3). The programs, the copy of the WEB pages and pages.json are in the folder bin of the build folder of the SDK, the unit tests run with ctest in the folder modules/ExamplesTemplates/WebControlPanelTemplate of the build folder. cmake --install of the SDK doesn’t install the service: for a device build the template stand alone (below) or configure the SDK with -DWEB_CONTROL_PANEL_INSTALL=ON.

cd RapidPixelSdk
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j$(nproc)
cd build/modules/ExamplesTemplates/WebControlPanelTemplate
ctest --output-on-failure

Build stand alone. The folder of the template does not contain sub-repositories. The libraries of the RapidPixel SDK which it uses (see 3rd-party libraries) must be in the same folder as the template. The folder structure must be:

<work folder>
    WebControlPanelTemplate
    ConfigReader
    CryptoProvider
    FormatConverter
    Frame
    ImageResizer
    Logger
    MServer
    VCodec
    VCodecLibva
    VCodecV4L2
    VOverlay
    VStreamer

Copy the template and the libraries from the RapidPixel SDK and build:

cp -r <RapidPixel SDK>/modules/ExamplesTemplates/WebControlPanelTemplate .
for LIBRARY in Service/Frame Service/ConfigReader Service/Logger Service/CryptoProvider \
               Service/ImageResizer VideoCoding/VCodec Service/VOverlay Service/FormatConverter \
               VideoStreaming/VStreamer VideoStreaming/MServer VideoCoding/VCodecLibva VideoCoding/VCodecV4L2; do
    cp -r "<RapidPixel SDK>/modules/$LIBRARY" .
done
cd WebControlPanelTemplate
mkdir build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j$(nproc)

If WebControlPanelTemplate is the top-level CMake project, the main CMakeLists.txt file adds the folders ../Frame, ../ConfigReader, ../Logger, ../CryptoProvider, ../ImageResizer, ../VCodec, ../VOverlay, ../FormatConverter, ../VStreamer, ../MServer (in this order) and the hardware encoders ../VCodecLibva (if libva is installed) and ../VCodecV4L2 (if the V4L2 headers are) before its own folders. If a folder does not exist, CMake stops with an error. To update the libraries, copy their folders again from a new version of the RapidPixel SDK.

Connect to your project. If WebControlPanelTemplate is included in another CMake project (add_subdirectory), the top-level CMakeLists.txt adds the libraries itself, in the order above and before WebControlPanelTemplate, and WebControlPanelTemplate adds none of them. The hardware encoders are optional: the application uses VCodecLibva and VCodecV4L2 only if their targets exist when its folder is added. Without a required library the build stops with a compile error (<Library>.h: No such file or directory). Such a project installs the service with cmake --install only with the option -DWEB_CONTROL_PANEL_INSTALL=ON (a stand alone build installs it by default, see Installation).

add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/Frame)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/ConfigReader)
# ... the other libraries in the order above ...
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/MServer)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/VCodecLibva)    # optional, before WebControlPanelTemplate
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/WebControlPanelTemplate)

The build folder gets bin/webpanel (service), bin/webpanel-auth (PAM helper), bin/ApplicationTemplate (application), the copy of the WEB pages bin/www and bin/pages.json.

Test accounts: the service logs in only the system users (by the PAM helper, see Login). The accounts of a file (users.json, param auth.mode “file”) are built into the service only with the option -DWEB_CONTROL_PANEL_TEST_ACCOUNTS=ON, for the checks of the login without the system accounts (the system checks need it, see Checks of the code); such a build gets bin/users.json and webpanel --hash-password. Without the option (the default, a device) the mode “file” is not in the service: with it in the configuration the service doesn’t start and writes the reason.

cmake .. -DCMAKE_BUILD_TYPE=Release -DWEB_CONTROL_PANEL_TEST_ACCOUNTS=ON    # a build for the checks

Pages built into the service: with the option -DWEB_CONTROL_PANEL_EMBED_WWW=ON the files of WebControlPanel/www (html, css, js, json, svg, png, ico) are built into webpanel: the pages and the program are one file, whose integrity the update of the device checks, and the pages can’t be changed on the device. The service gives them when its param webServer.wwwFolder is empty: cmake --install of such a build installs no folder of pages and its configuration has an empty wwwFolder. A folder in wwwFolder is given instead (e.g. pages in development). A page added or changed needs a new build (EmbedWww.cmake makes the source of the files when a file changes). The service writes the source of its pages to the log (WEB pages: built into the service (33 files) or WEB pages: folder ...).

cmake .. -DCMAKE_BUILD_TYPE=Release -DWEB_CONTROL_PANEL_EMBED_WWW=ON

SBOM: cmake --build build --target sbom writes build/sbom.cdx.json (CycloneDX 1.5, JSON; cmake/Sbom.cmake): the product, its modules - the code of the repository and the libraries of the RapidPixel SDK of the build (their folders next to the repository or added by the top-level project) with the versions and the commits of the folders which are git repositories (no code of others), the programs of the build with their SHA-256 and the packages of the OS which they use: the libraries of their ELF dependencies (the owner package of dpkg) and the packages needed at run time (systemd for the service, the PAM stack for the helper; the VA-API drivers and SSSD as optional if they are installed). The packages are the ones of the computer of the build: make the SBOM on the image of the device (or in its build system) for the real versions. cmake --install installs it to /usr/share/doc/webpanel/sbom.cdx.json if it is made before. A FIPS module which is not a package of the OS (see FIPS mode) is added by the integrator.

Run the unit tests in the build folder:

ctest --output-on-failure

Run

Run the application and the service from build/bin, each in its terminal (-v prints the logs also to the console, the logs are written to the Log folder). They stop on SIGINT (Ctrl+C) or SIGTERM and can be started in any order: the service checks the connection to the application once per second.

cd build/bin
./ApplicationTemplate -v      # in WSL2: GALLIUM_DRIVER=d3d12 LIBVA_DRIVER_NAME=d3d12 ./ApplicationTemplate -v
./webpanel -v

Open https://localhost:9000/ in a browser and log in with a system account of a group of a role (see Login): the service of the build folder uses the PAM helper too, start it as in The helper of the build folder of Login. In a build for the checks (-DWEB_CONTROL_PANEL_TEST_ACCOUNTS=ON) the test accounts of Table 11 work without the helper: set "auth": {"mode": "file"} in build/bin/webpanel.json. On the first start the service creates a self-signed certificate (webpanel.crt, webpanel.key): accept it in the browser once. Both processes create their configuration files with the default params on the first start: webpanel.json (see Service webpanel) and ApplicationConfig.json (see ApplicationTemplate); they find each other by the socket ApplicationTemplate.sock of the folder.

A change in WebControlPanel/www or WebControlPanel/config/pages.json gets to build/bin with the next build (cmake --build build); reload the page after it (restart the service after a change of pages.json). Edit the source files: the copies in build/bin are overwritten by the build.

Checks of the code

Unit tests: ctest in the build folder (see Build).

clang-tidy. The file .clang-tidy in the root of the repository has the checks of the bugs (clang-analyzer, bugprone, cert, concurrency, performance, portability, misc) and of the rules of the coding standards of the RapidPixel SDK (naming, braces, initialization, special member functions, casts, nullptr, override, macros, memory); the file lists the excluded checks and why. The code of WebControlPanel and ApplicationTemplate has no findings, so a finding is a new problem; a deliberate exception is marked in the code with // NOLINT(<check>): <reason>. clang-tidy 19 or newer is needed (the key ExcludeHeaderFilterRegex), e.g. pip install clang-tidy; it reads the commands of a build:

cmake -S . -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
run-clang-tidy -p build -quiet '(WebControlPanel|ApplicationTemplate)/.*\.cpp$'   # run-clang-tidy.py of pip

Sanitizers (AddressSanitizer with LeakSanitizer and UndefinedBehaviorSanitizer of GCC or Clang): a separate build folder, then the unit tests and the system checks (below) with --bin build-asan/bin:

cmake -S . -B build-asan -DCMAKE_BUILD_TYPE=Debug \
    -DCMAKE_C_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize-recover=undefined" \
    -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer -fno-sanitize-recover=undefined" \
    -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined" -DWEB_CONTROL_PANEL_TEST_ACCOUNTS=ON
cmake --build build-asan -j$(nproc)
cd build-asan && ASAN_OPTIONS=detect_leaks=1 UBSAN_OPTIONS=print_stacktrace=1 ctest --output-on-failure

An error stops the program with a report (log_path of ASAN_OPTIONS writes the reports to files). In WSL2 the VA-API driver d3d12 doesn’t start under ASan: for the video build ApplicationTemplate with -fsanitize=undefined only.

Fuzzers (the goal: at least 8 hours without a failure): libFuzzer of Clang with AddressSanitizer and UndefinedBehaviorSanitizer, folder WebControlPanel/tests/fuzz:

  • FuzzHttpRequest - the parser of the requests of WebServer (request line, header fields, Content-Length, Host);
  • FuzzHttpResponse - the parser of the responses of HttpsClient (the answers of the video server);
  • FuzzJson - the JSON parser of ConfigReader, a value written and read again, the settings, users.json; the secret values of a text (JsonSecrets) are compared with the values of the parser;
  • FuzzPages - pages.json, the description of the parameters of the application (GetConfig) and the rights of the roles (pages, commands, streams, requests);
  • FuzzApiRequests - the cookie of the session, the bodies of the login, of a command, of the confirmations, of a certificate and of the settings, the paths of the WebRTC signalling and of the files of the pages.
  • FuzzExternalProtocol - the datagrams of the External Protocol of the application and their answers (one line of the id of the message).

WebControlPanel/tests/fuzz/run.sh [<seconds of each fuzzer>] [<work folder>] builds them in Docker (Ubuntu 24.04, Clang 18, a copy of the sources of the repository and of the libraries next to it; nothing is installed on the computer) and runs them at once, one process each: 600 s and /tmp/wcp-fuzz by default, run.sh 28800 for 8 hours. The work folder keeps the build, the corpora (they grow from run to run), the logs and the inputs of the failures (crashes/<fuzzer>); the exit code is 1 if a fuzzer failed. Keep the computer awake for a long run: the time of libFuzzer goes on while the computer sleeps, so such a run is reported as INCOMPLETE (exit code 2), and an input which was being run when it fell asleep is saved as slow (slow-unit-*): the summary runs it again and counts it as a failure only if it is slow again. Without Docker: a build with Clang, -DWEB_CONTROL_PANEL_FUZZERS=ON and -DCMAKE_CXX_FLAGS="-fsanitize=fuzzer-no-link,address,undefined" (see inside.sh).

System checks (folder WebControlPanel/tests/system, Python 3 without other packages): the HTTP API of the service with the application (login, rights of the roles, WHEP proxy, a new start of the application, limit of the request rate, HSTS and the redirect of HTTP, the protective headers of the pages and the API and the pages without inline code and HTML of data, the templates of the pages without scripts and styles, system journal, factory reset, security events, certificate of the administrator, settings of admin, FIPS mode, the application without video, the configuration file of the application, the External Protocol of the application, the pages built into the service with --bin of such a build) and the interface in a headless Chromium-based browser (shell and user menu, components, video, factory reset, security events, an added language, certificate of the administrator, settings of admin, recovery of the video after a new start of the application: at most 5 s). Every check gets its own copy of the programs of build/bin in a temporary folder, with the service on 127.0.0.1:9600 and the test accounts of users.json (auth.mode “file”): the checks need a build with -DWEB_CONTROL_PANEL_TEST_ACCOUNTS=ON, the runner refuses another one; the copy of a failed check is kept with its logs (the path is in the summary). The pages report their results as commands of the application (E2E PASS ...), the runner reads them in the log of the service. Stop the running service and ApplicationTemplate first (the ports of the video server, 7000 and 7001, are the defaults of the application); the checks of the system journal are skipped without systemd-journald.

cmake -S . -B build -DWEB_CONTROL_PANEL_TEST_ACCOUNTS=ON   # the test accounts of the checks
cmake --build build
python3 WebControlPanel/tests/system/run_checks.py                     # API checks; the browser checks are skipped
python3 WebControlPanel/tests/system/run_checks.py --browser /usr/bin/google-chrome
python3 WebControlPanel/tests/system/run_checks.py api/auth e2e/shell  # some checks; --list lists them
# WSL2 with a Windows browser and the VA-API encoder:
GALLIUM_DRIVER=d3d12 LIBVA_DRIVER_NAME=d3d12 python3 WebControlPanel/tests/system/run_checks.py \
    --browser "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"

Options: --bin (another build, e.g. of the sanitizers), --port, --cycles (new starts of the application in e2e/recover, 3 by default), --keep (keep all copies), --fips <openssl.cnf> with --fips-modules <folder of fips.so> and --fips-version <version>: every check runs the service in the FIPS mode and api/fips checks the mode (without --fips it is skipped, see FIPS mode). The login of LDAP users through SSSD is checked by the stand WebControlPanel/tests/ldap in Docker (WebControlPanel/tests/ldap/run.sh, see Login). The exit code is 1 if a check fails. The video checks need a working H264 encoder of the application (see Video; in WSL2 run the checks with GALLIUM_DRIVER=d3d12 LIBVA_DRIVER_NAME=d3d12); api/video_off needs none.

3rd-party libraries

The 3rd-party libraries are libraries of the RapidPixel SDK: in the SDK its modules, in a stand alone build their folders copied into the same folder as WebControlPanelTemplate, not sub-repositories (see Build).

Table 2 - 3rd-party libraries.

Library Purpose
MServer Video server: WebRTC (WHEP, ICE-lite, DTLS-SRTP), HLS, modes CRA_STRICT / STRICT_FIPS / FIPS_ONVIF_BRIDGE. ApplicationTemplate uses WebRTC.
VCodecLibva Hardware H264 encoder (VA-API, Intel GPU) of ApplicationTemplate. Built only if libva is installed.
VCodecV4L2 Hardware H264 encoder (V4L2 memory to memory: Raspberry Pi 4, NVIDIA Jetson, i.MX) of ApplicationTemplate. Built on Linux.
CryptoProvider Cryptography provider: FIPS mode of OpenSSL with the check that the module is really used.
ConfigReader JSON parser and configuration reader.
Logger Logging.
Frame Video frame class. Dependency of MServer.
VCodec Video codec interface. Dependency of MServer.
VOverlay Video overlay interface. Dependency of MServer.
VStreamer Video streamer interface. Dependency of MServer.
FormatConverter Pixel format conversion. Dependency of MServer.
ImageResizer Image resizing. Dependency of MServer.

To add a library:

  1. Copy the folders of the library and of the libraries which it uses from the RapidPixel SDK into the folder which contains WebControlPanelTemplate (a stand alone build; in the RapidPixel SDK the library is a module of the SDK and the steps 1 and 2 are not needed):
cp -r "<RapidPixel SDK>/modules/<Category>/<Library>" .
  1. Add the library to the stand-alone block of the main CMakeLists.txt (if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)). The libraries do not add their dependencies when they are included in another project, so the dependencies of a library are added before the library:
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/../<Library> ${CMAKE_CURRENT_BINARY_DIR}/<Library>)
  1. Link the library to the target which uses it (in the CMake file of the target):
target_link_libraries(${PROJECT_NAME} <Library>)

WebServer library

The WebServer class (namespace rapidpixel) is the HTTPS server of the service and the server of the API of the application on a UNIX socket. The main features:

  • Only AES-GCM cipher suites are offered (TLS 1.2: with ECDHE key exchange).
  • The TLS context can be made in an OpenSSL library context of the caller, e.g. of the FIPS module of CryptoProvider (WebServerTls of init(…): libraryContext, an OSSL_LIB_CTX*), and the groups of the key exchange can be limited (groups, e.g. “P-256:P-384”). By default: the default context of OpenSSL and its groups.
  • The connections are accepted in the thread of run(…) and served in 32 worker threads. At most 64 accepted connections wait for a worker, further connections are closed at once. One client address of run(…) has at most 16 open connections (served or waiting; a browser opens up to 6): further connections of the address are closed at once, so one client takes at most half of the threads and the others are served.
  • Limits of a request: request line and header fields 16 KB (431), number of header fields 100 (431), body 1 MB given by Content-Length (413), chunked transfer coding is not supported (501), TLS handshake 10 s, waiting for the next request of a kept connection 5 s (an idle connection doesn’t hold a thread long), receiving a request 15 s, sending a response 15 s, 100 requests in one connection.
  • A request without a handler for its path is answered with 404, a known path with another method with 405, a malformed request with 400, an HTTP version other than 1.0 and 1.1 with 505.
  • The handlers are called from the worker threads, so several handlers can run at the same time. An exception thrown by a handler is caught by the server, the client receives 500.
  • A request filter (setFilter(…), e.g. a limit of the request rate) is called for every request before its handler, also for the requests without a handler: it passes the request on or answers it itself (e.g. 429).
  • A plain HTTP request on the port of run(…) (“http://” typed by mistake) is answered by the server with 301 to “https://” of the same host, port and target (400 without a valid Host field), the connection is closed. The server tells it by the first byte of the connection: a TLS connection starts with a handshake record.
  • A redirect port (openRedirectPort(…) before run(…), e.g. 80) answers every request without TLS with 301 to “https://” of the same host with the port of run(…) (none for 443) and the same target: “http://<device>” without a port leads to the HTTPS port. Its connections share the worker threads and the limit of the connections of an address with the HTTPS port; no handler and no filter is called. run(…) closes the port when it returns.
  • runUnix(…): HTTP/1.1 without TLS on a UNIX socket with the same limits. Only the allowed users connect: the kernel gives the user of the client process (SO_PEERCRED), the connections of other users are closed at once. The socket file gets the mode 0660 (and the group of the parameter); a socket file left by a stopped server is replaced, another file and the socket of a running server are not; the file is removed at the stop.

Table 3 - Methods of the WebServer class.

Method Description
init(…) Load the TLS certificate chain and the private key (PEM files); optional WebServerTls: the OpenSSL library context of the TLS context and the groups of the key exchange.
setHandler(…) Set a request handler for a method (GET, POST, PUT, OPTIONS, DELETE) and an exact path or “*” (requests of the method without a handler for their path).
setFilter(…) Set the request filter: called before the handler of every request; FALSE sends the answer of the filter. An empty filter removes it.
setDefaultHeaders(…) Set the header fields of every response over TLS, also of the answers of the server itself (an invalid request, no handler, a method which the path doesn’t have), e.g. Strict-Transport-Security; a field which the handler set is not added again.
openRedirectPort(…) Open a port without TLS for the next run(…) which answers every request with a redirect to HTTPS (e.g. 80). FALSE if it can’t be opened (used, no right to a port below 1024).
run(…) Listen to the IPv4 address and the port and serve the requests. Blocks the calling thread until stop() is called.
runUnix(…) Listen to a UNIX socket and serve the requests of the allowed users without TLS (init(…) is not needed). Blocks like run(…).
stop() Stop the server. Can be called from any thread, also from a request handler.

To use the library link it to the target: target_link_libraries(${PROJECT_NAME} WebServer). Example:

#include "WebServer.h"

int main()
{
    rapidpixel::WebServer server;
    // The certificate chain and the key of the program (PEM, the key 0600).
    if (!server.init("server.crt", "server.key"))
        return -1;

    server.setHandler(rapidpixel::WebServerMethod::GET, "/api/status",
        [](const rapidpixel::WebServerRequest&,
           rapidpixel::WebServerResponse& response)
        {
            response.setBody("{\"status\":\"OK\"}", "application/json");
        });

    // Blocks until server.stop() is called. Only the local computer: the
    // server doesn't authenticate the clients (see below).
    return server.run("127.0.0.1", 8443) ? 0 : -1;
}

The server doesn’t authenticate the clients: TLS encrypts the traffic but does not authorize a caller. Keep the port on a trusted network or add authentication in the handlers. The private key of the certificate must be readable by the account which runs the server; do not make private keys world-readable.

WEB interface

The WebControlPanel/www folder contains the WEB interface: HTML5, CSS3 and JavaScript modules without frameworks, npm and build. It is served by the service webpanel and works with the API of the service (Table 12; same origin, no CORS).

Shell (js/app.js). At start the shell requests the session (/api/auth/session: user, role, CSRF token; without a session the browser goes to the login page) and the pages of the role (/api/pages), builds the side menu (the Dashboard first if the role has cards, then the pages with their titles and icons) and shows the page of the address #/dashboard or #/page/<id> (the first item by default; the Back button and direct links work). A page is a JavaScript module which is loaded at its first opening with import() and exports mount(root, ctx) and unmount(). The context ctx has page (the entry of pages.json), api (requests to the service, the commands are written to the Commands list), ui (components), i18n (t(text, values) - translation of the texts, language() - the language of the interface, e.g. for the dates), user (role) and theme. When the user leaves a page, unmount() stops its timers and requests. If the service doesn’t answer, the shell shows “No connection to the service” and checks the connection itself also on a page without requests of its own (the pause grows to 5 seconds); the repeated requests don’t extend the idle timeout of the session.

Top bar and menu. The top bar has the logo (img/logo.svg) and the name of the product, the host name, the cryptography mode of the service (badge “Standard” or “FIPS”, the module in its tooltip) and the user menu: the user and the role, the theme (Auto - the system setting, Light, Dark), the language, the settings, the certificate of the HTTPS server and the factory reset (admin only, see Service webpanel) and the logout. The side menu follows the width of the screen: less than 600 px - it slides out by the button in the top bar; 600…1023 px - only the icons (the title is the tooltip and stays for screen readers); from 1024 px - the icons and the titles. The content is at most 1600 px wide. The checked widths are 320, 375, 768, 1024, 1366, 1920 and 2560 px: no horizontal scroll on any page.

Languages. The texts of the code are in English and go through t("..."); a part {name} is replaced with a value (t("Stream {stream}", {stream})), so a translation can put it at another place. The dictionaries www/i18n/<language>.json have the English texts as the keys: en.json lists all texts (the catalog for a new language; it can also change the English texts), ru.json has the Russian ones. The language is the choice of the user (the user menu, the login page) or the first language of the browser which the interface has (the whole tag, e.g. pt-BR, or its language, pt), English by default; the page is loaded again after the choice. Every language has its own file. To add a language, copy en.json to <code>.json (e.g. de.json or pt-BR.json), translate the values and add {"code": "<code>", "name": "<name in the language>"} to i18n/languages.json: the code is not changed, the language appears in the user menu and on the login page. The test I18nTest (ctest) checks that en.json has every text of the pages, that languages.json lists English and every dictionary and that every dictionary has the same texts with the same parts {name}. The titles of the pages of pages.json are translated if the dictionary has them; the texts of the description of the parameters come from the application and are shown as they are.

Components (js/ui/): elements, icons, tabs, dialogs, confirmations, notifications, loading indicators and menus in the WAI-ARIA patterns (keyboard, screen readers), the HTML templates of the pages. The pages get them in ctx.ui (see Components of Page development); the shell uses them too (the loading indicator while a page is loaded, a notification for a failed command and when the connection is restored).

Pages are set in WebControlPanel/config/pages.json (format: Rules of pages.json): id, title, icon (a symbol of icons/sprite.svg), type and roles of each page, the cards of the Dashboard and their roles. The service checks the file at start and gives each role only its pages; the rights are checked on every request (see Service webpanel). To add a page, put its folder into www/pages/<id>/ and add it to pages.json: the C++ code is not rebuilt (with the pages built into the service, see Build, the service is built again); the steps, an example and the reference are in Page development.

Table 4 - Types of pages.

Type Page
parameters Form built from the description of the parameters (/api/app/config). The field groups selects the groups of the page by their id (all groups without the field). The values are requested 2 times per second (/api/app/params); a field which the user is editing (text or number field before Enter, slider while it is moved) keeps the user value. For the role viewer all elements are read only. Without the connection to the application the page shows “No connection to the application” and waits for it.
video WebRTC player of the stream (stream, see Video) with the buttons over the video (controls: a click command or push / release commands) and the command of a click on the frame (click: the value <x>x<y> in percents of the frame). Under the video: the state of the player, the statistics (codec, size, FPS, bitrate, lost packets, jitter), the snapshot (PNG file) and the full screen. The role viewer gets no buttons and no click.
module Page with its own template and code (module, see Page development) and its requests (api: "<method> <path>", GET, POST, PUT or DELETE). The service gives a request which only module pages make (/api/system/journal) only to the roles of a page with it in api; the requests of the shell (session, pages, system information) and of admin (/api/admin/…) keep their own rules, so api lists them for the reader of the page. Example: pages/logs/page.js with the template page.html for the role admin, three tabs: the last 200 records of the system journal (/api/system/journal) with the filter by priority and the whole record in a dialog, the last login attempts (/api/system/info) and, for admin only, the security events of the service (/api/admin/audit: the event, the user, the address and the message, the filter of the warnings and errors, the record in a dialog).

Dashboard (pages/dashboard/page.js): the cards of dashboard.cards of pages.json in their order. The metrics (/api/system/metrics) are requested once per second, the information (/api/system/info) once per 30 seconds; the service keeps the history of 5 minutes, so the charts are full at the opening. The cards are placed in columns by the width of the screen: 1 on a phone, 2 on a tablet (600…1023 px), 3 on a PC (from 1024 px), 4 from 1600 px; the card Load takes 3 rows next to the other cards (1 column of 2, 2 columns of 3 or 4), in a narrow card the names of the values are above them.

Table 5 - Cards of the Dashboard.

Card Data
system Host name, board model (device tree or DMI), OS, kernel, uptime, time and time zone, versions of the template and of the application.
load CPU load (total and by cores) and memory (circular indicators), load average, charts of 5 minutes (CPU, memory, network received and sent), memory and swap, disks, temperatures, network interfaces (received and sent per second, addresses). Indicators are yellow from 70 %, red from 90 %.
application Connection to the application, its version and uptime, video streams (name, codec, resolution, FPS, bitrate, viewers); without video the reason (e.g. the mode STRICT_FIPS, no H264 encoder).
security Cryptography mode (FIPS 140-3 or standard), module (OpenSSL FIPS Provider and its version, or the version of OpenSSL), self test of the FIPS module (passed or failed; not run in the standard mode), video server (MServer version and its mode), cryptography of the video server (the mode of the process of the application, its module and the self test of the FIPS module), video in the FIPS module (fully or not fully: the MServer field fullModuleCoverage; WebRTC derives its SRTP keys outside the module), External Protocol of the application (off, or the ports and the address in yellow: no authentication), certificate of the server and its validity (yellow less than 30 days before the end). Last login attempts (time, user, address, result): for admin only.
video Preview of the stream of the card (stream): the WebRTC player without controls.

All 8 elements of the description are supported on the parameters pages:

Table 6 - Elements of the parameters page.

Element Control Command
TEXT_FIELD Text field. The value is sent on Enter or focus loss, Escape restores the value of the application. {"Command": name, "Value": text}
DROPDOWN List of enumValues. {"Command": name, "Value": value}
SWITCH On/Off switch. {"Command": name, "Value": "On"} or "Off"
INPUT_NUMBER Number field with min and max; INT accepts only integers, FLOAT any numbers. An invalid value is not sent, the field shows the reason. {"Command": name, "Value": "<number>"}
SLIDER Slider with min and max and the current value. The value is sent on release. {"Command": name, "Value": "<number>"}
COMMAND_BUTTON Button with buttonText. {"Command": name}
PUSH_RELEASE_BUTTON Button: press (pointer, Space or Enter) sends push, release sends release. {"Command": push}, {"Command": release}
DIVIDER Subheading with a line inside a group (only a line without label). —

The elements TEXT_FIELD, DROPDOWN, SWITCH, INPUT_NUMBER and SLIDER are editable only with access READ_WRITE. If the application rejects the value of a text or number field, the field shows “The application rejected the value” and returns to the value of the application. An invalid element (unknown type, missing fields) is shown with the reason and doesn’t stop the rendering of the page. Groups are collapsible. The interface has light and dark themes (system setting by default, the user menu chooses them) and adapts to screens from 320 px wide.

Page development

The pages of the interface are HTML and JavaScript files without frameworks, npm and build: the files of WebControlPanel/www go to the browser as they are. A page of the type parameters or video is only an entry of pages.json (Table 4): its elements and commands are described by the application. A page with its own code (type module) is a folder of www/pages with two kinds of files:

  • the template (page.html) - the markup of the page: cards, toolbars, lists, tables, buttons and their texts, which are translated;
  • the module (page.js) - a JavaScript module which loads the template, writes the data of the requests of the service to its elements and handles the events.

The markup is made in the template; the module makes only the elements which depend on the data (e.g. the rows of a table) with el(...) (see Components). The C++ code is not changed. This section is the guide for such pages: an example, the life cycle of a page, what the shell gives to it, the templates, the requests of the service, the styles, the rules, the limits and the checks.

Example: a page in five steps

The page “Device” shows the time and the uptime of the device to the roles operator and admin.

1. The template WebControlPanel/www/pages/device/page.html: a card with a list of two values. data-i18n - the text of the element is translated, data-ref - the element is given to the module:

<section class="card">
    <div class="card-header"><h2 class="card-title" data-i18n>Device time</h2></div>
    <div class="card-body">
        <dl class="info-list">
            <dt data-i18n>Time</dt><dd data-ref="time"></dd>
            <dt data-i18n>Uptime</dt><dd data-ref="uptime"></dd>
        </dl>
    </div>
</section>

2. The module WebControlPanel/www/pages/device/page.js exports two functions: mount(root, ctx) shows the page in the element root, unmount() stops it (see Life cycle):

// @ts-check
import { formatDuration } from "../../js/ui/format.js";

/**
 * Device page: the time and the uptime of the device, once per second. The
 * markup is the template page.html.
 * @typedef {import("../../js/app.js").PageContext} PageContext
 */

/** Counter of the mounts: an answer for an unmounted page is not shown. */
let mountCounter = 0;
/** Timer of the next request. */
let timer = 0;

/**
 * Show the page.
 * @param {HTMLElement} root Element of the page.
 * @param {PageContext} ctx Context of the page.
 */
export async function mount(root, ctx) {
    const counter = ++mountCounter;
    const { content, refs } = await ctx.ui.template("pages/device/page.html", ["time", "uptime"]);
    if (counter !== mountCounter) {
        return;
    }
    root.replaceChildren(content);

    const update = async () => {
        try {
            // A background request doesn't extend the idle timeout of the session.
            const metrics = /** @type  */ (
                await ctx.api.get("/api/system/metrics", { background: true }));
            if (counter !== mountCounter) {
                return;
            }
            refs.time.textContent = metrics.time ?? "";
            refs.uptime.textContent = formatDuration(metrics.uptime ?? 0);
        } catch {
            // No answer: the shell shows "No connection to the service".
        }
        if (counter === mountCounter) {
            timer = window.setTimeout(update, 1000);
        }
    };
    await update();
}

/** Stop the requests of the page. */
export function unmount() {
    mountCounter += 1;
    window.clearTimeout(timer);
}

ctx.ui.template(...) loads the template and gives its elements: content goes into the page, refs.time and refs.uptime are the <dd> elements of data-ref (see HTML templates); update() writes the values into them once per second. counter is the number of this opening of the page: if the user goes to another page while the template or a request is loaded, unmount() changes mountCounter, and the old opening doesn’t show its page and plans no next request. setTimeout (not setInterval) plans the next request after the answer to the previous one, so slow answers don’t pile up requests.

3. The entry of the page in the array pages of WebControlPanel/config/pages.json (the order of the array is the order of the menu):

{
    "id": "device",
    "title": "Device",
    "icon": "server",
    "type": "module",
    "roles": ["operator", "admin"],
    "module": "pages/device/page.js",
    "api": ["GET /api/system/metrics"]
}

4. The texts. Every new text of the template (data-i18n, data-i18n-attr) and of the module (t("...")) is added to www/i18n/en.json and to every other dictionary (ru.json), the title of the page too (it is translated if the dictionary has it); “Time” and “Uptime” are already there (see Texts and languages):

"Device": "Устройство",
"Device time": "Время устройства"

(in en.json: "Device": "Device", "Device time": "Device time").

5. Build and check. cmake --build build copies the pages and pages.json to build/bin (with -DWEB_CONTROL_PANEL_EMBED_WWW=ON it builds them into webpanel), ctest runs I18nTest (it fails if a dictionary has no text of the page). Restart the service: it reads pages.json only at start. On a device the files are /usr/share/webpanel/www/pages/<id>/ and /etc/webpanel/pages.json (see Installation). The page is at #/page/device; the role viewer doesn’t get it in the menu.

Pages of the sources. During the development the service of the build folder can give the files of the sources: set the absolute paths in webServer of build/bin/webpanel.json (the build doesn’t change this file) and start the service as in Quick start:

"wwwFolder": "/home/user/WebControlPanelTemplate/WebControlPanel/www",
"pagesFile": "/home/user/WebControlPanelTemplate/WebControlPanel/config/pages.json"

A changed template or module is then shown after a reload of the browser (F5) without a build; a changed pages.json needs a restart of the service.

Life cycle

  1. The shell loads the module at the first opening of the page (import()). The browser keeps it: the variables of the module (outside of the functions) stay between the openings of the page.
  2. At every opening the shell shows the title of the page (title of pages.json, translated) and the state of the connection, gives an empty element root and calls mount(root, ctx): the page loads its template, puts it into root and starts its requests. mount can be async: its exception shows “Error of the page: <message>” instead of the page (e.g. a template which can’t be loaded); a module which can’t be loaded (e.g. a syntax error) shows “Can’t load the page: <message>”.
  3. When the user goes to another page (menu, Back button, address), the shell calls unmount() and removes root: the page stops its timers, requests, players and pressed buttons.
  4. The logout, the end of the session (the answer 401 of any request) and the choice of a language load the document again: the shell calls unmount() before, the page gets mount(...) again in the new language. The choice of a theme changes only the CSS variables: the styles follow by themselves, ctx.theme() gives the theme to a drawing of JavaScript (e.g. a canvas).
  5. The card Commands under the page is of the shell: it lists the commands of all pages (ctx.api.command(...)).

A page leads to another page by a link of its template, <a href="#/page/video" data-i18n>Video</a>, or by location.hash = "#/dashboard".

Context of a page

mount(root, ctx) gets the context of the page (Table 7): it is all a page needs from the shell. The modules of the shell can also be imported directly (Table 8).

Table 7 - Context of a page (ctx).

Field Content
page Entry of the page in /api/pages: id, title, icon, type and module (a module page has no other fields: pages.json doesn’t accept them).
user User of the session: name and role (“admin”, “operator” or “viewer”). Only for the view, e.g. no buttons for viewer: the service checks the rights of every request itself.
theme() Current theme: “light” or “dark”.
api Requests to the service: get, post, send, command (see Sending requests).
ui Template of the page: template (see HTML templates); components: el, icon, tabs, dialog, confirm, notify, spinner, menu (see Components).
i18n t(text, values) - translation of a text, language() - code of the language of the interface (see Texts and languages).

HTML templates

ctx.ui.template(path, required) loads a template of the page and gives the promise of { content, refs }:

  • path - a file of the folder of the page, pages/<id>/<name>.html, of the folder of the pages as the module (the address of the document doesn’t matter). A page can have several templates, e.g. page.html and the form of a dialog (see dialog of Components). The file is loaded once, every call makes new elements: mount(...) after unmount() gets new ones. The user can leave the page while the template is loaded: the check of counter after await, as in the example.
  • content - the elements of the template (DocumentFragment): it is put into the page once (root.replaceChildren(content), root.append(content)); an element of refs can also go elsewhere, e.g. into a panel of tabs(...).
  • refs - the elements with the attribute data-ref, by its value; required - the values which the template must have, so a changed template doesn’t break the module silently.
  • The texts are translated as in index.html: the text of an element with data-i18n (the element has only the text) and the attributes of data-i18n-attr (e.g. data-i18n-attr="aria-label title"); I18nTest finds these texts.
  • A template is a part of the body of an HTML document: no html, head and body elements. An icon is <svg class="icon" aria-hidden="true" focusable="false"><use href="icons/sprite.svg#refresh"/></svg> (as icon("refresh")), the ids are unique on the page (the id of the page as their prefix, e.g. logs-priority).
  • A template is the markup, not the data: the module writes the values to refs as text (textContent), the rows of a table of data are elements of el(...) in a tbody of the template, a text with a value is t("...", values) of the module.
  • The loader refuses a path which is not of a template of a page, a file which is not loaded, an element script, style, link, meta, base, iframe, frame, frameset, object or embed, a value of data-ref twice and a missing required value: it throws an error, and the page shows “Error of the page: <reason>”. The Content-Security-Policy blocks the attributes onclick="..." and style="..." of a template, api/headers checks the templates for them.

The page Logs of the repository is made so: pages/logs/page.html has the panels of its tabs (the toolbars, the filters and the headers of the tables), pages/logs/page.js makes the tabs, the rows of the tables and the dialogs of the records.

Sending requests

ctx.api sends the requests of the page to the service with the cookie of the session and the CSRF token (the shell keeps them):

  • get(path, { background }) - GET, the promise of the JSON answer. background: true for a request which the user didn’t make (polling, repeated attempts): it doesn’t extend the idle timeout of the session.
  • post(path, body) - POST of the object body as JSON, the promise of the JSON answer.
  • send(path, { method, body, contentType, keepalive, background }) - a request which is not JSON or has another method (e.g. DELETE): the promise of the Response of any status (response.ok, response.status, await response.json()).
  • command({ Command, Value }) - command of the application (POST /api/app/command; the value is a string, a button has no Value): the promise of TRUE if the application accepted it. It doesn’t throw: the command and its result are written to the card Commands, and the shell shows a notification if it failed.

get and post wait at most 3 s, send 10 s. get and post throw ApiError for an answer with an error (its status: 403 - no rights, 429 - too many requests, 503 - no connection to the application) and another error if there is no answer. After the answer 401 (the session has ended) the shell goes to the login page itself, and it shows the loss of the connection to the service, so a polling page can ignore the errors and try again. A page which shows the errors:

import { ApiError, isNetworkError, messageOf } from "../../js/api.js";

try {
    const answer = await ctx.api.get("/api/app/params");
    // ... show the values
} catch (error) {
    if (error instanceof ApiError && error.status === 503) {
        refs.message.textContent = t("No connection to the application");
    } else if (!isNetworkError(error)) {
        ctx.ui.notify(messageOf(error), { type: "error" });
    }
}

An answer is unknown for the checker of the types: a page checks its fields before using them, as readEntries(...) of pages/logs/page.js, or describes the expected type with /** @type {...} */, as the example above.

Components

ctx.ui gives the components of the shell (js/ui/). They follow the theme and the WAI-ARIA patterns (keyboard, screen readers); the shell uses them too. The markup of a page is its template: el(...) makes the elements which depend on the data, the other components work with the elements of the template.

  • el(tag, attributes, children) - an element: the attributes are set by setAttribute, the children are elements and texts (a text is always text, never HTML). The rows of a table of the template (<tbody data-ref="streams"></tbody>) from the streams of /api/system/info:

    refs.streams.replaceChildren(...streams.map((stream) => el("tr", {}, [
        el("td", {}, [stream.name]),
        el("td", {}, [stream.codec]),
    ])));
    

    The events are listeners of the elements, not the attributes onclick: refs.apply.addEventListener("click", () => save()).

  • icon(name) - an icon of icons/sprite.svg for an element of el(...) (hidden from screen readers); a template has the same markup <svg class="icon" ...>. A button with only an icon gets its name in aria-label and title, translated by data-i18n-attr:

    <button type="button" class="icon-button" aria-label="Refresh" title="Refresh" data-i18n-attr="aria-label title"
            data-ref="refresh">
        <svg class="icon" aria-hidden="true" focusable="false"><use href="icons/sprite.svg#refresh"/></svg>
    </button>
    
  • tabs(tabs, { label, selected, onChange }) - tabs: { element, select(id), selected() }, only the panel of the selected tab is shown (onChange is called when the user selects a tab). Left and Right select the previous and the next tab, Home and End the first and the last. The panels are elements of the template: card-body elements or a toolbar and a table. A card with a toolbar and tabs:

    <section class="card" data-ref="card">
        <div class="toolbar">
            <!-- buttons -->
        </div>
    </section>
    <div class="card-body" data-ref="state">
        <dl class="info-list">
            <dt data-i18n>Time</dt><dd data-ref="time"></dd>
        </dl>
    </div>
    <div class="card-body" data-ref="history"></div>
    
    const view = ctx.ui.tabs([
        { id: "state", label: t("State"), panel: refs.state },
        { id: "history", label: t("History"), panel: refs.history },
    ], { label: t("Device") });
    refs.card.append(view.element);
    root.replaceChildren(content);
    
  • dialog({ title, content, actions, wide, onAction }) - modal dialog (native <dialog>): the promise of the value of the pressed button, null for Esc, the close button and a click outside. content - nodes and texts, e.g. the content of a template. A button is { label, value, kind, focus } (kind: “primary”, “secondary” or “danger”; one button “Close” by default). onAction(value) (may be async) is called when a button is pressed: FALSE keeps the dialog open (e.g. for an error of a field), the buttons are disabled while it runs. The focus returns to the previous element. The form of a dialog in its own template pages/device/rename.html:

    <label for="device-name" data-i18n>Name</label>
    <input class="input" id="device-name" maxlength="64" data-ref="name">
    <p class="field-error" role="alert" hidden data-ref="error"></p>
    
    const form = await ctx.ui.template("pages/device/rename.html", ["name", "error"]);
    const input = /** @type {HTMLInputElement} */ (form.refs.name);
    const result = await ctx.ui.dialog({
        title: t("Rename"),
        content: [form.content],
        actions: [{ label: t("Cancel"), value: "cancel" }, { label: t("Save"), value: "save", kind: "primary" }],
        onAction: (value) => {
            if (value === "save" && input.value === "") {
                form.refs.error.textContent = t("Enter the name");
                form.refs.error.hidden = false;
                return false;
            }
            return true;
        },
    });
    
  • confirm(message, { title, confirm, danger }) - confirmation of an action: the promise of TRUE or FALSE; with danger the confirming button is red and the focus is on “Cancel”:

    if (await ctx.ui.confirm(t("Restart the device?"), { confirm: t("Restart"), danger: true })) {
        // ...
    }
    
  • notify(message, { type, timeout }) - notification at the corner of the page: type info, success (5 s), warning or error (10 s; screen readers read an error at once, the others after the current speech), timeout in milliseconds (0 - until the user closes it); returns the function which hides it. The pointer or the focus keeps it, at most 4 are shown:

    ctx.ui.notify(t("Saved"), { type: "success" });
    
  • spinner(label, { visibleLabel, large }) - loading indicator: the text is read by screen readers, with visibleLabel it is also shown; with prefers-reduced-motion the ring pulses instead of rotating:

    refs.list.replaceChildren(ctx.ui.spinner(t("Loading…"), { visibleLabel: true }));
    
  • menu(button, label, build) - menu of a button: { element, close() }. build() gives the groups of the items at every opening, so the items show the current state: [{ label, items: [{ label, icon, checked, disabled, select }] }] (an item with checked is a choice). Down, Up, Home and End move, Enter and Space select, Esc and a click outside close it, the focus returns to the button. The button of the template is in a container menu-anchor, the menu goes after it: it opens under the left edge of the button (menu-anchor menu-anchor-end - under its right edge, for a button at the right end of a toolbar):

    <div class="menu-anchor">
        <button type="button" class="btn btn-secondary" data-ref="actions" data-i18n>Actions</button>
    </div>
    
    const menu = ctx.ui.menu(/** @type {HTMLButtonElement} */ (refs.actions), t("Actions"), () => [
        { items: [{ label: t("Rename…"), icon: "settings", select: () => void rename() }] },
    ]);
    refs.actions.after(menu.element);
    

Texts and languages

  • Every text of a page is translated: the texts of the template by data-i18n (the text of an element) and data-i18n-attr (its attributes, e.g. aria-label and title), the texts of the module by t("..."). The English text is the key of the dictionaries www/i18n/<language>.json, a text without a translation is shown in English.
  • I18nTest finds the texts of the pages: data-i18n and data-i18n-attr in the html files, the calls t("...") in the js and html files of www. So the function is called t (const { t } = ctx.i18n, no other name) and its first argument is the text itself in double quotes: t(name), t('...') and t(`...`) are not found, and a missing translation of such a text is not noticed.
  • A text with a value is made by the module: a part {name} of the text, t("Stream {stream}", { stream }), so a translation can put it at another place.
  • A new text goes to en.json and to every other dictionary: the test checks that all dictionaries have the same texts with the same parts {name}. The title of a page is translated if the dictionary has it.
  • Dates and numbers in the language of the interface: new Date(time).toLocaleString(ctx.i18n.language()).
  • The data of the device and of the application (names, messages of the journal) is shown as it is, without t.

Modules of the shell

A page imports the modules of the shell by their paths from its folder, e.g. import { formatBytes } from "../../js/ui/format.js" (Table 8).

Table 8 - Modules of the shell for the pages.

Module Exports
js/api.js ApiError - error of an answer (status); isNetworkError(error) - no answer (network error, timeout); messageOf(error) - text of an error for the user.
js/ui/format.js formatBytes(bytes) - “1.5 KB”; formatRate(bytesPerSecond) - “1.5 MB/s”; formatBitrate(bits) - “2.50 Mbit/s”; formatDuration(seconds) - “3 d 04:05:06”; formatPercent(value) - “42%”.
js/charts.js createLineChart({ title, series, format, slots, max }) - chart of a history: { element, update(data) }, data - the values of each series from old to new; createRing(label), createMeter(label) - circular and bar indicator of a percent: { element, update(percent, text) }, yellow from 70 %, red from 90 % (levelOf(percent)).
js/ui/hold.js bindHold(button, push, release) - push/release button (pointer, Space, Enter): returns the function which releases it.
js/video/whep.js WhepPlayer - WebRTC player of a stream; stateText(state, message) - text of its state; videoOffText(reason) - why the application has no video (videoOff of /api/system/info).

A chart of the metrics in an element of the template (the history of /api/system/metrics has one value per second for 5 minutes; the series have the colors chart-series-1 and chart-series-2):

import { createLineChart, createRing } from "../../js/charts.js";
import { formatPercent } from "../../js/ui/format.js";

const chart = createLineChart({ title: t("CPU, 5 minutes"), series: [{ name: t("CPU"), className: "chart-series-1" }],
    format: formatPercent, slots: 300, max: 100 });
const ring = createRing(t("CPU"));
refs.history.append(chart.element, ring.element);
// update(): the answer of /api/system/metrics.
chart.update([metrics.history.cpu]);
ring.update(metrics.cpu.total);

A video with a push/release button: the player shows a stream of a video page or a video card of the role (it connects again by itself after a loss of the connection), the button sends the commands of the buttons of a video page of the role:

<section class="card">
    <div class="card-header"><h2 class="card-title" data-i18n>Video</h2></div>
    <div class="card-body">
        <div class="video-frame"><video class="video-element" playsinline muted data-ref="video"></video></div>
        <p data-ref="videoState" data-i18n>Connecting…</p>
        <button type="button" class="btn btn-secondary btn-hold" data-ref="zoom" data-i18n>Zoom in</button>
    </div>
</section>
import { bindHold } from "../../js/ui/hold.js";
import { WhepPlayer, stateText } from "../../js/video/whep.js";

const video = /** @type {HTMLVideoElement} */ (refs.video);
video.muted = true;
video.setAttribute("aria-label", t("Video stream {stream}", { stream: "Cam" }));
player = new WhepPlayer(video, "Cam", ctx.api, {
    onState: (value, message) => {
        refs.videoState.textContent = stateText(value, message);
    },
    // onStats: (stats) => ... - fps, bitrate, width, height, codec, packetsLost, jitter once per second.
});
player.start();
releaseZoom = bindHold(/** @type {HTMLButtonElement} */ (refs.zoom),
    () => void ctx.api.command({ Command: "Lens/ZoomTele" }),
    () => void ctx.api.command({ Command: "Lens/ZoomStop" }));
// unmount(): player.stop() closes the video session (DELETE), releaseZoom() sends the release if the button is
// still pressed.

Requests of the service

Table 9 - Requests of the service for the pages (the answers: Table 12).

Request Roles Data
GET /api/system/info every role (logins: admin) Host, board, OS, versions, application and its streams, cryptography, certificate.
GET /api/system/metrics every role Time, uptime, CPU, memory, disks, temperatures, network, history of 5 minutes.
GET /api/app/config every role Description of the groups of the parameters pages of the role.
GET /api/app/params every role Values of the elements of these groups.
POST /api/app/command operator, admin Commands of the elements of the parameters pages of the role and of the buttons and the click of its video pages (ctx.api.command).
POST /api/video/{stream}/whep, DELETE /api/video/{stream}/whep/{id} every role WebRTC of a stream of a video page or a video card of the role (WhepPlayer).
GET /api/system/journal roles of a module page with it in api Last 200 records of the system journal.
GET /api/admin/audit, /api/admin/certificate, /api/admin/settings admin Security events, certificate of the HTTPS server, settings.

The rights are of the role, not of the page: a request of api is given to a role if any module page of the role lists it (admin gets /api/system/journal from the page “Logs”).

Styles

The templates use the classes of www/css/components.css (Table 10): they follow the theme, the width of the screen and the touch screens (controls of 44 px).

Table 10 - Classes of the components.

Classes Element
card, card-header, card-title, card-body Card: a panel with a frame; its header (title and buttons); its content.
toolbar, toolbar-summary Row of the controls at the top of a card; a text at its right end (e.g. “200 records”).
table-wrap, table Table, scrolled horizontally on a narrow screen.
info-list List <dl> of names (<dt>) and values (<dd>) in two columns.
btn with btn-primary, btn-secondary, btn-danger, btn-link Buttons: the main action, another action, an action which can’t be undone, a button which looks like a link.
icon-button Button with only an icon (aria-label and title).
btn-hold Push/release button (bindHold): pressed while held.
input, input-small, input-number Text field or list <select>; of the width of its content; number field.
switch On/off switch: <input type="checkbox" class="switch" role="switch">.
field-error, field-note Error of a field (role="alert"); note under a field.
alert with alert-error, alert-warning, alert-success Message across the page.
menu-anchor, menu-anchor-end Container of a button and its menu.
video-frame, video-element Frame 16:9 of a video (black, the video fits into it) and the <video> of a player in it.
visually-hidden Text only for screen readers.

The layout of a page: cards one under another (section.card, the shell puts the card Commands under them), messages across the page (alert). A card has a header (card-header) and its content (card-body), or a toolbar and a table (toolbar, table-wrap), or a toolbar and tabs (see tabs of Components).

Styles of a page. A page with classes of its own has the file pages/<id>/page.css (a template has no <style> and <link>), and the module adds it at its first mount(...); the names of its classes begin with the id of the page, so they don’t change the other pages:

const STYLE = "pages/device/page.css";
if (!document.querySelector(`link[href="${STYLE}"]`)) {
    document.head.append(ctx.ui.el("link", { rel: "stylesheet", href: STYLE }));
}
/* pages/device/page.css */
.device-value {
    color: var(--color-primary);
    font-family: var(--font-mono);
}

The colors, the spaces and the fonts are the variables of css/theme.css and css/tokens.css, so a class has its colors in both themes: --color-surface, --color-surface-alt, --color-text, --color-text-muted, --color-border, --color-primary, --color-danger, --color-warning, --color-success, --space-1…--space-6 (4…32 px), --radius, --font-mono, --control-height. The widths of the screen: less than 600 px - phone (the side menu slides out), 600…1023 px - tablet, from 1024 px - PC; the content is at most 1600 px wide. A page has no horizontal scroll from 320 px (a wide table goes into table-wrap).

Rules of pages.json

The service checks the file at start; if it is not valid, the service doesn’t start and writes the reason to the log (e.g. Invalid pages.json: pages[4] (device): "icon" is not an icon of the sprite):

  • id - 1…32 symbols a-z, 0-9 and ‘-‘, unique;
  • module - only a file of the folder of the page: pages/<id>/<name>.js (letters, digits, ‘_’ and ‘-‘ in the name);
  • icon - a symbol of www/icons/sprite.svg; a new icon is a new <symbol id="<name>" viewBox="0 0 24 24"> of the sprite (lines of currentColor, as the other icons, so it follows the theme);
  • roles - viewer, operator and admin;
  • api - the requests of the page: "<method> /api/<path>", GET, POST, PUT or DELETE; the field is required, "api": [] for a page without requests.

Rules of the code of a page

  • The markup is in the template, the data is shown as text: textContent and el(...), never innerHTML (the data of the device and of the users is not HTML). The only HTML which the interface parses is a template of a page: a file of the pages, not data (see HTML templates).
  • The Content-Security-Policy of the pages (script-src 'self'; style-src 'self'; connect-src 'self') blocks inline code: <script> and <style> elements, the attributes style="..." and onclick="...", and the scripts, the styles and the fonts of other hosts (a CDN; a device usually has no Internet). The styles are the classes of css/components.css and of the file of the page (see Styles); a computed value goes to element.style.setProperty(...) (allowed by the policy).
  • The files of the pages are only html, css, js, json, svg, png and ico, with names of letters, digits, ‘-‘, ‘_’ and ‘.’. A page has its templates and can import its own modules of its folder (e.g. pages/parameters/parameters.js) and the modules of the shell (Table 8).
  • The files of the pages are given without a session (as the login page): they contain no data and no secrets. The data of the device comes only from the requests of the API, which need a session and check the role.
  • The timers, the requests, the players and the push/release buttons which mount(...) starts are stopped by unmount(); an answer which comes after unmount() is not shown (the counter of the mounts of the example). Polling requests are background ones ({ background: true }).
  • Native elements (<button type="button">, <input>, <select>) with a <label for> or aria-label: the keyboard and the screen readers work with them. A value which changes by itself is not announced (no aria-live on polled values), only a result which the user waits for (e.g. a toolbar-summary with aria-live="polite").
  • // @ts-check and the JSDoc types, as in the modules of the shell: an editor with TypeScript (e.g. VS Code) checks the module with the types of the shell (PageContext).

What a module page can’t do

  • Commands of the application. The service accepts POST /api/app/command only with the commands of the elements of the parameters pages of the role and of the buttons and the click of its video pages; other commands get 403 (the role viewer gets 403 for every command). A module page sends ctx.api.command({Command: "<Group>/<Name>", Value: "<value>"}) only for a command which a parameters or video page of the same role has.
  • Requests of its own. api gives the roles of the page the requests which the service has (Table 9), it doesn’t add requests: the request of a new kind of data is a handler of WebControlPanel/src/Service/ServiceApi.cpp with the check of the rights canRequest(role, method, path) of Pages, like /api/system/journal. The values of the application are /api/app/params of the groups of the parameters pages of the role.
  • Video. The player WhepPlayer shows a stream only if a video page or a video card of the role has it (403 otherwise).
  • Fields of its own in pages.json. A module page has only id, title, icon, type, roles, module and api: the settings of a page are constants of its module or values of the application.
  • Cards of the Dashboard. The cards are system, load, application, security and video (Table 5): a card of a new kind is code of pages/dashboard/page.js and of the check of the cards of Pages (C++).

Checking a page

  • ctest: I18nTest checks the texts of the template and of the module in the dictionaries.
  • The console of the browser (F12): the errors of the module and of the template, the refused requests (403) and the blocked inline code (Content-Security-Policy). The errors of loading and of mount(...) are shown instead of the page.
  • The log of the service: the commands of the page and the refused requests.
  • api/headers (system check) checks the files of the pages: no inline code, no HTML of data, the templates without scripts, styles, frames and objects.
  • System checks (see Checks of the code): api/roles.py checks the pages of the roles of config/pages.json of the template, so a changed pages.json needs its lists (check("pages of the role", ...)) changed. A check of a new page is a file WebControlPanel/tests/system/api/<name>.py with the function run(bench) and its name in API_CHECKS of run_checks.py; python3 WebControlPanel/tests/system/run_checks.py api/device runs it:

    """Page device: the roles which get it, its files and its request."""
    
    
    def run(bench):
        bench.start_service()
        for role, expected in (("admin", True), ("operator", True), ("viewer", False)):
            session = bench.login(role)
            pages = bench.request("GET", "/api/pages", headers=session.headers()).json()
            ids = [page["id"] for page in pages["pages"]]
            bench.check(f"[{role}] page device {'given' if expected else 'not given'}", ("device" in ids) == expected, ids)
            metrics = bench.request("GET", "/api/system/metrics", headers=session.headers())
            bench.check(f"[{role}] request of the page", metrics.status == 200 and "uptime" in metrics.json(),
                        metrics.status)
        for path in ("/pages/device/page.js", "/pages/device/page.html"):
            bench.check(f"file {path}", bench.request("GET", path).status == 200)
        bench.stop_service()
    

    The checks of the interface in a browser are pages of tests/system/e2e which send their results as commands (e.g. e2e/ui.js).

Login

The login has two modes (param auth.mode of the service):

  • pam - the system users, the installed configuration. A user logs in with the password of the system account and gets the role of their Linux groups: webpanel-admin, webpanel-operator, webpanel-viewer (params auth.adminGroup, auth.operatorGroup, auth.viewerGroup; the highest role of the groups of the user). A user without these groups, root, a locked user (usermod -L, passwd -l), an expired account (chage -E) and an expired password (chage -d 0) don’t log in. Every auth.recheckPeriod seconds (5 minutes) the service checks the accounts of the users of the sessions again: the sessions of a user whose account has expired or who has left the groups end; after a change of the groups the sessions with the previous role end. To end the sessions of a user, expire their account: sudo usermod -L -e 1 <user>; the sessions end at the next check of the accounts, at most auth.recheckPeriod later (a locked password alone stops the next logins, PAM doesn’t check it without the password). The users of an LDAP server log in so too, through SSSD of the system (see LDAP users below).
  • file - the test accounts of users.json (Table 11): only in a build with -DWEB_CONTROL_PANEL_TEST_ACCOUNTS=ON, for the checks of the login without the system accounts (the system checks). The service of a device has no such mode: with it in the configuration the service doesn’t start.

PAM helper. The service runs without root and doesn’t read the passwords of the system. The password is checked by the small helper webpanel-auth (WebControlPanel/auth, about 490 lines): systemd starts it as root for each connection of the socket /run/webpanel-auth.sock (webpanel-auth.socket, Accept=yes, at most 4 at a time, without the trigger limit of systemd). The service makes at most 4 connections at once: a login or a confirmation over them gets the answer 503. The helper:

  • answers only the user of the service (–user webpanel, the kernel gives the user of the client by SO_PEERCRED; the socket file belongs to the group webpanel, mode 0660);
  • calls only pam_authenticate and pam_acct_mgmt of the PAM service webpanel (/etc/pam.d/webpanel: common-auth, common-account and a delay of 2 s for a failure; empty passwords are refused);
  • checks only the members of the groups of the roles and never root (unless –allow-root), so the service can’t be used to guess the passwords of other users; for them PAM checks a user which doesn’t exist, so the answer takes the time of a wrong password. The groups of the roles are the ones of the settings of the service which it sends with each request (some of –groups): a member of a group which admin took from the roles is checked so too, also with the right password;
  • answers with the uid and the groups of the user among the groups of the roles; the service gets the role from them;
  • gives the service its groups of the roles (command “groups”): the settings of admin may give the roles only these groups (see Settings of Service webpanel).

A user name which the helper doesn’t take (1…32 letters, digits, ‘_’, ‘.’ and ‘-‘, not ‘-‘ first; e.g. not alice@example.org: use the short names of SSSD) is a failed login (401) without the helper. If the helper doesn’t answer, the login answers 503 “Login is not available now” (not counted as a failed attempt) and the sessions stay until the next check. The helper of the build folder can be tried without the installation: the service of build/bin (it runs as your user) logs in the system users of the groups of the roles through it (auth.mode “pam” is the default):

sudo cp WebControlPanel/pam/webpanel /etc/pam.d/webpanel
sudo groupadd --system webpanel-admin; sudo groupadd --system webpanel-operator; sudo groupadd --system webpanel-viewer
sudo usermod -aG webpanel-admin $USER    # the role of your account (a new login of the session of the OS is not needed)
sudo systemd-socket-activate -a --inetd -l /run/webpanel-auth.sock build/bin/webpanel-auth --user $USER &
sudo chmod 666 /run/webpanel-auth.sock    # the helper answers only the user of --user

Then log in with the name and the password of your account. The helper reads the groups of the system at each login.

LDAP users. The users of an LDAP server (OpenLDAP) log in through PAM like the system users: SSSD of the system gives them and their groups to the system (NSS and pam_sss in common-auth and common-account), so the helper checks their password and their groups as for a local user. The service has no LDAP client of its own and the login page has no choice of the kind of the account. The groups of the roles are LDAP groups: give their names to auth.adminGroup, auth.operatorGroup and auth.viewerGroup of the service and to –groups of the helper (ExecStart of webpanel-auth@.service), or name the LDAP groups webpanel-admin, webpanel-operator and webpanel-viewer. Install sssd-ldap libnss-sss libpam-sss (the packages add SSSD to NSS and to the PAM stacks) and write /etc/sssd/sssd.conf (mode 0600), for example:

[sssd]
services = nss, pam
domains = example

[nss]
memcache_timeout = 60

[domain/example]
id_provider = ldap
auth_provider = ldap
access_provider = ldap
ldap_uri = ldaps://ldap1.example.org, ldaps://ldap2.example.org
ldap_search_base = dc=example,dc=org
ldap_tls_reqcert = demand
ldap_tls_cacert = /etc/ssl/certs/example-ldap-ca.pem
ldap_access_order = expire
ldap_account_expire_policy = shadow
entry_cache_timeout = 300
cache_credentials = false
ldap_network_timeout = 3
ldap_opt_timeout = 5
  • TLS only: ldaps:// (636) or ldap:// with ldap_id_use_start_tls = true (StartTLS, 389). ldap_tls_reqcert = demand checks the certificate of the server by the CA of ldap_tls_cacert and the host name: a certificate of another CA refuses every login. Also with ldap:// without StartTLS SSSD starts TLS before the bind with a password (it is never sent in clear unless ldap_auth_disable_tls_never_use_in_production).
  • Several servers: a list in ldap_uri, SSSD goes to the next one if a server doesn’t answer (ldap_network_timeout, ldap_opt_timeout).
  • Expired accounts: ldap_access_order = expire with the policy of the accounts of the server (shadow - shadowExpire of the entry) refuses the login and ends the sessions at their next check.
  • Caches: the service checks the accounts of its sessions every auth.recheckPeriod (300 s); a change of the groups in LDAP reaches it after entry_cache_timeout of SSSD (5400 s by default) and memcache_timeout (300 s by default), so keep them not above auth.recheckPeriod as above. A login always gets the current groups: SSSD reads them at the authentication. cache_credentials = false: no login with a cached password while the server doesn’t answer.
  • Empty password: refused by the service before PAM (an LDAP bind with an empty password is anonymous, RFC 4513).
  • FIPS: TLS to LDAP is made by SSSD (libldap of the system), not by the service: on a system in FIPS mode (e.g. RHEL 9) it works with the module of the system; on Debian and Ubuntu libldap uses GnuTLS outside the FIPS module.

The stand WebControlPanel/tests/ldap (Docker) checks it: OpenLDAP with LDAPS and StartTLS, SSSD, the service and the helper of a build (users alice, bob, carol of the groups of the roles, dave without a group, erin expired; a second CA). WebControlPanel/tests/ldap/run.sh [<bin>] builds the image of Ubuntu 24.04, starts the container with the programs of build/bin (built for Ubuntu 24.04 or an older glibc), runs 20 checks (roles by the LDAP groups, refusals, the recheck of the sessions after a change in LDAP, LDAPS, StartTLS, TLS of the bind, a certificate of another CA, the groups of the roles in the settings of admin: a group which the helper doesn’t have and groups which would make the admin not admin refused, a changed group ends the sessions with another role at once) and removes the container.

Table 11 - Test accounts of WebControlPanel/config/users.json (mode file, a build with -DWEB_CONTROL_PANEL_TEST_ACCOUNTS=ON).

User Password Role
admin Admin#2026 admin: all pages, cards and commands, the journal, the login attempts
operator Operator#2026 operator: pages Parameters and Video, commands of these pages
viewer Viewer#2026 viewer: pages Parameters and Video, read only

These are test passwords of the repository, they are not installed and not in the service of a device. The file keeps the password hashes, not the passwords: {"name", "role", "passwordHash"} for each user, the hash is PBKDF2-HMAC-SHA256 with a random salt of 128 bits and 100000 iterations (pbkdf2-sha256$<iterations>$<salt>$<hash>). The name root is not allowed. A hash for a new password is printed by the service of such a build:

printf '%s\n' 'New#Password1' | ./webpanel --hash-password
  • Login page (login.html): user name and password; every failure gives the same message “Invalid user name or password” (the reason is written to the log of the service); the page doesn’t show the users. After the login the browser returns to the page which needed the login.
  • Session: the token is 256 random bits in the cookie __Host-wcp (Secure; HttpOnly; SameSite=Strict; Path=/); the server keeps only its SHA-256. The session ends after 15 minutes without actions of the user (the background requests of the pages, e.g. the values and the metrics, and the repeated attempts, e.g. of a video player whose connection is lost, don’t extend it) and 8 hours after the login (params auth.idleTimeout and auth.absoluteTimeout), or by the logout (button in the top bar). A user has at most 16 sessions: a new login ends the oldest of them; at most 256 sessions in all: a new login ends the oldest session of the user with the most sessions, which can be another user (such an ended session is in the journal, sessions_ended). When the session ends, the next request of the page goes to the login page.
  • CSRF: the changing requests (commands, logout) carry the CSRF token of the session in X-CSRF-Token, and a browser request must be of the same origin (Origin, Sec-Fetch-Site); otherwise the answer is 403.
  • Password guessing: an answer of a failure is delayed by 0.5 s for each failure in a row (3 s at most); after 5 failures in 5 minutes the client address and the user name are blocked for 5 minutes (answer 429; params auth.maxFailures and auth.blockTime); a successful login forgives only its own failures: those of the name and, of the address, the failures of this name from it, so an account of their own doesn’t let somebody try other names from an address; an unknown name takes the same time as a known one. Every attempt is written to the log, the last 50 attempts are shown to admin on the Dashboard (card Security).
  • Request rate: every request of a client address (pages, files and API) counts against its limit, by default 30 requests per second and 120 at once (params webServer.requestsPerSecond and webServer.requestBurst). A page of the interface polls about 3 requests per second, a load of the interface is about 40 requests. Over the limit the answer is 429 with Retry-After: 1 and {"error":"too many requests"}; the pages repeat their requests later, the login page shows “Too many requests”. The refusals of an address are written to the log at most once a minute ([SECURITY]: Too many requests from <address>: <number> refused).
  • Journal of the security events: the logins, the failed and blocked attempts, the logins refused as requests of another origin (login_refused), the logouts, the sessions ended by the check of the accounts or by the limits of the sessions, the commands (with the value which the application accepted), the refused command requests, the factory resets (also of the command line), the changes of the certificate and of the settings (also refused), the refused requests of the limit of the request rate and a start refused by the FIPS mode (crypto_failed) are written to the log of the service and to the system journal (journald) with the identifier webpanel, the facility authpriv and the fields WEBPANEL_EVENT (e.g. login, login_failed, command, factory_reset, certificate_changed), WEBPANEL_USER and WEBPANEL_ADDRESS: journalctl -t webpanel, journalctl -t webpanel WEBPANEL_EVENT=login_failed. The service writes to the socket of journald by its native protocol (no libsystemd); without journald the events are only in the log file. The module page “Logs” shows the system journal to its roles and, on the tab “Security events”, these events to admin (GET /api/admin/audit). Param journal = false turns the records off.

Service webpanel

The service webpanel (WebControlPanel/src/Service) is the only process of the WEB interface with a network port. It serves the pages and the API (Table 12) over HTTPS, keeps the sessions and checks the rights of the role on every request; the requests of the application go to it over its UNIX socket (AppBridge class), the WebRTC signalling to its video server (VideoProxy). All requests of the API except the login need a session (see Login). The classes and functions of the service and of its library WebControlPanelCore (WebControlPanel/src) are internal code of the module: they are in the namespace rapidpixel::webpanel_impl (coding standards of the RapidPixel SDK).

Connection to the application. Once per second the service asks the application for its state (GetInfo). At the first answer and after every new start of the application it reads the description of the parameters (GetConfig: the groups of the pages, the commands of the roles) and the WHEP endpoints of the video streams with their credentials (GetStreams). While the application doesn’t answer, the pages, the Dashboard and the login work; the requests of the application are answered with 503 {"error":"no connection to the application"}, the Dashboard shows “No connection to the application”, the parameters page waits for it. The log of the service has the first state, the loss and the return of the connection and the streams of pages.json which the application doesn’t have.

The service checks every command twice: the rights of the role (Pages: the commands of the elements and buttons of the groups of the parameters pages of the role and the commands of the buttons and the click of its video pages; the role viewer sends no commands; otherwise 403) and then the application checks the value (see ApplicationTemplate). The service writes every command with the user and the accepted value to its log.

Table 12 - HTTPS API of the service.

Request Answer
POST /api/auth/login Body {"user", "password", "realm"} (realm: “local” or absent; the LDAP users log in so too, through SSSD). Answer: the session (as below) and the cookie __Host-wcp; 401 - invalid user name or password (the same for every reason), 429 - too many failures, 503 - the PAM helper doesn’t answer.
POST /api/auth/logout End the session (CSRF token required).
GET /api/auth/session {"user", "role", "csrfToken", "idleTimeout", "absoluteTimeout"} (timeouts in seconds); 401 - no session.
GET /api/pages Pages and cards of the role (pages.json without the pages, buttons and click which the role can’t use).
GET /api/system/info Information for the Dashboard: hostname, model, os, kernel, timezone, versions (template, application), application (connected, version, streams: name, codec, resolution, fps, bitrate, viewers, state; videoOff - why there is no video: “disabled”, “strict-fips”, “no-encoder”, “failed”, empty while the video works), security (cryptoMode “fips” or “standard”, module, selfTest “passed”, “failed” or “not run”, see FIPS mode; videoServer, videoCrypto - cryptoMode, module and selfTest of the process of the video server, videoCoverage - the video server fully covered by the FIPS module (both only while it runs), externalProtocol, certificate; logins for admin only).
GET /api/system/metrics Metrics for the Dashboard: time, uptime, CPU (total and cores, %), load average, memory and swap, temperatures, disks, network interfaces, uptime of the application and the history of 5 minutes (one value per second: CPU, memory, received and sent bytes per second). The service takes a sample once per second (SystemInfo class).
GET /api/app/config Description of the groups of the parameters pages of the role; 503 - no connection to the application.
GET /api/app/params Values of the elements of these groups: {"WebParams": {"<Group>": {"<Name>": "<value>"}}}, the values are strings; 502 - the answer of the application is not valid, 503 - no connection to the application.
POST /api/app/command Body {"Command": "<Group>/<Name>", "Value": "<value>"} (the value is a string, without value for the buttons), Content-Type application/json. Answer {"status":"OK"} or {"status":"ERROR"}; 400 - invalid JSON, 403 - the role may not send the command, 413 - body larger than 4 KB, 415 - other Content-Type, 503 - no connection to the application.
POST /api/video/{stream}/whep WebRTC signalling (WHEP): body - SDP offer, Content-Type application/sdp, CSRF token required. Answer 201 with the SDP answer of the video server and Location: /api/video/{stream}/whep/{id}; 400 - the video server refused the offer (the reason in {"error"}, e.g. the stream has no video yet), 403 - no video page or video card of the role shows the stream (also a name of no stream), 404 - the application has no stream of the pages ({"error", "videoOff"} with the reason if the application has no video: the player shows it), 413 - offer larger than 32 KB, 415 - other Content-Type, 429 - too many video sessions, 502 - the video server doesn’t answer, 503 - no connection to the application (e.g. its new start).
DELETE /api/video/{stream}/whep/{id} Close a video session of the session (CSRF token required); 404 - the session has no such video session.
POST /api/admin/reset Factory reset (admin only, CSRF token required): body {"password"} - the password of the account of the session. Answer {"status":"OK"}: the certificate is replaced, the log files are removed, 1 s later all sessions end and the HTTPS server restarts with the new certificate. If the log files or the settings file can’t be removed, the answer is {"status":"ERROR", "error"} after the certificate was replaced (the restart and the end of the sessions follow). 400 - invalid body, 403 - not admin (forbidden) or wrong password (invalid password, counted as a failed login), 413 - body larger than 1 KB, 415 - other Content-Type than JSON, 429 - too many failures, 500 - the new certificate can’t be created (nothing is changed), 503 - the PAM helper doesn’t answer.
GET /api/admin/certificate Certificate of the HTTPS server (admin only): {"subject", "issuer", "notBefore", "notAfter", "names", "key", "fingerprint", "selfSigned", "chainLength"} (times UTC, names of the alternative names, key e.g. “EC P-256”, SHA-256 fingerprint). 403 - not admin, 500 - the certificate can’t be read.
POST /api/admin/certificate Certificate of admin (CSRF token required): body {"certificate", "privateKey", "password"} - the certificate chain and its key (PEM, at most 64 KB and 16 KB) and the password of the account of the session. Answer {"status":"OK", "certificate": {...as above}}: the files are installed and 1 s later the HTTPS server restarts with them, the sessions stay. 400 - invalid body or refused files (the reason in {"error"}, see Certificate below), 403 - not admin or wrong password (invalid password, counted as a failed login), 413 - body larger than 128 KB, 415 - other Content-Type than JSON, 429 - too many failures, 500 - the files can’t be written (nothing is changed), 503 - the PAM helper doesn’t answer.
GET /api/admin/settings Settings (admin only, see Settings below): {"settings": {"idleTimeout", "absoluteTimeout", "recheckPeriod", "adminGroup", "operatorGroup", "viewerGroup", "journal"}, "authMode": "pam" or "file", "journalOpen"} (times in seconds). 403 - not admin.
PUT /api/admin/settings Change of the settings (CSRF token required): body {"settings": {<changed fields>}, "password"} - the password of the account of the session. Answer {"status":"OK", "settings": {...}}: the settings file is written and the settings are used at once. 400 - invalid body or refused settings (the reason in {"error"}, e.g. “idleTimeout must be 60…86400 s”, “group x is not a group of the roles of the PAM helper (its argument –groups)”, “user admin would not be admin with these groups”), 403 - not admin or wrong password (invalid password, counted as a failed login), 413 - body larger than 4 KB, 415 - not JSON, 429 - too many failures, 500 - the file can’t be written (nothing is changed), 503 - the PAM helper doesn’t answer.
GET /api/admin/audit Security events of the service (admin only): the last 500 records of the system journal with the identifier webpanel, {"entries": [{"time", "priority", "source", "message", "event", "user", "address"}]} from old to new; {"journal": false, "entries": []} if the param journal is off (the events are only in the log file); 403 - not admin, 503 - journalctl can’t be run.
GET /api/system/journal Last 200 records of the system journal: {"entries": [{"time", "priority", "source", "message"}]}, only for the roles of a module page with this request in its field api (403 for other roles), 503 if journalctl can’t be run. The service reads the records which its user can read (members of the groups systemd-journal and adm read the whole journal).

Every request (also the files of the pages) can get 429 over the limit of the request rate of the client address (see Login).

The service also gives the files of the WEB pages (folder webServer.wwwFolder, GET requests of other paths than the API; WebFiles class): “/” is index.html, only the files html, css, js, json, svg, png and ico, the path consists of letters, digits, ‘-‘, ‘_’ and ‘.’ (no “..”, no hidden files, no directory listing), the real path of the file must be in the folder (a symbolic link can’t lead outside of it). A file has an entity tag of its content (ETag, FNV-1a 64): with Cache-Control: no-cache the browser checks its copy at each opening (If-None-Match) and gets 304 without the file if the copy is current, so a page opened again transfers only the changed files. The tag depends only on the content: the same file installed again (also with a fixed time of a reproducible build) keeps its tag, a changed file gets a new one. The pages are given with the headers Content-Security-Policy (default-src 'self', no frames), X-Content-Type-Options, Referrer-Policy, Cross-Origin-Opener-Policy, Cross-Origin-Resource-Policy and Permissions-Policy.

HTTPS only. An address http:// of the port of the service gets 301 to the same address with https://. The port webServer.httpRedirectPort (80 in the installed configuration) only answers with this redirect: http://<device> without a port (a browser goes to the port 80) leads to the panel; it has no pages and no API. A device is usually opened by its IP address, for which the browsers don’t use HSTS, so without this port such an address gives an error of the connection. Every answer of the pages and of the API, also the answers of the HTTPS server itself (400, 404, 405, 413, 431), has Strict-Transport-Security: max-age=31536000 (and X-Content-Type-Options: nosniff) (param webServer.hstsMaxAge, 0 - no header): the browser opens the host only over HTTPS (an address http://<name> becomes https://<name>) and doesn’t let the user go past an error of the certificate. The browsers use it only for a host name with a certificate without errors (a certificate of a CA or one which the computer trusts), not for an IP address and not while the self-signed certificate gives a warning. If a browser has seen the header and the device then gets a self-signed certificate (e.g. a factory reset), the browser doesn’t open the device by its name until the time ends: open it by its IP address or remove the host from the HSTS list of the browser (Chrome and Edge: chrome://net-internals/#hsts). Set a short time or 0 if the device can lose its certificate of a CA.

Certificate. If neither webServer.certificateFile nor webServer.privateKeyFile exists, the service creates them at start: ECDSA key P-256, self-signed certificate for 10 years (both files with the mode 0600), CN - the host name, alternative names - the host name, localhost and the IPv4 addresses of the computer. If only one of the files exists, the service doesn’t start. A certificate of a CA (e.g. of the company, so that the browsers trust the device and use HSTS) is uploaded by admin in the user menu, “Certificate…” (POST /api/admin/certificate): the dialog shows the current certificate (subject, issuer, validity, names, key, SHA-256 fingerprint) and takes the file of the chain, the file of the key and the password of the account again (as for a factory reset). The service checks them:

  • the chain is the certificate of the device first, then its intermediate certificates, each issued by the next one (at most 10);
  • the certificate is valid now, not of a CA, signed with SHA-256 or stronger; its key usage and extended key usage, if it has them, allow a TLS server (digitalSignature, serverAuth);
  • the key is not encrypted, is EC P-256, P-384, P-521 (not in the FIPS mode) or RSA of 2048…8192 bits and matches the certificate;
  • the HTTPS server loads the new files (written next to the old ones with the suffix “.new”, the key with the mode 0600) before they replace the old ones: a chain which its OpenSSL refuses (e.g. an intermediate certificate signed with SHA-1) never stops the server.

Then the HTTPS server restarts with the new certificate; the sessions stay and the page loads again. A refused file gets the reason (e.g. “the private key doesn’t match the certificate of the server”); every change and refusal is in the log and in the journal (certificate_changed, certificate_refused). Putting the files to the paths and restarting the service works too.

Settings. Admin changes some params of the configuration in the interface: the user menu, “Settings…” (GET / PUT /api/admin/settings). The dialog has the timeouts of the sessions and the period of the check of the accounts in minutes, the groups of the roles (mode pam; in the mode file the roles are in users.json and the fields are disabled) and the system journal on or off, and takes the password of the account again (as for a factory reset). Only the changed values are sent. The service checks them (the limits of Table 13; the names of the groups at most 64 bytes without control symbols, ‘,’ and ‘:’, different groups of the roles; in the mode pam each group must be a group of the PAM helper (its –groups) and the admin who changes them must stay admin, so the last admin can’t lock everybody out), writes them to settingsFile (mode 0600, a new file renamed over the old one) and uses them at once:

  • the timeouts: for all sessions, also the open ones (a shorter absolute timeout can end the session of the change);
  • the groups of the roles: at the next login and at a check of the accounts of the sessions right after the change: the sessions whose role has changed end;
  • the journal: the change is the last record before it is off and the first one after it is on; while it is off the events are only in the log file of the service and the tab “Security events” of the page “Logs” says that the journal is off.

The values of the configuration file are the values of the factory: at a start the service reads settingsFile over them and writes the changed ones to the log; an invalid settings file stops the service (remove it or make a factory reset). Every change is in the log and in the journal (settings_changed with the old and the new values, settings_refused, settings_failed).

Factory reset. It removes the data of the service: the certificate and its key, the settings of admin (settingsFile: the settings of the configuration file again), the log files of the service (WebPanel_*.txt of logFolder; the other files of the folder stay), the sessions with their video sessions and the login attempts. The accounts (the system users or users.json), the configuration files (configuration of the service, pages.json) and the application with its settings are not changed. The records of the system journal stay: the system keeps its journal (e.g. journalctl --vacuum-time=...); the reset is written to it. Two ways:

  • Interface: the user menu of admin, “Factory reset…”, and the password of the account again (an open session is not enough; a wrong password counts against the guessing as a failed login). The service writes a new self-signed certificate next to the old files and renames it over them (if it can’t be created, nothing is changed), removes its log files and writes the reset to the new log, answers, and 1 s later ends all sessions and restarts its HTTPS server with the new certificate. The page waits for the restart and opens the login page with the message “Factory reset done”; the browser warns about the new certificate once.
  • Command line, for the stopped service (e.g. a reset of the device): webpanel --factory-reset -c <config file> removes the certificate, its key, the settings file and the log files and writes the removed files; the service creates a new certificate at its next start. The running service locks its log folder (flock): the command doesn’t reset a running service, and a second service with the same log folder doesn’t start.

The service reads the configuration file of the argument -c (webpanel.json of the working folder by default). If the file doesn’t exist, the service creates it with the default params; if it exists and is not valid, the service doesn’t start (the file is not replaced). A param which the file doesn’t have keeps its default value, so a file of an older version stays valid: the log lists these params and the unknown params of the file (e.g. a misspelled name), which are not used. Arguments: webpanel [-v] [-c <config file>] [--factory-reset]; a build with the test accounts (-DWEB_CONTROL_PANEL_TEST_ACCOUNTS=ON) has also --hash-password.

Table 13 - Params of the configuration of the service (webpanel.json).

Param Default Description
webServer.address 127.0.0.1 IPv4 address to listen to: 127.0.0.1 - this computer only, 0.0.0.0 - all network interfaces.
webServer.port 9000 TCP port of the HTTPS server. The installed configuration has 443; without the installation the service runs without root, so the port is above 1024.
webServer.certificateFile webpanel.crt Certificate chain file (PEM), created if there is none.
webServer.privateKeyFile webpanel.key Private key file (PEM), created if there is none.
webServer.wwwFolder www Folder of the WEB pages. Empty: the pages built into the service (option WEB_CONTROL_PANEL_EMBED_WWW, see Build); a service built without them gives no pages (API only).
webServer.pagesFile pages.json Pages of the interface. If the file is not valid, the service doesn’t start and writes the reason to the log.
webServer.requestsPerSecond 30 Limit of the request rate of a client address, requests per second (0…10000), 0 - no limit. Over the limit the answer is 429. Behind a NAT or a proxy the users share an address: raise the limit for many users.
webServer.requestBurst 120 Requests which an address may send at once above the rate (1…100000).
webServer.hstsMaxAge 31536000 Time of Strict-Transport-Security, seconds (0…63072000): the browser opens the host only over HTTPS for this time (1 year by default). 0 - no header. See HTTPS only above.
webServer.httpRedirectPort 0 Port without TLS which answers every request with a redirect to https:// of the same host and target (0…65535, not port), 0 - none. The installed configuration has 80. If it can’t be opened (used by another program, no right to a port below 1024) the service works without it and writes a warning to the log. See HTTPS only above.
auth.mode pam Accounts: pam - system users by the PAM helper, file - the test accounts of usersFile, only in a build with -DWEB_CONTROL_PANEL_TEST_ACCOUNTS=ON (see Login); otherwise the service doesn’t start.
auth.usersFile users.json Test accounts of the mode file (a build for the checks). If the file is not valid, the service doesn’t start and writes the reason to the log.
auth.pamSocket /run/webpanel-auth.sock Socket of the PAM helper (mode pam).
auth.adminGroup, auth.operatorGroup, auth.viewerGroup webpanel-admin, webpanel-operator, webpanel-viewer Linux groups of the roles (mode pam), empty - no group of the role. The argument –groups of the helper (webpanel-auth@.service) must have them. A setting (see Settings above).
auth.recheckPeriod 300 Period of the repeated check of the accounts of the sessions, seconds (60…3600, mode pam). A setting.
auth.idleTimeout 900 Idle timeout of a session, seconds (60…86400). A setting.
auth.absoluteTimeout 28800 Absolute timeout of a session after the login, seconds (idleTimeout…604800). A setting.
auth.maxFailures 5 Failed logins in auth.blockTime which block the client address or the user name for auth.blockTime (3…100).
auth.blockTime 300 Time of the counting of the failed logins and of the block, seconds (60…86400).
applicationSocket ApplicationTemplate.sock UNIX socket of the application (its param control.socketPath).
logFolder Log Folder of the log files (WebPanel_*.txt). One service works with a folder: it locks the folder while it runs.
journal true Write the security events also to the system journal (journald, identifier webpanel); false - the log files only. A setting.
settingsFile settings.json File of the settings which admin changes in the interface (see Settings above): its values replace the values of this file which are marked “A setting”. The installed configuration has /var/lib/webpanel/settings.json (the service may write only there). A factory reset removes it.
cryptoMode auto Mode of the cryptography: auto - FIPS if the OS is in the FIPS mode (/proc/sys/crypto/fips_enabled is 1), else standard; fips - always FIPS; standard - always standard (refused on an OS in the FIPS mode). See FIPS mode.
fips.moduleFolder (empty) Folder of fips.so. Empty: the folder of the modules compiled into OpenSSL.
fips.configFile (empty) openssl.cnf which includes fipsmodule.cnf by an absolute path and activates the providers fips and base. Empty: the openssl.cnf compiled into OpenSSL (e.g. the FIPS configuration of RHEL 9).
fips.moduleVersion (empty) Version of the FIPS module which the service accepts, e.g. 3.1.2 (a CMVP certificate is given to a version). Empty: any version.

The mode file (a build for the checks) has test accounts: keep the default address 127.0.0.1.

Installation

cmake --install installs the service (prefix /usr). It is a stand alone build of the template (see Build); a project which includes the template, e.g. the RapidPixel SDK, installs the service only with the option -DWEB_CONTROL_PANEL_INSTALL=ON:

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr
cmake --build build -j$(nproc)
sudo cmake --install build
Path Content
/usr/lib/webpanel/webpanel Service.
/usr/lib/webpanel/webpanel-auth PAM helper (if libpam0g-dev is installed).
/usr/share/webpanel/www WEB pages (not with the pages built into the service).
/etc/webpanel/config.json Configuration (config/config.json.in): port 443 on all interfaces, port 80 for the redirect to HTTPS, the paths below, socket of the application /run/ApplicationTemplate/control.sock.
/etc/webpanel/pages.json Pages of the interface.
/usr/lib/systemd/system/webpanel.service Unit of the service.
/usr/lib/systemd/system/webpanel-auth.socket, webpanel-auth@.service Socket and unit of the PAM helper.
/etc/pam.d/webpanel PAM configuration of the helper.
/usr/lib/sysusers.d/webpanel.conf The user webpanel of the service and the groups of the roles (systemd/webpanel.sysusers, systemd-sysusers).
/usr/lib/tmpfiles.d/webpanel.conf The mode 0640 and the group webpanel of /etc/webpanel/config.json and pages.json (systemd/webpanel.tmpfiles.in, systemd-tmpfiles, also at each boot).
/var/lib/webpanel Certificate and key (created by the service at the first start), the settings of admin (settings.json).
/var/log/webpanel Log.
/usr/share/doc/webpanel/sbom.cdx.json SBOM (CycloneDX) of the build, if cmake --build build --target sbom was run before.

No accounts and passwords are installed: the users of the interface are the system users of the groups of the roles. Create the user of the service and the groups and give the configuration to the service (a package of the device runs these two commands after the installation), add the users to the groups and start the socket of the helper and the service:

sudo systemd-sysusers webpanel.conf
sudo systemd-tmpfiles --create webpanel.conf
sudo usermod -aG webpanel-admin <user>
sudo systemctl daemon-reload
sudo systemctl enable --now webpanel-auth.socket webpanel

Factory reset of the installed service from the command line (see Service webpanel):

sudo systemctl stop webpanel
sudo /usr/lib/webpanel/webpanel --factory-reset -c /etc/webpanel/config.json
sudo systemctl start webpanel

Removal of the installed service: the units, the files of cmake --install (the list install_manifest.txt of the build folder), the folders with the certificate, the key and the log, the user and the groups (the records of the system journal stay):

sudo systemctl disable --now webpanel webpanel-auth.socket
sudo xargs -a build/install_manifest.txt rm -f
sudo rm -rf /usr/lib/webpanel /usr/share/webpanel /etc/webpanel /var/lib/webpanel /var/log/webpanel
sudo systemctl daemon-reload
sudo userdel webpanel
sudo groupdel webpanel-admin && sudo groupdel webpanel-operator && sudo groupdel webpanel-viewer

The unit (systemd/webpanel.service.in) runs the service as the user webpanel without root: the ports 443 and 80 (the redirect) are given by the only capability CAP_NET_BIND_SERVICE; NoNewPrivileges, ProtectSystem=strict (writable only /var/lib/webpanel and /var/log/webpanel), ProtectHome, PrivateTmp, PrivateDevices, RestrictAddressFamilies (UNIX, IPv4, IPv6, netlink for the addresses of the interfaces), SystemCallFilter=@system-service, restart on failure. The user reads the system journal as a member of the group systemd-journal. The unit of the helper (systemd/webpanel-auth@.service.in) runs it as root, because PAM reads /etc/shadow, but without capabilities except CAP_AUDIT_WRITE (audit records of PAM), with NoNewPrivileges, ProtectSystem=strict (writable only /run/faillock), ProtectHome=read-only, PrivateTmp, PrivateDevices, SystemCallFilter=@system-service and at most 30 s.

PAM checks the passwords outside the FIPS module: for a FIPS device the image of the OS uses the hashes of its FIPS mode (usually SHA-512-crypt instead of yescrypt). /etc/pam.d/webpanel includes the stacks of Debian and Ubuntu (@include common-auth); on a system with other stacks include them instead (e.g. system-auth). The helper runs as root without capabilities to override the file permissions (CapabilityBoundingSet of webpanel-auth@.service): where /etc/shadow has the mode 0000 (e.g. RHEL, Fedora) add CAP_DAC_READ_SEARCH to it.

The application is not installed by the template: it is the program of the device. It must listen to the socket of /etc/webpanel/config.json and allow the user webpanel, for example with the params "control": {"socketPath": "/run/ApplicationTemplate/control.sock", "socketGroup": "webpanel", "allowedUsers": ["webpanel"]} and a unit with RuntimeDirectory=ApplicationTemplate and SupplementaryGroups=webpanel (the group of the socket file is set by the application, so it must be a member of the group).

FIPS mode

The service does its cryptography with the OpenSSL FIPS provider through CryptoProvider. The param cryptoMode chooses the mode at start: auto (default) - FIPS if the OS is in the FIPS mode (/proc/sys/crypto/fips_enabled is 1), fips - always, standard - never. In the FIPS mode the service:

  • loads the module of the params fips (not of the environment variables OPENSSL_CONF and OPENSSL_MODULES, so a user can’t replace it), requires the settings of openssl fipsinstall -pedantic in fipsmodule.cnf (security-checks, tls1-prf-ems-check, drbg-no-trunc-md) and the version of fips.moduleVersion, checks that only the providers fips and base are active and runs the self tests of the module. If something fails, the service doesn’t start: the log and the system journal (crypto_failed) have the reason (FipsError), e.g. Can't init the cryptography FIPS 140-3 (cryptoMode fips): FipsError::ModuleVersionMismatch, OpenSSL FIPS provider is not the required version (fips.moduleVersion 3.0.9). A changed fips.so fails its integrity check (ModuleLoadFailed);
  • makes every OpenSSL object in the library context of CryptoProvider: the TLS contexts of the HTTPS server and of the client of the video server, the random bytes of the session tokens, SHA-256, PBKDF2 of users.json, the key and the certificate of the first start, the uploaded certificates;
  • gives TLS 1.3 and TLS 1.2 (only with Extended Master Secret: the module refuses a TLS 1.2 handshake without it), AES-128/256-GCM only, the key exchange with the groups P-256 and P-384 only (X25519, X448 and the other groups are refused); the certificate of the server has an ECDSA key P-256 or P-384 or RSA of 2048 to 8192 bits (P-521 is refused at the upload; at the start the service checks the files of the certificate and doesn’t start in the FIPS mode with another key, a key which doesn’t match or a signature weaker than SHA-256, e.g. after an upload in the standard mode or files put by hand: install other files or make a factory reset, crypto_failed in the journal);
  • shows the mode, the module with its version and the result of the self test in /api/system/info and on the Dashboard (card Security and the badge “FIPS” in the top bar).

In the standard mode the same objects are made in a library context of CryptoProvider with the default provider. Outside the module: the passwords of the system users (PAM, see Installation), TLS to an LDAP server (SSSD, see Login), the command --hash-password (it doesn’t read the configuration) and the application with its video server (MServer has its own mode, video.securityProfile).

Video and FIPS. WebRTC carries the video only by SRTP, and the SRTP key derivation (SP 800-135 5.3) is not in the validated module (CMVP #4985). The modes of the video server (video.securityProfile of the application):

  • CRA_STRICT (default) - WebRTC, no FIPS claim for the video;
  • FIPS_ONVIF_BRIDGE - WebRTC with SRTP AES_CM_128_HMAC_SHA1_80 and the module of the params fips of the application (checked by api/fips with --fips): every primitive is approved, but the SRTP keys are derived outside the module, so the conformance is limited (the card Security shows “Video in the FIPS module: not fully”). The mode for a FIPS device with video in the browser;
  • STRICT_FIPS - everything in the module: the application doesn’t start its video server, the browser has no video (the video page and the cards say why). HLS through the service for this mode is not made: it is done if a device needs video with the full coverage.

The service in the FIPS mode works with every mode: its client of the video server uses the groups P-256 and P-384, which MServer accepts.

A FIPS module which is not of the OS: build OpenSSL with enable-fips (e.g. the validated version 3.1.2), install the module with openssl fipsinstall -pedantic -module <folder>/fips.so -out <folder>/fipsmodule.cnf and write an openssl.cnf for the service:

config_diagnostics = 1
openssl_conf = openssl_init
.include /opt/openssl-fips/ssl/fipsmodule.cnf

[openssl_init]
providers = provider_sect

[provider_sect]
fips = fips_sect
base = base_sect

[base_sect]
activate = 1

and the params "cryptoMode": "fips", "fips": {"moduleFolder": "/opt/openssl-fips/lib/ossl-modules", "configFile": "/opt/openssl-fips/ssl/openssl.cnf", "moduleVersion": "3.1.2"}. The libraries libssl and libcrypto of the system (3.0 or newer) load the module. The system checks run the service in this mode with run_checks.py --fips /opt/openssl-fips/ssl/openssl.cnf --fips-modules /opt/openssl-fips/lib/ossl-modules --fips-version 3.1.2 (see Checks of the code).

Table for the laboratory. The template gives the facts of the service for the security policy of a device; the integrator makes the file of the certification (the validated module, the OS, the entropy source, the device).

  • Boundary of the module. The cryptographic module is the OpenSSL FIPS Provider (fips.so with its fipsmodule.cnf, e.g. version 3.1.2, CMVP certificate #4985). The service and the libraries libssl and libcrypto of the OS are outside the boundary: they run the protocols (TLS, X.509, PEM, HTTP digest) and call the module for every cryptographic primitive. The service uses the module only through the library context of CryptoProvider, which has the providers fips and base (base: encoders and decoders of keys and certificates, no cryptography). The DRBG of the module is seeded by the OS (getrandom): the entropy source is outside the module and is documented for the device (SP 800-90B).
  • Approved mode. cryptoMode “fips”, the module of the params fips with the settings of fipsinstall -pedantic and the required version, the self tests passed at start (otherwise the service doesn’t start). The indicator: /api/system/info (security.cryptoMode “fips”, security.module with the version, security.selfTest “passed”), the badge “FIPS” and the log line Cryptography FIPS 140-3 ....
  • Self tests. The module checks its integrity (HMAC-SHA2-256 of fips.so with the value of fipsmodule.cnf) and runs its known answer tests when it is loaded; the service runs runFipsSelfTest() once more before it starts. A generated key pair gets the pairwise consistency test of the module.

Table 14 - Cryptographic functions of the service in the FIPS mode.

Function Algorithm and parameters Code
TLS server: HTTPS of the interface, the probe of an uploaded certificate TLS 1.3 (TLS_AES_256_GCM_SHA384, TLS_AES_128_GCM_SHA256, TLS 1.3 KDF) and TLS 1.2 only with Extended Master Secret (ECDHE-ECDSA- and ECDHE-RSA-AES256/128-GCM-SHA384/256, TLS 1.2 PRF); key agreement ECDH P-256, P-384 (KAS-ECC-SSC); authentication of the server ECDSA P-256 or P-384 with SHA-256/384, or RSA 2048…8192; AES-GCM with the nonce of the TLS protocol WebServer (WebServerTls)
TLS client: WHEP to the video server of the application (127.0.0.1) the same versions, cipher suites and groups; the certificate of the server is pinned (compared with the certificate of GetStreams, no chain); HTTP digest authentication with SHA-256 (RFC 7616), client nonce 128 bits HttpsClient, VideoProxy
Random numbers DRBG of the module (CTR_DRBG with AES-256, SP 800-90A): session tokens and CSRF tokens 256 bits, salts 128 bits, ids of the video sessions 128 bits, client nonces 128 bits, serial numbers of certificates 127 bits, the dummy password for unknown users CryptoContext (randomBytes), Certificate
Hash SHA-256: the sessions are kept by the SHA-256 of their tokens (the token itself is not stored), the fingerprints of certificates, HTTP digest, the subject key identifier (leftmost 160 bits, RFC 7093) Sessions, Certificate, HttpsClient
Password hash of users.json (mode file, a prototype) PBKDF2 with HMAC-SHA-256 (SP 800-132): salt 128 bits, 100000 iterations (at least 10000 are accepted), key 256 bits; the comparison takes constant time Users
Key generation EC P-256 key pair of the self-signed certificate (first start, factory reset) Certificate
Signature ECDSA P-256 with SHA-256 of the self-signed X.509 certificate Certificate
Checks of an uploaded certificate and key the key EC P-256, P-384 or RSA 2048…8192, the key matches the certificate (comparison of the public keys), the signature algorithm of the certificate of at least 128 bits of security (read, not verified: the browsers verify the chain); the TLS server loads them before they replace the old files Certificate
Zeroization overwritten (OPENSSL_cleanse) after the use, with every copy: the passwords of the logins, of the confirmations and of the video stream, the text of an uploaded private key, the tokens of the sessions and the CSRF tokens, the random bytes of the tokens and of the password of the stream. The secret values of the JSON bodies don’t go through the JSON parser, which frees its copies without wiping (JsonSecrets); WebServer wipes the heads and the bodies of the requests, the responses and the buffers of the connections (also when a buffer grows); the answer of GetStreams is written and read without the JSON values of the passwords; the PAM helper wipes the request and the password. The keys inside the module are freed with their objects Secrets, WebServer, Sessions, ServiceApi, AuthClient, AppBridge, HttpsClient, Certificate; webpanel-auth; ApplicationTemplate (Video)

Non-approved cryptographic functions of the service in the FIPS mode: none. Functions which are not cryptographic: the entity tags of the files of the pages (FNV-1a 64), the comparison of the CSRF tokens in constant time. In the standard mode the service uses the same functions with the provider default of OpenSSL and the TLS groups of OpenSSL (also X25519, X448, ffdhe), P-521 keys are accepted; the standard mode makes no FIPS claim.

Outside the module:

  • the passwords of the system users: the PAM helper and PAM (libxcrypt, e.g. yescrypt or SHA-512-crypt) - a requirement to the image of the OS (see Installation);
  • TLS to an LDAP server: SSSD of the OS (on Debian and Ubuntu GnuTLS outside any FIPS module; on an OS in the FIPS mode, e.g. RHEL 9, its module), see Login;
  • webpanel --hash-password: PBKDF2-HMAC-SHA-256 in the default context of OpenSSL (an offline command, it doesn’t read the configuration);
  • the application and its video server MServer: another process with its own mode (video.securityProfile, see Video and FIPS above): WebRTC derives its SRTP keys outside the module (fullModuleCoverage false), STRICT_FIPS has no video in the browser;
  • the entropy source of the OS and the TLS of the browsers.

The system check api/fips checks the boundary: it runs the service in the FIPS mode with only the provider null in the default context of OpenSSL (OPENSSL_CONF), so any operation outside the context of CryptoProvider fails; the certificate of the first start, the login, an uploaded certificate, a change of the settings, the WHEP proxy and a factory reset work.

ApplicationTemplate

The ApplicationTemplate folder contains the application with the parameters of the WEB interface and the video, as the application of WebControlPanelTemplate of the RapidPixel SDK. It keeps the values of the parameters in memory; the video is a test source (see Video). The UDP control of WebControlPanelTemplate is not included: the remote control without the interface is the External Protocol, off by default.

The application has no HTTPS server: its API for the service is HTTP on a UNIX socket (Control.cpp, WebServer::runUnix(...)). Only the user of the application and the users of control.allowedUsers connect (the kernel gives the user of the client); the socket file has the mode 0660. The service checks the rights of the roles before it sends a command; the application checks the value.

Table 15 - API of the application on the UNIX socket.

Request Answer
GET /GetInfo State for the Dashboard: {"version", "instance", "uptime", "videoServer", "streams", "videoOff", "videoCoverage", "videoCrypto", "externalProtocol"} (videoCrypto while the video server runs: cryptoMode fips or standard, module, selfTest passed, failed or not run; externalProtocol: enabled, failed - on in the configuration but a port can’t be opened, bindAddress, udpPort, tcpPort); instance is random at every start (the service reads the description and the streams again when it changes), streams - name, codec, resolution, fps, bitrate, viewers, state; videoOff - why there is no video (“disabled”, “strict-fips”, “no-encoder”, “failed”; empty while the video works); videoCoverage - fullModuleCoverage of MServer (only while the video server runs). The service takes the last two as optional (an application of an older version).
GET /GetConfig Description of the parameters (WebTableContent.cpp).
GET /GetParameters Values of all elements: {"WebParams": {"<Group>": {"<Name>": "<value>"}}}.
POST /Command Body {"Command": "<Group>/<Name>", "Value": "<value>"}. Answer {"status": "OK", "value": "<accepted value>"} or {"status": "ERROR"}; 400 - invalid JSON, 413 - body larger than 4 KB.
GET /GetStreams WHEP endpoints of the video streams: [{"name", "port", "certificate", "user", "password"}] (certificate - PEM text which the service pins; the credentials are random at every start).

The description of the parameters is in WebTableContent.cpp (one group for each of the 8 elements and the group Video with the results of the commands of the video page; the field id of a group selects it for a page). At start the application reads the description (WebParameters class) and accepts a command only with a valid value: a value only for an element with access READ_WRITE and only within the limits of the element (TEXT_FIELD - text up to 256 bytes without control characters, DROPDOWN - one of the values of enumValues, SWITCH - “On” or “Off”, INPUT_NUMBER and SLIDER - decimal number from min to max, INT - integer); a command without value only for a button; the commands of the video page are the commands of the application (Lens/ZoomTele, Lens/ZoomWide, Lens/ZoomStop, VideoTracker/Reset, VideoTracker/CapturePercents with the value <x>x<y> of numbers 0…100). Otherwise the answer is {"status":"ERROR"}.

The read only values are set by the application (main.cpp): uptime, tracker mode (TRACKING while the PUSH/RELEASE button is pressed), state of the editable switch, editable slider in percents, signal which rises from 0 to 100 and falls back in 10 seconds, version, number of accepted commands, zoom state and the point of the last click on the video. The button RESET sets the default values of the editable parameters.

On the first run the application creates the configuration file ApplicationConfig.json with the default params:

Table 16 - Params of ApplicationConfig.json.

Param Default Description
control.socketPath ApplicationTemplate.sock UNIX socket of the API for the service (its param applicationSocket), shorter than 108 bytes.
control.socketGroup (empty) Group of the socket file: the group of the service. Empty: the group of the application.
control.allowedUsers [“webpanel”] Users who may connect besides the user of the application. A user which doesn’t exist is skipped (written to the log).
video.enable true Video: FALSE - no video.
video.stream Cam Name of the stream: the field stream of the video pages and the video card of pages.json.
video.width, video.height 1280, 720 Size of the frames, pixels (even, 16…4096).
video.fps 30 Frames per second (1…60).
video.bitrateKbps 3000 Bitrate, kbps (100…100000).
video.gop 30 Period of the key frames, frames (1…300).
video.h264Profile 0 H264 profile: 0 - constrained baseline, 1 - main, 2 - high.
video.encoder auto H264 encoder: auto - the first which works of VA-API and V4L2, vaapi - VCodecLibva, v4l2 - VCodecV4L2.
video.webRtcPort 7000 TCP port of the WHEP signalling of the video server. The service sends the offers to it at 127.0.0.1; close it for other computers in the firewall.
video.webRtcMediaPort 7001 UDP port of the media: the browsers connect to it, open it in the firewall.
video.publicAddress (empty) IPv4 address of the ICE candidate: the address of the device which the browsers reach. Empty: the address of the default route (set it on a device with several interfaces).
video.bindAddress 0.0.0.0 Local IPv4 address of the sockets of the video server: 0.0.0.0 - all interfaces.
video.securityProfile CRA_STRICT Mode of the video server: CRA_STRICT, FIPS_ONVIF_BRIDGE (needs the FIPS module; WebRTC with a limited FIPS conformance) or STRICT_FIPS (no video in the browser: the video server is not started, WebRTC is not possible). See Video and FIPS in FIPS mode.
video.certificateFile, video.privateKeyFile ApplicationTemplate.crt, ApplicationTemplate.key Certificate and key of the WHEP signalling. If neither exists, the application creates a self-signed certificate for localhost and 127.0.0.1; the service pins it.
fips.moduleFolder, fips.configFile, fips.moduleVersion (empty) FIPS module of the video server in FIPS_ONVIF_BRIDGE, as the params fips of the service: the folder of fips.so, openssl.cnf with fipsmodule.cnf and the required version (empty: the paths compiled into OpenSSL, any version). The application loads the module from them (not from OPENSSL_CONF and OPENSSL_MODULES) and runs its self test before the certificate and the video server; if it can’t, there is no video (videoOff failed, the reason in the log) and the application works.
externalProtocol.enable false External Protocol: TRUE - the application listens to its ports. No authentication and no encryption.
externalProtocol.bindAddress 127.0.0.1 IPv4 address of the interface of the ports, e.g. the address of the network of the control computers; 0.0.0.0 - all interfaces.
externalProtocol.udpPort 52000 UDP port (1024…65535), 0 - no UDP.
externalProtocol.tcpPort 52000 TCP port (1024…65535), 0 - no TCP (not both 0).

A param which the configuration file doesn’t have (a file of an older version) keeps its default value and the file is not changed; the log lists these params and the unknown params of the file. If there is no file, the application creates it with the default params. A file which can’t be read, is not JSON or has a value which is not valid stops the application with the reason in the log (e.g. Invalid config file ApplicationConfig.json: video.fps: 1...60), and the file is not changed: the params of the user, e.g. the FIPS mode of the video, are never replaced by the defaults; correct the file or remove it.

External Protocol

The External Protocol is the remote control of the application without the WEB interface, e.g. by a control program of the system: the format of the External control protocol of the application of version 2 of the template by UDP and by TCP and the elements and the commands of the WEB page (WebTableContent.cpp and the commands of the pages), so everything which the WEB page sets can be set by it. Its commands go to the same handler as the commands of the service (executeCommand(...), Control.cpp): the same checks of the names and the values, and the WEB page shows the new values. The protocol is in WebControlPanel/src/ExternalProtocol.h (parsing and answers), the ports in ApplicationTemplate/ExternalProtocol.cpp.

Warning: the protocol has no authentication and no encryption: anybody who reaches the ports changes the parameters of the device. It is off by default (externalProtocol.enable); turn it on only in a trusted network (e.g. the network of the control computers), on the address of that interface (externalProtocol.bindAddress, 127.0.0.1 by default), and close the ports for the other networks in the firewall. The card Security of the Dashboard shows it (“UDP 52000, TCP 52000 on 10.0.0.5, no authentication”). A protected remote control (authentication, TLS/DTLS) is a later stage. Unlike the old protocol, it gives no credentials of the video streams: only the elements of the WEB page.

A message is one UDP datagram of 10…2048 bytes which starts with [; other datagrams are ignored (no answer). It has exactly four parts separated by /, without empty parts and without a line feed at the end (a line feed is a part of the value or of the name: the message gets NAC). The value is the text after the first :: it can contain : but not /. The answers end with a line feed and go from the port to the address and the port of the datagram.

By TCP (externalProtocol.tcpPort) the messages are the same, each ends with a line feed (\n or \r\n, not a part of the message): several messages can come in one packet and a message in several packets, the answers come in the order of the messages. A line which doesn’t start with [ or is shorter than 10 bytes is ignored, a line longer than 2048 bytes closes the connection. At most 8 connections at once (another one is closed at once), a connection without messages for 5 minutes is closed.

Message Answer
[<id>]/Command/<Group>/<Name>:<value> Set an editable element (TEXT_FIELD, DROPDOWN - the value of an item, SWITCH - On or Off, INPUT_NUMBER, SLIDER): [<id>]/ACK, or [<id>]/NAC if the element is read only, unknown or the value is not valid.
[<id>]/Command/<Group>/<Name> A command without a value: COMMAND_BUTTON, the push and the release commands of PUSH_RELEASE_BUTTON, a command of a page (e.g. Lens/ZoomTele): [<id>]/ACK or [<id>]/NAC.
[<id>]/Query/<Group>/<Name> [<id>]/Reply/<Group>/<Name>:<value> - the value of an element (also read only), or [<id>]/NAC.

The id is 1…32 symbols in brackets (e.g. a number); a message without a valid id gets [0]/NAC. Example (UDP: nc -u 127.0.0.1 52000, each message without a line feed; TCP: nc 127.0.0.1 52000, each message a line):

[1]/Command/TextField/ReadWrite:hello  ->  [1]/ACK
[2]/Query/TextField/ReadWrite          ->  [2]/Reply/TextField/ReadWrite:hello
[3]/Command/Slider/ReadOnly:5          ->  [3]/NAC
[4]/Command/CommandButton/Reset        ->  [4]/ACK

Every executed command is written to the log of the application and to the system journal with the identifier ApplicationTemplate (WEBPANEL_EVENT=external_command, WEBPANEL_ADDRESS - the address and the port of the client: journalctl -t ApplicationTemplate); the refused messages too (external_refused, at most one record per second with their number).

Video

The video of the application goes from the application to the browser by WebRTC:

application:  test source (NV12) ──► VCodecLibva / VCodecV4L2 (H264) ──► MServer ──UDP, DTLS-SRTP──► browser
                                                                       ▲
browser ──HTTPS──► webpanel: /api/video/Cam/whep ──► VideoProxy ──HTTPS 127.0.0.1, digest──┘
  • Source. A thread of the application draws the frames with the FPS of the params: color bars, a moving square, a bar of the second at the bottom and a cross at the point of the last click on the video (Video/CapturePoint). Replace it with the frames of a camera in a real application.
  • Encoder. H264 is encoded by the hardware: VCodecLibva (VA-API) or VCodecV4L2 (V4L2), param video.encoder. With “auto” the application tries the encoders of the build (VA-API first) and takes the first which encodes a frame of color bars; the log has “Video encoder: …”. If no encoder works (none built, no VA-API device or driver, no V4L2 encoder device or no rights to it) the application writes “No video” to the log and works without video; the video page and the video card show “The stream is not available”. VCodecV4L2 writes “Not supported parameter” for the params which MServer sets and V4L2 doesn’t have (e.g. the bitrate mode): this is not an error of the video. After a failed frame the encoder is replaced by a new one (RecoveringEncoder, the log has “Video encoder failed (N in all): a new encoder for the next frames”): an error can leave the driver unusable, e.g. the VA-API driver d3d12 of WSL2 sometimes throws an exception and keeps the lock of its display, and the next call of the old encoder never returns. The new encoder gets the params set before and starts with a key frame; the old one is destroyed in a thread of its own. New encoders are created at most once per second and while less than 3 old ones are still being destroyed (“Video encoder doesn’t recover” otherwise).
  • Video server. MServer serves the stream by WebRTC only (no RTSP, no HLS) in the mode video.securityProfile (in STRICT_FIPS it is not started). The WHEP signalling uses the certificate video.certificateFile of the application. The credentials of the stream are random at every start: only the video server and the service (GetStreams of the UNIX socket) know them, the browser never gets them. A stream without viewers is not encoded.
  • Signalling. The browser sends the SDP offer to the service (POST /api/video/<stream>/whep with the session and the CSRF token), the proxy (VideoProxy) sends it to the video server at 127.0.0.1 (HttpsClient: TLS with the pinned certificate of GetStreams, digest authentication SHA-256) and returns the answer. A video session belongs to the session of the user: logout and the timeouts of the session close it. A session of a user has at most 4 video sessions, the service at most 32. After a new start of the application the service takes its new streams and forgets the old video sessions; the players connect again.
  • Player. js/video/whep.js: RTCPeerConnection recvonly, the offer after the gathering of the candidates (no trickle ICE), H264 (H265 where the browser decodes it), a new connection with a growing pause (1…30 s) after a loss, also when no frame is decoded within 5 s of the media connection or no new frame for 2 s while it plays (a stopped video server or a decoder which shows nothing more is noticed before the browser finds the connection lost; the decoded frames are counted by getStats, the received bytes where the browser doesn’t count them or the page is hidden); the pause is reset by the first decoded frame and is the shortest while the service answers 503, so the video is back within seconds after a new start of the application, statistics once per second (getStats), snapshot, DELETE of the video session when the page is left or closed.
  • Network. The video server is ICE-lite with one host candidate: no STUN and TURN servers, no NAT between the browser and the device, IPv4 only. The browser connects to UDP video.webRtcMediaPort of the address of the candidate (video.publicAddress or the address of the default route). A device with several interfaces needs video.publicAddress: e.g. a Raspberry Pi with Ethernet and Wi-Fi whose default route is the Wi-Fi, opened by the browsers at its Ethernet address, gives the Wi-Fi address without it, and the video doesn’t connect. The WHEP port listens on video.bindAddress too (MServer has one address for all sockets): close TCP video.webRtcPort for other computers in the firewall, for example with nftables:
sudo nft add rule inet filter input tcp dport 7000 iif != lo drop

Table of contents