Configure server through web onboarding and encrypt backups

This commit is contained in:
Ludwig Lehnert committed 2026-10-05 16:47:49 +00:00
1 parent 5cb3b5bedf
commit 88f803daf2
35 files changed
+4250 -981

No files matched your search

+5 -67
View File
@@ -1,67 +1,5 @@
REALM=EXAMPLE.COM # Deprecated: new installations use no .env file.
WORKGROUP=EXAMPLE # Run ./setup, open http://<server>/ for HTTPS configuration,
DOMAIN=example.com # then continue over HTTPS for AD setup. Manage settings at /admin/settings
JOIN_USER=FileShare_ServiceAcc # and backup destinations, schedules and encryption at /admin/backup.
JOIN_PASSWORD=ReplaceWithLongRandomPassword # Existing .env files are imported once by ./setup and are never evaluated.
DOMAIN_USERS_SID=S-1-5-21-1111111111-2222222222-3333333333-513
DOMAIN_ADMINS_SID=S-1-5-21-1111111111-2222222222-3333333333-512
FSLOGIX_GROUP_SID=S-1-5-21-1111111111-2222222222-3333333333-513
# AD_DNS_IP=192.0.2.10
# AD_DNS_NAME=adsambafsrv.example.com
# AD_DNS_IP_AUTO=1
# SAMBA_HOSTNAME=adsambafsrv
# NETBIOS_NAME=ADSAMBAFSRV
WEB_ENABLED=true
WEB_HOSTNAME=files.example.com
WEB_HTTPS_PORT=443
WEB_JWT_SECRET=ReplaceWithAtLeast32RandomBytes
WEB_TLS_MODE=acme
ACME_CA_SERVER=https://ca.internal/acme/acme/directory
ACME_CA_CERTIFICATES=/state/tls/acme-ca-certificates.pem
# Optional one-time HTTPS download when ACME_CA_CERTIFICATES does not exist:
# ACME_CA_CERTIFICATES_URL=https://ca.internal/roots.pem
# ACME_CA_CERTIFICATES_INSECURE_DOWNLOAD=true
ACME_HTTP_LISTEN=:80
ACME_HTTP_PORT=80
# ACME_RENEW_CHECK_SECONDS=900
# WEB_TLS_CERT_FILE=/state/tls/web.crt
# WEB_TLS_KEY_FILE=/state/tls/web.key
# WEB_JWT_TTL_SECONDS=28800
# WEB_AUTH_RECHECK_SECONDS=60
# WEB_TRUSTED_ORIGINS=https://files.example.com
# WEB_TLS_HANDSHAKE_TIMEOUT_SECONDS=5
# WEB_REQUEST_TIMEOUT_SECONDS=30
# WEB_MAX_CONNECTIONS=64
# WEB_USAGE_SCAN_INTERVAL_SECONDS=900
# WEB_DIRECTORY_CACHE_SECONDS=300
# WEB_LOGIN_ATTEMPTS_PER_5_MIN=10
# WEB_LOGIN_ACCOUNT_ATTEMPTS_PER_5_MIN=10
# DOCUMENT_SCAN_SECONDS=30
# DOCUMENT_OCR_LANGUAGE=deu+eng
# DOCUMENT_OCR_TIMEOUT_SECONDS=600
# DOCUMENT_OCR_DPI=300
# DOCUMENT_OCR_MAX_DIMENSION=3500
# DOCUMENT_OCR_PAGE_TIMEOUT_SECONDS=30
# DOCUMENT_MAX_FILE_MB=512
# DOCUMENT_MAX_PDF_PAGES=500
# TRASH_RETENTION_DAYS=7
# LDAP_URI=ldaps://example.com
# LDAP_BASE_DN=DC=example,DC=com
# PRIVATE_SKIP_USERS=svc_backup,svc_sql
# PRIVATE_SKIP_PREFIXES=svc_,sql_
# BACKUP_DESTINATION=rsync://user:pass@backup.example.com/samba-backups
# BACKUP_DESTINATION=smb://DOMAIN%5Cuser:pass@backup.example.com/Backups/samba
# BACKUP_DESTINATION=davfs://user:pass@webdav.example.com/remote.php/dav/files/backup
# BACKUP_DESTINATION=sftp://user:pass@sftp.example.com/exports/samba
# BACKUP_START_HOUR=2 # 0-23, UTC
# BACKUP_RETENTION_DAILY=3
# BACKUP_RETENTION_WEEKLY=2
# BACKUP_RETENTION_MONTHLY=2
# BACKUP_RETENTION_YEARLY=1
# BACKUP_LOG_FILE=/var/log/backup.log
# BACKUP_PROGRESS=auto
# BACKUP_PROGRESS_INTERVAL_SECONDS=10
# BACKUP_STATUS_FILE=/state/backup-status.json
# STATE_DB_PATH=/state/shares.db
# AUDIT_QUERY_MAX_DAYS=31
# AUDIT_SKIP_USER_SUFFIXES=_svc,_ServiceAcc
+5 -1
View File
@@ -46,6 +46,10 @@ COPY app/audit_collector.py /app/audit_collector.py
COPY app/trash.py /app/trash.py COPY app/trash.py /app/trash.py
COPY app/web_ui.py /app/web_ui.py COPY app/web_ui.py /app/web_ui.py
COPY app/web_security.py /app/web_security.py COPY app/web_security.py /app/web_security.py
COPY app/configuration.py app/backup_keys.py app/tls_configuration.py app/entrypoint.py app/run_service.py app/healthcheck.py /app/
COPY app/http_setup.py /app/http_setup.py
COPY app/restore_backup.py /app/restore_backup.py
COPY app/vendor /app/vendor
COPY app/document_types.py /app/document_types.py COPY app/document_types.py /app/document_types.py
COPY app/documents.py /app/documents.py COPY app/documents.py /app/documents.py
COPY app/document_search.py /app/document_search.py COPY app/document_search.py /app/document_search.py
@@ -60,4 +64,4 @@ RUN chmod +x /app/init.sh /app/reconcile_shares.py /app/backup_to_destination.py
&& true && true
ENTRYPOINT ["/usr/bin/tini", "--"] ENTRYPOINT ["/usr/bin/tini", "--"]
CMD ["/app/init.sh"] CMD ["python3", "/app/entrypoint.py"]
+42 -193
View File
@@ -29,14 +29,14 @@ This repository provides a production-oriented Samba file server container that
- The administration console at `/admin/...` manages Data folders and individual user access, and provides statistics, logs, trash downloads/restores, manual backups, and share reconciliation. It also includes a fully client-side Typst PDF report. - The administration console at `/admin/...` manages Data folders and individual user access, and provides statistics, logs, trash downloads/restores, manual backups, and share reconciliation. It also includes a fully client-side Typst PDF report.
- Web sign-in validates the submitted username/password with Kerberos and issues an expiring JWT in a Secure, HttpOnly, SameSite=Strict cookie. Human AD users can sign in; `MSOL_*` and `krbtgt` accounts are excluded. Administration pages and APIs require membership in `DOMAIN_ADMINS_SID`. The browser does not use NTLM/SPNEGO or Kerberos negotiation. - Web sign-in validates the submitted username/password with Kerberos and issues an expiring JWT in a Secure, HttpOnly, SameSite=Strict cookie. Human AD users can sign in; `MSOL_*` and `krbtgt` accounts are excluded. Administration pages and APIs require membership in `DOMAIN_ADMINS_SID`. The browser does not use NTLM/SPNEGO or Kerberos negotiation.
- HTTPS certificates are requested from a configured local Smallstep CA and renewed automatically. Pre-issued certificate files are also supported. - HTTPS certificates are requested from a configured local Smallstep CA and renewed automatically. Pre-issued certificate files are also supported.
- Optional remote backups run when `BACKUP_DESTINATION` and `BACKUP_ARCHIVE_PASSWORD` are configured; each active or archived group folder is uploaded as its own encrypted, non-solid 7z archive. - Optional remote backups are configured in the admin UI, including destination, scheduling and full-data encryption.
- Private home creation skips well-known/service accounts by default (including `krbtgt`, `msol_*`, `FileShare_ServiceAcc`). - Private home creation skips well-known/service accounts by default (including `krbtgt`, `msol_*`, `FileShare_ServiceAcc`).
- Reconciliation is executed: - Reconciliation is executed:
- once on startup - once on startup
- every 5 minutes via cron - every 5 minutes via cron
- Backup is executed: - Backup is executed:
- manually through the Domain Admin web UI or CLI - manually through the Domain Admin web UI or CLI
- daily at `BACKUP_START_HOUR` in UTC when `BACKUP_AUTO_ENABLED=true` (default: `true`; the switch is environment-only) - daily at the configured UTC hour when automatic backups are enabled in the UI
## Data Folder Lifecycle ## Data Folder Lifecycle
@@ -71,7 +71,7 @@ The Data share uses Samba Windows ACL checks instead of POSIX ACLs. Keep its dat
## File Search and PDF Recognition ## File Search and PDF Recognition
Users sign in at `/` with their existing AD credentials using `username`, `DOMAIN\username`, or `username@domain`. Domain-qualified names accept the configured AD DNS domain/realm; the short NetBIOS domain is also accepted after `@`. The file view provides live search by filename and content, folder and file-type filters, grid/list views, previews, and downloads of the original files. Grid and list entries show file metadata without extracted content snippets. Only Domain Admins see the administration link and can use management pages and APIs under `/admin/...`; old administration URLs redirect there. Administrative APIs are under `/admin/api/...`, while sign-in, session, and document endpoints remain under `/api/...`. This upgrade expires existing web sessions. Users sign in at `/` with their existing AD credentials using `username`, `DOMAIN\username`, or `username@domain`. Domain-qualified names accept the configured AD DNS domain/realm; the short NetBIOS domain is accepted only with the `DOMAIN\username` spelling. The file view provides live search by filename and content, folder and file-type filters, grid/list views, previews, and downloads of the original files. Grid and list entries show file metadata without extracted content snippets. Only Domain Admins see the administration link and can use management pages and APIs under `/admin/...`; old administration URLs redirect there. Administrative APIs are under `/admin/api/...`, while sign-in, session, and document endpoints remain under `/api/...`. This upgrade expires existing web sessions.
The catalog includes active Data folders and each user's own Private folder. Every search, detail, preview, and download request checks current individual folder permissions. Revoking access or archiving a folder takes effect without waiting for reindexing. Domain Admins can see all active Data folders, but the user file view still shows only their own Private folder. Archived folders, recycle repositories, FSLogix profiles, symlinks, nested mounts, and special files are excluded. `Thumbs.db` (case-insensitive) and Office lock files whose names start with `~$` are omitted from results, counts and file-type filters in both Data and Private folders. Upgrades remove their existing catalog entries without deleting original files. Private files additionally require ownership and read/traverse permissions for the signed-in user's mapped Unix identity. The catalog includes active Data folders and each user's own Private folder. Every search, detail, preview, and download request checks current individual folder permissions. Revoking access or archiving a folder takes effect without waiting for reindexing. Domain Admins can see all active Data folders, but the user file view still shows only their own Private folder. Archived folders, recycle repositories, FSLogix profiles, symlinks, nested mounts, and special files are excluded. `Thumbs.db` (case-insensitive) and Office lock files whose names start with `~$` are omitted from results, counts and file-type filters in both Data and Private folders. Upgrades remove their existing catalog entries without deleting original files. Private files additionally require ownership and read/traverse permissions for the signed-in user's mapped Unix identity.
@@ -102,7 +102,7 @@ Domain Admins monitor the worker at `/admin/documents`: current file and phase,
| `DOCUMENT_MAX_FILE_MB` | `512` | Largest file copied for extraction; larger files use filename search | | `DOCUMENT_MAX_FILE_MB` | `512` | Largest file copied for extraction; larger files use filename search |
| `DOCUMENT_MAX_PDF_PAGES` | `500` | Maximum PDF page count for extraction | | `DOCUMENT_MAX_PDF_PAGES` | `500` | Maximum PDF page count for extraction |
These settings are passed through the existing Compose environment file. Setting `WEB_ENABLED=false` also disables the document worker. These settings are configured under Dokumentindex und OCR at `/admin/settings`. Their internal names below also identify imported legacy settings.
## Shared SQLite State Database ## Shared SQLite State Database
@@ -127,7 +127,7 @@ Standard SQLite does not provide transparent general-purpose compression, so thi
## AD Requirements ## AD Requirements
- Existing AD DS domain reachable from the Docker host. - Existing AD DS domain reachable from the Docker host.
- Initial admin credentials with rights to create/reset `FileShare_ServiceAccount` during `./setup`. - An AD account with permission to join the server to the domain and read directory users/groups.
- `FileShare_ServiceAccount` must be allowed to join computers to the domain (`net ads join`) in your AD policy. - `FileShare_ServiceAccount` must be allowed to join computers to the domain (`net ads join`) in your AD policy.
- Directory reads use machine-account LDAP (`net ads search -P`); join credentials are only used as a fallback LDAP bind path. - Directory reads use machine-account LDAP (`net ads search -P`); join credentials are only used as a fallback LDAP bind path.
- Existing AD users are selectable by the administrator; no AD group naming convention is required for new Data folders. - Existing AD users are selectable by the administrator; no AD group naming convention is required for new Data folders.
@@ -140,7 +140,7 @@ Standard SQLite does not provide transparent general-purpose compression, so thi
- Preferred setup: Docker host uses AD-integrated DNS or forwards to AD DNS. - Preferred setup: Docker host uses AD-integrated DNS or forwards to AD DNS.
- If Docker bridge networking is used, set `AD_DNS_IP` to the Docker host LAN IP that clients should use for SMB, not the container `172.x` address. - If Docker bridge networking is used, set `AD_DNS_IP` to the Docker host LAN IP that clients should use for SMB, not the container `172.x` address.
- When `AD_DNS_IP` is set, domain join uses `--no-dns-updates`; each container startup unregisters/re-registers `AD_DNS_NAME -> AD_DNS_IP` in AD DNS using the machine account. - When `AD_DNS_IP` is set, domain join uses `--no-dns-updates`; each container startup unregisters/re-registers `AD_DNS_NAME -> AD_DNS_IP` in AD DNS using the machine account.
- `./setup` and `./redeploy` auto-refresh `AD_DNS_IP` from the host route when `AD_DNS_IP_AUTO=1`. - Configure the host LAN address used for AD DNS registration in the web setup or server settings.
## Time Sync Requirements ## Time Sync Requirements
@@ -202,6 +202,16 @@ Password: PreviewAdmin123!
The generated CA is intentionally disposable. `scripts/dev` prints the temporary root certificate path so it can be trusted only for the duration of that run. Ctrl-C stops and removes all run-scoped containers, volumes, the network, and the temporary root. A watchdog performs the same cleanup if the parent script is killed. The generated CA is intentionally disposable. `scripts/dev` prints the temporary root certificate path so it can be trusted only for the duration of that run. Ctrl-C stops and removes all run-scoped containers, volumes, the network, and the temporary root. A watchdog performs the same cleanup if the parent script is killed.
To test first-launch onboarding with empty configuration and data, run:
```bash
./scripts/dev --onboarding
```
Open `http://files.localhost:8080/`. This mode starts the same disposable AD, CA, and rsync target, but supplies no application configuration through environment variables and skips file seeding, automatic domain join, the SMB activity client, and the backup driver. Only the external HTTPS port mapping is recorded for correct setup links and browser origin checks.
The launcher prints both setup codes, the ACME directory, the root certificate file to upload, domain credentials, group names, and the optional backup destination. Configure HTTPS first, temporarily trust the disposable CA root, then follow the link to `https://files.localhost:8443/` to complete domain setup. Configure backups afterwards in `/admin/settings`. Each launch starts fresh; Ctrl-C removes that run's configuration and test data. `--onboarding` and `--e2e` are mutually exclusive.
Neither the dummy DC nor the application container receives extra capabilities. Neither the dummy DC nor the application container receives extra capabilities.
Useful overrides: Useful overrides:
@@ -209,6 +219,7 @@ Useful overrides:
| Variable | Default | Purpose | | Variable | Default | Purpose |
| --- | --- | --- | | --- | --- | --- |
| `DEV_HTTPS_PORT` | `8443` | HTTPS port bound to host loopback | | `DEV_HTTPS_PORT` | `8443` | HTTPS port bound to host loopback |
| `DEV_HTTP_PORT` | `8080` | HTTP setup port bound to host loopback in `--onboarding` mode |
| `DEV_WEB_HOSTNAME` | `files.localhost` | HTTPS name validated by the disposable ACME CA | | `DEV_WEB_HOSTNAME` | `files.localhost` | HTTPS name validated by the disposable ACME CA |
| `DEV_SKIP_BUILD` | `0` | Set to `1` to reuse already-built local images | | `DEV_SKIP_BUILD` | `0` | Set to `1` to reuse already-built local images |
| `DEV_CA_IMAGE` | `docker.io/smallstep/step-ca:latest` | CA image; pin a tag or digest for reproducible CI | | `DEV_CA_IMAGE` | `docker.io/smallstep/step-ca:latest` | CA image; pin a tag or digest for reproducible CI |
@@ -271,62 +282,17 @@ node tests/access_ui_smoke.mjs
## Setup ## Setup
1. Run interactive setup: No environment file is required. Run `./setup` to build and start the service, then open `http://<server>/`. HTTP exposes only HTTPS configuration: enter the separate HTTPS setup code from `docker compose logs samba`, choose the HTTPS hostname and ACME directory URL, and optionally upload a PEM root CA certificate. Public CAs use the system trust bundle. The ACME CA must resolve the hostname and reach its HTTP-01 challenge on port 80.
```bash Once issuance succeeds, follow the HTTPS link. Enter the second, independent setup code from the container log. This code is used only over HTTPS. Configure the AD realm, NetBIOS domain, controller, domain-join/LDAP credentials and server names. After the domain join succeeds, select the AD groups for login, administration and FSLogix, and verify an account in the selected administrator group. Folder permissions remain individual assignments.
./setup
```
2. If `.env` is missing, you will be prompted for: The web UI remains available if joining AD fails. Correct the settings and retry without removing any data volumes. The setup capability stops working after completion. Domain-join credentials are retained for LDAP; use an account with the necessary directory read and join permissions, or replace its credentials in administration after joining.
- `REALM`
- `WORKGROUP`
- `DOMAIN`
- `AD_DNS_IP` (host LAN IP to publish in AD DNS)
- optional `AD_DNS_NAME` (defaults to `SAMBA_HOSTNAME.DOMAIN`)
- initial admin credentials (used once for provisioning)
- `DOMAIN_USERS_SID`
- `DOMAIN_ADMINS_SID`
- optional `FSLOGIX_GROUP_SID` (defaults to `DOMAIN_USERS_SID`)
- optional `BACKUP_DESTINATION` (empty disables backup)
- `BACKUP_ARCHIVE_PASSWORD` when a backup destination is configured
- optional environment-only `BACKUP_AUTO_ENABLED` (`true` or `false`, default `true`)
- optional `BACKUP_START_HOUR` (0-23, default `2`; used only when automatic backups are enabled)
- optional `BACKUP_RETENTION_DAILY` (default `3`)
- optional `BACKUP_RETENTION_WEEKLY` (default `2`)
- optional `BACKUP_RETENTION_MONTHLY` (default `2`)
- optional `BACKUP_RETENTION_YEARLY` (default `1`)
- optional `BACKUP_LOG_FILE` (default `/var/log/backup.log`)
- optional `BACKUP_PROGRESS` (`auto`, `always`, or `never`; default `auto`)
- optional `BACKUP_PROGRESS_INTERVAL_SECONDS` (default `10`)
- `WEB_HOSTNAME` (the DNS name in the HTTPS certificate)
- optional `WEB_HTTPS_PORT` (host port, default `443`)
- `ACME_CA_SERVER` (ACME directory URL)
- either an ACME CA root bundle on the host or an `ACME_CA_CERTIFICATES_URL` for one-time retrieval
- optional `ACME_HTTP_PORT` (HTTP-01 host port, default `80`)
Setup generates a random `WEB_JWT_SECRET` and either imports the selected public CA root or configures its one-time download to `/state/tls/acme-ca-certificates.pem`. Administrators manage server settings at `/admin/settings` and backup destinations, schedules, retention and encryption at `/admin/backup`. Settings are stored in the root-only `/state/configuration.db`. Backup changes apply to the next run. Other changes restart the service processes, preserving files and the existing domain join; active SMB connections may reconnect. Switching to a different AD domain is deliberately rejected after setup.
Optional: For an existing installation, run `./setup` or `./redeploy`: the previous container’s resolved configuration is imported once when available; otherwise, its `.env` is imported without executing it. The original domain join, storage paths, access database, volumes, backup password, destinations and backup history are preserved. A configured installation ignores later `.env` edits. An unconfigured installation can also import its old file from the HTTPS setup screen. Keep the same Compose project name and volume names during the upgrade. Never use `docker compose down -v` on retained data.
- `SAMBA_HOSTNAME` (defaults to `adsambafsrv`)
- `NETBIOS_NAME` (defaults to `ADSAMBAFSRV`, max 15 chars)
3. Setup behavior: Compose publishes fixed ports 80 and 443, plus SMB 139 and 445. A deployment requiring different host ports can use a Compose override; it does not configure application credentials or backup destinations. TLS, AD settings and backup configuration are managed in the browser.
- creates or updates AD service account from desired name `FileShare_ServiceAccount`
- uses a valid AD `sAMAccountName` (max 20 chars); default effective value is `FileShare_ServiceAcc`
- always sets a long random password
- writes only service-account credentials to `.env` (initial admin credentials are not stored)
- writes `AD_DNS_IP` so container restarts keep AD DNS pointed at the host LAN IP
4. The setup script then starts the service with:
```bash
docker compose up -d
```
5. After startup:
- container joins AD (idempotent)
- startup reconciliation runs
- cron runs reconciliation every 5 minutes
## SMB Shares ## SMB Shares
@@ -393,7 +359,7 @@ The console is intentionally operational and plain:
The PDF report deliberately excludes the activity log and backup log. Its dedicated snapshot endpoint removes those fields before returning data. Typst, its WebAssembly compiler, and the report fonts are shipped with the application; Typst source and PDF bytes are created only in the authenticated browser and are never uploaded to another service. The first export downloads roughly 22 MiB of compiler/font assets, which are then cached as immutable files. The CSP grants only `'wasm-unsafe-eval'` for WebAssembly compilation and does not enable JavaScript `'unsafe-eval'`. The PDF report deliberately excludes the activity log and backup log. Its dedicated snapshot endpoint removes those fields before returning data. Typst, its WebAssembly compiler, and the report fonts are shipped with the application; Typst source and PDF bytes are created only in the authenticated browser and are never uploaded to another service. The first export downloads roughly 22 MiB of compiler/font assets, which are then cached as immutable files. The CSP grants only `'wasm-unsafe-eval'` for WebAssembly compilation and does not enable JavaScript `'unsafe-eval'`.
The mutation endpoints under `/admin/api/` manage Data access, restore retained files, control indexing, or start an immediate backup/share reconciliation. They require an active Domain Admin session and CSRF protection. Restore cannot overwrite a live file. Backup schedules, retention, and `BACKUP_AUTO_ENABLED` are configured through the environment. Automatic backups can be enabled or disabled only through the environment and therefore require a redeployment/restart. The mutation endpoints under `/admin/api/` manage Data access, restore retained files, control indexing, or start an immediate backup/share reconciliation. They require an active Domain Admin session and CSRF protection. Restore cannot overwrite a live file. Backup schedules, destinations, retention and encryption are configured through `/admin/backup`, without redeploying.
### Authentication and sessions ### Authentication and sessions
@@ -406,88 +372,13 @@ The mutation endpoints under `/admin/api/` manage Data access, restore retained
- TLS handshakes run in bounded connection workers, outside the accept loop, with a five-second timeout. Request I/O also has a timeout. - TLS handshakes run in bounded connection workers, outside the accept loop, with a five-second timeout. Request I/O also has a timeout.
- Responses set HSTS, a restrictive Content Security Policy, clickjacking protection, and MIME sniffing protection. APIs and ordinary UI assets use no-store caching; pinned Typst compiler/font assets use immutable long-term caching. - Responses set HSTS, a restrictive Content Security Policy, clickjacking protection, and MIME sniffing protection. APIs and ordinary UI assets use no-store caching; pinned Typst compiler/font assets use immutable long-term caching.
### TLS with an internal ACME CA ### HTTPS and certificate management
The default uses standard ACME HTTP-01 enrollment. The names deliberately describe the protocol and inputs rather than a particular CA product: The HTTP onboarding step accepts only an ACME directory URL without credentials, a hostname and an optional PEM root CA upload. Its setup code cannot access the HTTPS configuration API. HTTP rejects login, AD settings, backup settings and every administrative action. After onboarding, ordinary HTTP requests redirect to HTTPS; the ACME challenge route remains available for renewals. Challenges are forwarded to a loopback-only responder.
```env In `/admin/settings`, choose ACME, Smallstep CA, uploaded certificate/key PEM, or a self-signed certificate. ACME and CA credentials, custom trust roots, renewal intervals and uploaded private keys are entered over HTTPS. A temporary self-signed certificate keeps HTTPS setup reachable before managed issuance succeeds. Uploaded certificate/key pairs are validated before replacing working files. Certificate changes reload the HTTPS listener.
WEB_ENABLED=true
WEB_HOSTNAME=files.example.com
WEB_HTTPS_PORT=443
WEB_JWT_SECRET=<at-least-32-random-bytes>
WEB_TLS_MODE=acme
ACME_CA_SERVER=https://ca.internal/acme/acme/directory
ACME_CA_CERTIFICATES=/state/tls/acme-ca-certificates.pem
ACME_CA_CERTIFICATES_URL=https://ca.internal/roots.pem
ACME_CA_CERTIFICATES_INSECURE_DOWNLOAD=true
ACME_HTTP_LISTEN=:80
ACME_HTTP_PORT=80
```
`ACME_CA_CERTIFICATES` is the persistent destination inside the file-server container. If that path does not exist and `ACME_CA_CERTIFICATES_URL` is set, the service downloads at most 4 MiB over HTTPS, validates that the result contains readable certificate data, and atomically installs it. Once the destination exists, it is never downloaded or overwritten again—not even when it is empty or invalid. Removing the file is therefore an explicit operator action that permits a new bootstrap download. The client uses [`step ca certificate --acme --root --standalone`](https://smallstep.com/docs/step-cli/reference/ca/certificate/). Automatic ACME renewal checks default to every 900 seconds. If using a private CA, also install its root in clients' trust stores. Certificate provisioning errors leave the web setup available for correction.
HTTPS verification is enabled by default. `ACME_CA_CERTIFICATES_INSECURE_DOWNLOAD=true` explicitly enables a one-time trust-on-first-use bootstrap equivalent to `curl -k`; it is useful when the server certificate is signed by the very root being fetched. This protects subsequent starts but cannot protect the first download from a man-in-the-middle attack, so compare the downloaded root fingerprint through an independent channel when possible. Instead of downloading, setup can import a local PEM bundle into the same destination.
The CA must be able to resolve `WEB_HOSTNAME` and reach `http://WEB_HOSTNAME/.well-known/acme-challenge/...` on port 80. `ACME_HTTP_LISTEN` controls the in-container standalone challenge listener and `ACME_HTTP_PORT` controls the Compose host-port mapping.
The equivalent Traefik settings translate as follows:
| Traefik setting | File-server setting |
| --- | --- |
| `acme.httpchallenge=true` | `WEB_TLS_MODE=acme` |
| `acme.httpchallenge.entrypoint=http` | `ACME_HTTP_LISTEN=:80` and `ACME_HTTP_PORT=80` |
| `acme.caserver=https://ca.internal/acme/acme/directory` | `ACME_CA_SERVER=https://ca.internal/acme/acme/directory` |
| `acme.cacertificates=/traefik/stepca/roots.pem` | `ACME_CA_CERTIFICATES=<persistent PEM destination inside this container>` |
| one-time equivalent of `curl https://ca.internal/roots.pem -k` | `ACME_CA_CERTIFICATES_URL=https://ca.internal/roots.pem` and `ACME_CA_CERTIFICATES_INSECURE_DOWNLOAD=true` |
The client uses [`step ca certificate --acme --root --standalone`](https://smallstep.com/docs/step-cli/reference/ca/certificate/) and periodically checks whether the certificate needs renewal. Renewal is a fresh ACME order, so this mode is not coupled to a proprietary renewal endpoint. The HTTPS listener reloads the replaced certificate files.
A generic direct-CA/JWK or token enrollment mode remains available when ACME HTTP-01 cannot be routed:
```env
WEB_TLS_MODE=ca
TLS_CA_URL=https://ca.internal:9000
TLS_CA_FINGERPRINT=<root-certificate-fingerprint>
TLS_CA_PROVISIONER=fileserver
TLS_CA_PROVISIONER_PASSWORD=<provisioner-password>
# TLS_CA_PROVISIONER_PASSWORD_FILE=/run/secrets/ca-provisioner-password
# TLS_CA_TOKEN=<single-use-bootstrap-token>
# TLS_CA_REBOOTSTRAP=false
# TLS_CA_STATE_DIR=/state/tls-client
```
Externally managed certificate files can be used instead:
```env
WEB_TLS_MODE=files
WEB_TLS_CERT_FILE=/state/tls/web.crt
WEB_TLS_KEY_FILE=/state/tls/web.key
```
Useful optional settings:
| Variable | Default | Purpose |
| --- | ---: | --- |
| `ACME_CA_CERTIFICATES_URL` | unset | HTTPS URL used only when the persistent root bundle does not exist |
| `ACME_CA_CERTIFICATES_INSECURE_DOWNLOAD` | `false` | Disable TLS verification only for that initial root download |
| `WEB_TLS_AUTORENEW` | `true` | Renew managed certificates automatically |
| `ACME_RENEW_CHECK_SECONDS` | `900` | Interval for ACME renewal checks; minimum 60 seconds |
| `WEB_JWT_TTL_SECONDS` | `28800` | Session lifetime, 5 minutes to 7 days |
| `WEB_AUTH_RECHECK_SECONDS` | `60` | Session identity/role recheck interval via winbind, 5 to 300 seconds |
| `WEB_TRUSTED_ORIGINS` | derived | Comma-separated exact HTTPS origins; default uses `WEB_HOSTNAME` and `WEB_HTTPS_PORT` |
| `WEB_LOGIN_ATTEMPTS_PER_5_MIN` | `10` | Per-address login attempt limit, including successful attempts |
| `WEB_LOGIN_ACCOUNT_ATTEMPTS_PER_5_MIN` | `10` | Per-target-account login attempt limit across client addresses |
| `WEB_TLS_HANDSHAKE_TIMEOUT_SECONDS` | `5` | TLS handshake deadline, 1 to 30 seconds |
| `WEB_REQUEST_TIMEOUT_SECONDS` | `30` | Request I/O timeout, 1 to 300 seconds |
| `WEB_MAX_CONNECTIONS` | `64` | Concurrent connection workers, 4 to 512; excess connections are closed |
| `WEB_USAGE_SCAN_INTERVAL_SECONDS` | `900` | Recursive storage scan interval |
| `WEB_DIRECTORY_CACHE_SECONDS` | `300` | AD membership tree cache time |
| `TRASH_RETENTION_DAYS` | `7` | Recycled-file lifetime; cleanup accepts 1 to 365 days |
| `STATE_DB_PATH` | `/state/shares.db` | Shared SQLite database for shares, activity, collector offsets, and caches |
| `AUDIT_QUERY_MAX_DAYS` | `31` | Largest activity query window |
| `AUDIT_SKIP_USER_SUFFIXES` | `_svc,_ServiceAcc` | Case-insensitive account suffixes excluded from collection and queries; set empty to disable |
If `WEB_ENABLED` is absent on an upgraded installation and no TLS settings/certificate exist, the web service stays disabled while Samba and audit collection continue. Set `WEB_ENABLED=true` after adding TLS configuration.
## Activity Database ## Activity Database
@@ -510,61 +401,19 @@ Collection starts even when the web UI is disabled. Existing databases remain qu
## Backups ## Backups
- Backups are available only if `BACKUP_DESTINATION` is non-empty and `BACKUP_ARCHIVE_PASSWORD` is set. Configure backups entirely in `/admin/backup`: destination, automatic daily start hour (UTC), retention counts and optional encryption. Supported targets are rsync, SFTP, SMB and WebDAV; for example `sftp://backupuser:password@backup.example.com/exports/samba`. URL-encode reserved characters in credentials. Stored destination passwords are never returned to the browser; the UI shows only the protocol, server and path. Removing the destination disables future backups without deleting remote history.
- Each run creates a timestamped snapshot under `snapshots/YYYYMMDDTHHMMSSZ` at the destination.
- `BACKUP_AUTO_ENABLED=true` schedules the job daily at `BACKUP_START_HOUR` in UTC. With `false`, no backup cron entry is installed; manual web and CLI runs remain available. This setting is environment-only and cannot be changed through the web API.
- The container and Compose service force `TZ=Etc/UTC`.
- Sources synced to destination on each run:
- `/data/private` -> `data/private`
- `/data/groups` -> `data/groups`; direct group directories below `data` and `archive` become one `<group>.7z` each
- `/data/fslogix` -> `data/fslogix`
- `/state` -> `state` (the live WAL database is replaced by a consistent SQLite online snapshot)
- `/var/lib/samba/private` -> `samba/private`
- Retention policy env vars (defaults):
- `BACKUP_RETENTION_YEARLY=1`
- `BACKUP_RETENTION_MONTHLY=2`
- `BACKUP_RETENTION_WEEKLY=2`
- `BACKUP_RETENTION_DAILY=3`
- The backup script writes directly to `BACKUP_LOG_FILE` (default: `/var/log/backup.log`). Cron does not redirect backup output into the logfile.
- Before uploading, the backup script creates a temporary, integrity-checked SQLite online snapshot of the shared state database.
- Each direct active and archived group folder is then compressed with LZMA2 at level 5 and multithreading into one non-solid (`-ms=off`) 7z archive. Header/data encryption is enabled (`-mhe=on`); the password comes only from `BACKUP_ARCHIVE_PASSWORD` and is supplied to 7z through stdin, never as a process argument. Non-group entries below `/data/groups` are preserved unchanged.
- `BACKUP_ARCHIVE_TEMP_DIR` selects the local staging directory (default `/tmp`). It must have enough free space for the compressed group archives. Staging data is removed after success or failure.
- Losing `BACKUP_ARCHIVE_PASSWORD` makes the group archives unrecoverable; keep it in the same secret-management system as the remote-backup credentials.
- After staging, the script measures all upload sources so it can report total transfer progress.
- Upload progress is logged per file every `BACKUP_PROGRESS_INTERVAL_SECONDS` seconds and again when a file reaches 100%, including percentage and transferred/remaining bytes with auto-scaled units.
- `BACKUP_PROGRESS=auto` shows an interactive multi-line progress view only for TTY/manual runs. Current file uploads are shown as separate rows, capped at 12 rows, with the total progress row at the bottom. Use `always` to force it or `never` to suppress the bar. File and total progress are still logged.
- Every run atomically updates `BACKUP_STATUS_FILE` (default `/state/backup-status.json`) with its state, current source, active files, byte totals, percentage, snapshot, and final result for the live web view.
- Active status is reconciled against the kernel-held `/state/backup.lock`; if a container restart or forced termination releases the lock while status still says `starting` or `running`, the web API atomically records the run as interrupted instead of reporting a phantom backup.
- Rclone-backed destinations cap concurrent file transfers at 12. Rsync remains single-streamed by rsync itself.
- Retention logic:
- daily: newest N snapshots
- weekly: newest N snapshots created on week start (Monday)
- monthly: newest N snapshots created on day 1
- yearly: newest N snapshots created on Jan 1
- snapshots selected by any tier are retained; all others are pruned
- Supported destination schemes:
- `rsync://user:pass@host/module/path`
- `smb://user:pass@host/share/path` (domain user example: `smb://DOMAIN%5Cuser:pass@host/share/path`)
- `davfs://user:pass@host/path` (WebDAV over HTTPS)
- `sftp://user:pass@host/path`
- Username/password components should be URL-encoded when they contain reserved characters (`@`, `:`, `/`, `\`, `%`, `#`, `?`).
- Example: Backups include Private files, active and archived Data folders, FSLogix, persistent server configuration/access records and Samba private state. Both SQLite databases use integrity-checked online snapshots. The rebuildable document index and previews, and retained trash, are omitted. Originals remain unchanged. The UI provides manual start, progress, current transfers and logs. Configuration and key changes are blocked while a backup is running.
```env When encryption is enabled, all sources—including credentials and server state—are staged as AES-256 7z archives with encrypted filenames/headers. Only encrypted archives and public format/key identifiers are uploaded. Generate a 24-word recovery phrase and confirm you recorded it before activating the key. It is displayed once, never persisted as a phrase, and expires after 15 minutes if not confirmed. The server retains the derived key so unattended backups work; protect the state volume and the Docker host accordingly. Encrypted staging requires space for a complete compressed backup.
BACKUP_DESTINATION=sftp://backupuser:StrongPassword@sftp.example.com/exports/samba
BACKUP_ARCHIVE_PASSWORD=use-a-long-random-secret Key renewal creates a separate `keys/<key-id>/snapshots/` generation. Existing backups stay in their previous location and require their previous phrase or legacy password. Retention affects only the active generation; older key generations are never pruned by a new key. Losing an old phrase or password makes that generation unrecoverable. Disabling encryption after using a generated key writes a separate `plain/` generation, keeping encrypted history separate. Existing installations retain their previous backup format/password until encryption is deliberately enabled or renewed.
BACKUP_AUTO_ENABLED=true
BACKUP_START_HOUR=2 Retention defaults are 3 daily, 2 weekly, 2 monthly and 1 yearly snapshots. Each tier selects its newest eligible snapshots; the union is kept. Snapshot names are UTC timestamps, and an incomplete upload is not marked complete. A interrupted job is detected from the backup lock rather than shown as running indefinitely.
BACKUP_ARCHIVE_TEMP_DIR=/tmp
BACKUP_RETENTION_DAILY=3 To recover a generated-key archive offline, use `python3 app/restore_backup.py ARCHIVE.7z NEW_RECOVERY_DIRECTORY` with Python and 7z installed. The tool prompts for the phrase without echoing it, derives the key and extracts only into a new directory. Inspect the files before copying anything into live volumes. It refuses to overwrite an existing recovery directory. Legacy archives still use their original archive password.
BACKUP_RETENTION_WEEKLY=2
BACKUP_RETENTION_MONTHLY=2 The versioned key format is `adfs-backup-archive-v1`: standard BIP39 English phrase/checksum and seed derivation (empty BIP39 passphrase), then PBKDF2-HMAC-SHA512 with that seed as the password, ASCII salt `adfs-backup-archive-v1`, one iteration, 32-byte output, lowercase hexadecimal. This becomes the archive password used by 7z's own AES-256 key derivation. The key identifier is the first 24 hexadecimal characters of SHA-256 of that ASCII password. The wordlist and license are bundled, so offline recovery does not depend on a network service.
BACKUP_RETENTION_YEARLY=1
BACKUP_LOG_FILE=/var/log/backup.log
BACKUP_PROGRESS=auto
BACKUP_PROGRESS_INTERVAL_SECONDS=10
```
## Useful Commands ## Useful Commands
@@ -572,7 +421,7 @@ Collection starts even when the web UI is disabled. Existing databases remain qu
docker compose logs -f samba docker compose logs -f samba
docker compose logs -f samba | grep -E '\\[web\\]|\\[audit\\]' docker compose logs -f samba | grep -E '\\[web\\]|\\[audit\\]'
docker compose exec samba python3 /app/reconcile_shares.py docker compose exec samba python3 /app/reconcile_shares.py
docker compose exec samba python3 /app/backup_to_destination.py docker compose exec samba python3 /app/run_service.py backup_to_destination.py
docker compose exec samba sqlite3 /state/shares.db 'PRAGMA quick_check;' docker compose exec samba sqlite3 /state/shares.db 'PRAGMA quick_check;'
docker compose exec samba sqlite3 /state/shares.db 'SELECT action, count(*) FROM audit_events GROUP BY action;' docker compose exec samba sqlite3 /state/shares.db 'SELECT action, count(*) FROM audit_events GROUP BY action;'
docker compose exec samba testparm -s docker compose exec samba testparm -s
@@ -586,7 +435,7 @@ docker compose exec samba python3 -m json.tool /state/reconcile-status.json
### Domain join fails ### Domain join fails
- Verify service account credentials in `.env`. - Verify the stored domain-join/LDAP credentials in `/admin/settings`.
- Verify DNS resolution from container: - Verify DNS resolution from container:
```bash ```bash
@@ -603,7 +452,7 @@ docker compose exec samba python3 -m json.tool /state/reconcile-status.json
### AD DNS points at 172.x ### AD DNS points at 172.x
- This means Samba registered the container bridge IP. - This means Samba registered the container bridge IP.
- Ensure `.env` contains `AD_DNS_IP=<host LAN IP>` and `AD_DNS_NAME=<server FQDN>`. - Set the AD DNS registration address and name in `/admin/settings` → Server und DNS.
- Recreate/restart the container so startup re-registers AD DNS: - Recreate/restart the container so startup re-registers AD DNS:
```bash ```bash
+52
View File
@@ -0,0 +1,52 @@
"""BIP39 recovery phrases for versioned, reproducible backup archive keys."""
import hashlib
import secrets
import unicodedata
from pathlib import Path
WORDS = (Path(__file__).parent / 'vendor' / 'bip39' / 'english.txt').read_text().splitlines()
WORD_IDS = {word: index for index, word in enumerate(WORDS)}
if len(WORDS) != 2048 or len(WORD_IDS) != 2048:
raise RuntimeError('Invalid BIP39 wordlist')
def phrase_from_entropy(entropy):
if len(entropy) not in (16, 20, 24, 28, 32):
raise ValueError('Invalid entropy length')
checksum_bits = len(entropy) // 4
value = (int.from_bytes(entropy, 'big') << checksum_bits) | (hashlib.sha256(entropy).digest()[0] >> (8 - checksum_bits))
count = (len(entropy) * 8 + checksum_bits) // 11
return ' '.join(WORDS[(value >> (11 * index)) & 2047] for index in reversed(range(count)))
def normalize_phrase(phrase):
phrase = ' '.join(unicodedata.normalize('NFKD', phrase).lower().split())
words = phrase.split()
if len(words) not in (12, 15, 18, 21, 24) or any(word not in WORD_IDS for word in words):
raise ValueError('Ungültige Wiederherstellungsphrase')
value = 0
for word in words:
value = (value << 11) | WORD_IDS[word]
checksum_bits = len(words) // 3
entropy = (value >> checksum_bits).to_bytes((len(words) * 11 - checksum_bits) // 8, 'big')
if phrase_from_entropy(entropy) != phrase:
raise ValueError('Prüfsumme der Wiederherstellungsphrase stimmt nicht')
return phrase
def seed(phrase, passphrase=''):
phrase = normalize_phrase(phrase)
salt = unicodedata.normalize('NFKD', 'mnemonic' + passphrase)
return hashlib.pbkdf2_hmac('sha512', phrase.encode(), salt.encode(), 2048, dklen=64)
def archive_key(phrase):
# A domain-separated archive password, followed by 7z's own AES-256 KDF.
return hashlib.pbkdf2_hmac('sha512', seed(phrase), b'adfs-backup-archive-v1', 1, dklen=32).hex()
def generate():
phrase = phrase_from_entropy(secrets.token_bytes(32))
password = archive_key(phrase)
return {'phrase': phrase, 'password': password, 'keyId': hashlib.sha256(password.encode()).hexdigest()[:24],
'format': 'adfs-backup-archive-v1'}
+57 -10
View File
@@ -968,6 +968,7 @@ def prepare_state_snapshot(
database_relative, database_relative,
f"{database_relative}-wal", f"{database_relative}-wal",
f"{database_relative}-shm", f"{database_relative}-shm",
'configuration.db', 'configuration.db-wal', 'configuration.db-shm',
} }
def ignore_live_database(directory: str, names: List[str]) -> Set[str]: def ignore_live_database(directory: str, names: List[str]) -> Set[str]:
@@ -1002,6 +1003,18 @@ def prepare_state_snapshot(
finally: finally:
destination.close() destination.close()
source.close() source.close()
configuration_path = os.path.join(state_root, 'configuration.db')
if os.path.isfile(configuration_path):
source = sqlite3.connect(f'file:{configuration_path}?mode=ro', uri=True, timeout=30)
destination = sqlite3.connect(os.path.join(staged_state, 'configuration.db'))
os.chmod(os.path.join(staged_state, 'configuration.db'), 0o600)
try:
source.backup(destination)
if destination.execute('PRAGMA quick_check').fetchone()[0] != 'ok':
raise RuntimeError('Configuration snapshot failed its integrity check')
finally:
destination.close()
source.close()
return temporary_root, staged_state return temporary_root, staged_state
except Exception: except Exception:
shutil.rmtree(temporary_root, ignore_errors=True) shutil.rmtree(temporary_root, ignore_errors=True)
@@ -1019,7 +1032,7 @@ def archive_password() -> str:
return password return password
def create_group_archive(source_path: str, archive_path: str, password: str) -> None: def create_group_archive(source_path: str, archive_path: str, password: Optional[str]) -> None:
os.makedirs(os.path.dirname(archive_path), exist_ok=True) os.makedirs(os.path.dirname(archive_path), exist_ok=True)
source_parent = os.path.dirname(source_path) source_parent = os.path.dirname(source_path)
source_name = os.path.basename(source_path) source_name = os.path.basename(source_path)
@@ -1032,14 +1045,15 @@ def create_group_archive(source_path: str, archive_path: str, password: str) ->
"-mx=5", "-mx=5",
"-mmt=on", "-mmt=on",
"-ms=off", "-ms=off",
"-mhe=on", *(['-mhe=on', '-p'] if password else []),
"-p", '-snl',
'-xr!.trash',
"-y", "-y",
archive_path, archive_path,
"--", "--",
source_name, source_name,
], ],
input_text=f"{password}\n", input_text=f"{password}\n" if password else None,
check=False, check=False,
env=os.environ.copy(), env=os.environ.copy(),
cwd=source_parent, cwd=source_parent,
@@ -1153,6 +1167,29 @@ def available_sources(
return sources return sources
def prepare_encrypted_sources(sources, password, temporary_parent=None):
"""Encrypt every original/configuration source, including archive headers."""
root = tempfile.mkdtemp(prefix='backup-encrypted-', dir=temporary_parent or None)
staged = os.path.join(root, 'encrypted')
os.makedirs(staged)
try:
for source_path, destination_path in sources:
name = destination_path.replace('/', '-') + '.7z'
if BACKUP_STATUS is not None:
BACKUP_STATUS.write(state='running', currentSource=destination_path,
message=f'Encrypting {destination_path}', activeFiles=[])
create_group_archive(source_path, os.path.join(staged, name), password)
metadata = {'format': os.getenv('BACKUP_KEY_FORMAT', '7z-aes256'),
'keyId': os.getenv('BACKUP_KEY_ID', ''), 'encrypted': True,
'archives': [destination.replace('/', '-') + '.7z' for _, destination in sources]}
with open(os.path.join(staged, 'backup-format.json'), 'w') as handle:
json.dump(metadata, handle)
return root, [(staged, 'encrypted')]
except BaseException:
shutil.rmtree(root, ignore_errors=True)
raise
def format_host(hostname: str) -> str: def format_host(hostname: str) -> str:
if ":" in hostname and not hostname.startswith("["): if ":" in hostname and not hostname.startswith("["):
return f"[{hostname}]" return f"[{hostname}]"
@@ -1693,6 +1730,11 @@ def run_backup() -> int:
interactive_progress = should_show_progress_bar(progress_mode) interactive_progress = should_show_progress_bar(progress_mode)
destination = parse_destination(destination_url) destination = parse_destination(destination_url)
namespace = os.getenv('BACKUP_NAMESPACE', '').strip('/')
if namespace:
if not re.fullmatch(r'keys/[a-f0-9]{24}|plain', namespace):
raise ValueError('Invalid backup key namespace')
destination.path = destination.path.rstrip('/') + '/' + namespace
BACKUP_STATUS = BackupStatus( BACKUP_STATUS = BackupStatus(
os.getenv("BACKUP_STATUS_FILE", DEFAULT_BACKUP_STATUS_FILE).strip() os.getenv("BACKUP_STATUS_FILE", DEFAULT_BACKUP_STATUS_FILE).strip()
) )
@@ -1703,6 +1745,7 @@ def run_backup() -> int:
backend = None backend = None
state_snapshot_root = None state_snapshot_root = None
group_archive_root = None group_archive_root = None
encrypted_root = None
try: try:
state_snapshot = None state_snapshot = None
if os.path.isdir(STATE_ROOT): if os.path.isdir(STATE_ROOT):
@@ -1710,21 +1753,23 @@ def run_backup() -> int:
state_snapshot_root, state_snapshot = prepare_state_snapshot() state_snapshot_root, state_snapshot = prepare_state_snapshot()
groups_snapshot = None groups_snapshot = None
if os.path.isdir(GROUPS_SOURCE_PATH): encrypted = os.getenv('BACKUP_ENCRYPTION_ENABLED', 'false').lower() == 'true'
if os.path.isdir(GROUPS_SOURCE_PATH) and not encrypted:
BACKUP_STATUS.write( BACKUP_STATUS.write(
state="running", state="running",
currentSource="data/groups", currentSource="data/groups",
message="Creating encrypted group archives", message="Creating group archives",
) )
group_archive_root, groups_snapshot, archive_count = prepare_group_archives( group_archive_root, groups_snapshot, archive_count = prepare_group_archives(password='' if os.getenv('BACKUP_KEY_ID') else os.getenv('BACKUP_ARCHIVE_PASSWORD', ''))
password=archive_password() log(f"Created {archive_count} non-solid group archive(s)")
)
log(f"Created {archive_count} encrypted non-solid group archive(s)")
sources = available_sources(state_snapshot, groups_snapshot) sources = available_sources(state_snapshot, groups_snapshot)
if not sources: if not sources:
log("No backup sources are available, skipping backup") log("No backup sources are available, skipping backup")
return 0 return 0
if encrypted:
encrypted_root, sources = prepare_encrypted_sources(sources, archive_password(),
os.getenv('BACKUP_ARCHIVE_TEMP_DIR', DEFAULT_ARCHIVE_TEMP_DIR))
backend = build_backend(destination) backend = build_backend(destination)
log(f"Starting backup to {redact_destination(destination.raw_url)}") log(f"Starting backup to {redact_destination(destination.raw_url)}")
@@ -1784,6 +1829,8 @@ def run_backup() -> int:
shutil.rmtree(state_snapshot_root, ignore_errors=True) shutil.rmtree(state_snapshot_root, ignore_errors=True)
if group_archive_root is not None: if group_archive_root is not None:
shutil.rmtree(group_archive_root, ignore_errors=True) shutil.rmtree(group_archive_root, ignore_errors=True)
if encrypted_root is not None:
shutil.rmtree(encrypted_root, ignore_errors=True)
def with_lock() -> int: def with_lock() -> int:
+456
View File
@@ -0,0 +1,456 @@
"""Persistent application settings. Environment input is imported only once."""
import argparse
import contextlib
import hashlib
import hmac
import ipaddress
import json
import os
from pathlib import Path
import re
import secrets
import shlex
import sqlite3
import ssl
import sys
import time
import urllib.parse
try:
from . import backup_keys
except ImportError:
import backup_keys
ROOT = Path('/state')
SID = re.compile(r'S-\d+(?:-\d+)+')
DNS = re.compile(r'(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?')
def field(section, label, default='', kind='text', minimum=None, maximum=None, **extra):
return dict(section=section, label=label, default=default, kind=kind, minimum=minimum, maximum=maximum, **extra)
FIELDS = {
'REALM': field('domain', 'Kerberos-Domäne', kind='dns', required=True),
'WORKGROUP': field('domain', 'NetBIOS-Domäne', kind='netbios', required=True),
'DOMAIN': field('domain', 'Domänencontroller / AD-DNS-Name', kind='dns', required=True),
'JOIN_USER': field('domain', 'Konto für Domänenbeitritt und LDAP'),
'JOIN_PASSWORD': field('domain', 'Passwort für Domänenbeitritt und LDAP', kind='secret'),
'LDAP_URI': field('domain', 'LDAP-Adresse (optional)', kind='ldap'),
'LDAP_BASE_DN': field('domain', 'LDAP-Basis-DN (optional)'),
'DOMAIN_USERS_SID': field('groups', 'Benutzergruppe', kind='group', required=True),
'DOMAIN_ADMINS_SID': field('groups', 'Administratorengruppe', kind='group', required=True),
'FSLOGIX_GROUP_SID': field('groups', 'FSLogix-Gruppe', kind='group', required=True),
'NETBIOS_NAME': field('network', 'Servername (NetBIOS)', 'ADSAMBAFSRV', 'netbios'),
'SAMBA_HOSTNAME': field('network', 'Servername (DNS)', 'adsambafsrv', 'dns'),
'AD_DNS_NAME': field('network', 'AD-DNS-Eintrag (optional)', kind='dns'),
'AD_DNS_IP': field('network', 'IP-Adresse für AD-DNS-Eintrag (optional)', kind='ip'),
'WEB_HOSTNAME': field('tls', 'HTTPS-Hostname', 'localhost', 'dns'),
'WEB_TLS_MODE': field('tls', 'HTTPS-Zertifikat', 'self-signed', 'choice', choices=['self-signed', 'acme', 'ca', 'files']),
'WEB_TLS_AUTORENEW': field('tls', 'Zertifikate automatisch erneuern', True, 'bool'),
'ACME_CA_SERVER': field('tls', 'ACME-Verzeichnisadresse', kind='https'),
'ACME_CA_CERTIFICATES_PEM': field('tls', 'CA-Vertrauenszertifikat (PEM)', kind='pem'),
'ACME_CA_CERTIFICATES_URL': field('tls', 'Adresse für CA-Vertrauenszertifikat (optional)', kind='https'),
'ACME_CA_CERTIFICATES_INSECURE_DOWNLOAD': field('tls', 'CA-Download ohne Zertifikatsprüfung', False, 'bool'),
'ACME_RENEW_CHECK_SECONDS': field('tls', 'Erneuerung prüfen (Sekunden)', 900, 'int', 60, 86400),
'TLS_CA_URL': field('tls', 'CA-Adresse', kind='https'),
'TLS_CA_ROOT_PEM': field('tls', 'CA-Wurzelzertifikat (PEM)', kind='pem'),
'TLS_CA_FINGERPRINT': field('tls', 'CA-Fingerabdruck'),
'TLS_CA_PROVISIONER': field('tls', 'CA-Provisioner'),
'TLS_CA_TOKEN': field('tls', 'CA-Einrichtungstoken', kind='secret'),
'TLS_CA_PASSWORD': field('tls', 'CA-Provisioner-Passwort', kind='secret'),
'WEB_TLS_CERT_PEM': field('tls', 'HTTPS-Zertifikat (PEM)', kind='pem'),
'WEB_TLS_KEY_PEM': field('tls', 'Privater HTTPS-Schlüssel (PEM)', kind='secretpem'),
'WEB_TRUSTED_ORIGINS': field('web', 'Weitere HTTPS-Origins (kommagetrennt)', kind='origins'),
'WEB_JWT_TTL_SECONDS': field('web', 'Sitzungsdauer (Sekunden)', 28800, 'int', 300, 604800),
'WEB_AUTH_RECHECK_SECONDS': field('web', 'AD-Rechte erneut prüfen (Sekunden)', 60, 'int', 5, 300),
'WEB_LOGIN_ATTEMPTS_PER_5_MIN': field('web', 'Anmeldeversuche pro IP / 5 Minuten', 10, 'int', 3, 100),
'WEB_LOGIN_ACCOUNT_ATTEMPTS_PER_5_MIN': field('web', 'Anmeldeversuche pro Konto / 5 Minuten', 10, 'int', 3, 100),
'WEB_TLS_HANDSHAKE_TIMEOUT_SECONDS': field('web', 'TLS-Handshake-Zeitlimit (Sekunden)', 5, 'int', 1, 30),
'WEB_REQUEST_TIMEOUT_SECONDS': field('web', 'Anfrage-Zeitlimit (Sekunden)', 30, 'int', 1, 300),
'WEB_MAX_CONNECTIONS': field('web', 'Gleichzeitige Web-Verbindungen', 64, 'int', 4, 512),
'WEB_USAGE_SCAN_INTERVAL_SECONDS': field('web', 'Belegung erfassen (Sekunden)', 900, 'int', 10, 86400),
'WEB_DIRECTORY_CACHE_SECONDS': field('web', 'AD-Verzeichniszwischenspeicher (Sekunden)', 300, 'int', 5, 3600),
'PRIVATE_SKIP_USERS': field('files', 'Private Ordner: ausgeschlossene Benutzer (kommagetrennt)'),
'PRIVATE_SKIP_PREFIXES': field('files', 'Private Ordner: ausgeschlossene Präfixe (kommagetrennt)'),
'TRASH_RETENTION_DAYS': field('files', 'Papierkorb aufbewahren (Tage)', 7, 'int', 1, 365),
'AUDIT_SKIP_USER_SUFFIXES': field('files', 'Protokoll: ausgeschlossene Kontosuffixe', '_svc,_ServiceAcc'),
'AUDIT_QUERY_MAX_DAYS': field('files', 'Protokoll: größter Suchzeitraum (Tage)', 31, 'int', 1, 366),
'DOCUMENT_SCAN_SECONDS': field('documents', 'Dateien erneut erfassen (Sekunden)', 30, 'int', 5, 3600),
'DOCUMENT_OCR_LANGUAGE': field('documents', 'OCR-Sprachen', 'deu+eng', 'languages'),
'DOCUMENT_OCR_TIMEOUT_SECONDS': field('documents', 'OCR-Auftrag-Zeitlimit (Sekunden)', 600, 'int', 30, 3600),
'DOCUMENT_OCR_DPI': field('documents', 'OCR-Auflösung (DPI)', 300, 'int', 150, 400),
'DOCUMENT_OCR_MAX_DIMENSION': field('documents', 'OCR: größte Bildkante (Pixel)', 3500, 'int', 1500, 5000),
'DOCUMENT_OCR_PAGE_TIMEOUT_SECONDS': field('documents', 'OCR-Seiten-Zeitlimit (Sekunden)', 30, 'int', 5, 120),
'DOCUMENT_MAX_FILE_MB': field('documents', 'Größte Datei für Texterfassung (MiB)', 512, 'int', 1, 4096),
'DOCUMENT_MAX_PDF_PAGES': field('documents', 'Größte PDF-Seitenzahl', 500, 'int', 1, 5000),
'BACKUP_DESTINATION': field('backup', 'Sicherungsziel', kind='secreturl'),
'BACKUP_AUTO_ENABLED': field('backup', 'Automatische Sicherungen', False, 'bool'),
'BACKUP_START_HOUR': field('backup', 'Tägliche Startzeit (Stunde, UTC)', 2, 'int', 0, 23),
'BACKUP_RETENTION_DAILY': field('backup', 'Tägliche Sicherungen aufbewahren', 3, 'int', 0, 10000),
'BACKUP_RETENTION_WEEKLY': field('backup', 'Wöchentliche Sicherungen aufbewahren', 2, 'int', 0, 10000),
'BACKUP_RETENTION_MONTHLY': field('backup', 'Monatliche Sicherungen aufbewahren', 2, 'int', 0, 10000),
'BACKUP_RETENTION_YEARLY': field('backup', 'Jährliche Sicherungen aufbewahren', 1, 'int', 0, 10000),
'BACKUP_ENCRYPTION_ENABLED': field('backup', 'Alle Sicherungsdaten verschlüsseln', True, 'bool'),
'BACKUP_PROGRESS_INTERVAL_SECONDS': field('backup', 'Fortschritt erfassen (Sekunden)', 10, 'int', 1, 300),
}
PRIVATE_FIELDS = {'WEB_JWT_SECRET', 'BACKUP_ARCHIVE_PASSWORD', 'BACKUP_KEY_ID', 'BACKUP_KEY_FORMAT',
'BACKUP_NAMESPACE', 'STATE_DB_PATH', 'SHARE_DB_PATH', 'STATE_ROOT', 'GROUP_ROOT',
'GROUP_ARCHIVE_ROOT', 'PRIVATE_ROOT', 'FSLOGIX_ROOT', 'DOCUMENT_STATE_ROOT',
'RECONCILE_STATUS_FILE', 'RECONCILE_LOG_FILE', 'BACKUP_STATUS_FILE', 'BACKUP_LOG_FILE',
'BACKUP_ARCHIVE_TEMP_DIR', 'WEB_TLS_CERT_FILE', 'WEB_TLS_KEY_FILE', 'ACME_CA_CERTIFICATES',
'TLS_CA_ROOT', 'TLS_CA_PROVISIONER_PASSWORD', 'TLS_CA_PROVISIONER_PASSWORD_FILE', 'AUDIT_SOURCE_GLOB', 'AUDIT_ARCHIVE_DIR', 'AUDIT_POLL_SECONDS',
'TLS_CA_STATE_DIR', 'TLS_CA_REBOOTSTRAP', 'BACKUP_PROGRESS',
'WEB_HTTPS_PORT', 'WEB_BIND_PORT', 'WEB_BIND_ADDRESS', 'ACME_HTTP_LISTEN'}
SECTIONS = {'domain': 'Active Directory', 'groups': 'Gruppen für Anmeldung und Systemzugriff',
'network': 'Server und DNS', 'tls': 'HTTPS und Zertifikate', 'web': 'Web-Zugriff',
'files': 'Dateien und Protokolle', 'documents': 'Dokumentindex und OCR', 'backup': 'Sicherungen'}
def validate(name, value):
spec = FIELDS[name]
kind = spec['kind']
if kind == 'bool':
if value in (True, 'true', '1', 1):
return True
if value in (False, 'false', '0', 0):
return False
raise ValueError(spec['label'] + ': ungültiger Schalter')
if kind == 'int':
if isinstance(value, bool) or not re.fullmatch(r'\d+', str(value)):
raise ValueError(spec['label'] + ': ganze Zahl erforderlich')
value = int(value)
if not spec['minimum'] <= value <= spec['maximum']:
raise ValueError(spec['label'] + ': Wert außerhalb des zulässigen Bereichs')
return value
if not isinstance(value, str) or len(value) > (65536 if 'pem' in kind else 4096):
raise ValueError(spec['label'] + ': ungültiger Wert')
if '\0' in value or ('pem' not in kind and any(char in value for char in '\r\n')):
raise ValueError(spec['label'] + ': ungültige Steuerzeichen')
if kind not in ('secret', 'secretpem'):
value = value.strip()
if not value:
return value
if kind == 'dns' and not DNS.fullmatch(value):
raise ValueError(spec['label'] + ': ungültiger DNS-Name')
if kind == 'netbios' and not re.fullmatch(r'[A-Za-z0-9_-]{1,15}', value):
raise ValueError(spec['label'] + ': höchstens 15 Buchstaben/Ziffern, _ oder -')
if kind == 'group' and not SID.fullmatch(value):
raise ValueError(spec['label'] + ': ungültige Gruppen-SID')
if kind == 'ip':
ipaddress.ip_address(value)
if kind == 'languages' and not re.fullmatch(r'[a-z]{3}(?:\+[a-z]{3})*', value):
raise ValueError('Ungültige OCR-Sprachen')
if kind == 'choice' and value not in spec['choices']:
raise ValueError(spec['label'] + ': ungültige Auswahl')
if name in ('ACME_CA_CERTIFICATES_PEM', 'TLS_CA_ROOT_PEM'):
try:
ssl.create_default_context().load_verify_locations(cadata=value)
except ssl.SSLError as exc:
raise ValueError(spec['label'] + ': ungültiges PEM-Zertifikat') from exc
if kind in ('https', 'ldap', 'secreturl'):
parsed = urllib.parse.urlsplit(value)
allowed = {'https'} if kind == 'https' else {'ldap', 'ldaps'} if kind == 'ldap' else {'rsync', 'sftp', 'smb', 'cifs', 'davfs', 'dav', 'webdav', 'https', 'http'}
if parsed.scheme not in allowed or not parsed.hostname or parsed.query or parsed.fragment:
raise ValueError(spec['label'] + ': ungültige Adresse')
if kind == 'https' and (parsed.username is not None or parsed.password is not None):
raise ValueError(spec['label'] + ': Zugangsdaten in dieser Adresse sind nicht zulässig')
if parsed.port is not None and not 1 <= parsed.port <= 65535:
raise ValueError(spec['label'] + ': ungültiger Port')
if any(char in urllib.parse.unquote(value) for char in '\r\n\0'):
raise ValueError(spec['label'] + ': ungültige Steuerzeichen in der Adresse')
if kind == 'origins':
try:
from .web_security import origin
except ImportError:
from web_security import origin
for item in value.split(','):
origin(item.strip())
return value
class Conflict(ValueError):
pass
class Store:
def __init__(self, root=ROOT):
self.root = Path(root)
self.root.mkdir(parents=True, exist_ok=True)
self.path = self.root / 'configuration.db'
fd = os.open(self.path, os.O_CREAT | os.O_RDWR, 0o600)
os.close(fd)
os.chmod(self.path, 0o600)
with self.connect() as conn:
conn.execute('''CREATE TABLE IF NOT EXISTS configuration (
id INTEGER PRIMARY KEY CHECK(id=1), revision INTEGER NOT NULL, phase TEXT NOT NULL,
service_revision INTEGER NOT NULL, settings TEXT NOT NULL)''')
defaults = {name: spec['default'] for name, spec in FIELDS.items()}
defaults['WEB_JWT_SECRET'] = secrets.token_urlsafe(48)
conn.execute('INSERT OR IGNORE INTO configuration VALUES(1,0,?,0,?)', ('unconfigured', json.dumps(defaults)))
conn.execute('''CREATE TABLE IF NOT EXISTS pending_backup_keys (
nonce TEXT PRIMARY KEY, owner TEXT NOT NULL, expires REAL NOT NULL, revision INTEGER NOT NULL,
password TEXT NOT NULL, key_id TEXT NOT NULL, format TEXT NOT NULL)''')
conn.execute('CREATE TABLE IF NOT EXISTS scheduled_backups (slot TEXT PRIMARY KEY)')
@contextlib.contextmanager
def connect(self):
conn = sqlite3.connect(self.path, timeout=30)
conn.row_factory = sqlite3.Row
conn.execute('PRAGMA journal_mode=WAL')
try:
yield conn
conn.commit()
except BaseException:
conn.rollback()
raise
finally:
conn.close()
def snapshot(self):
with self.connect() as conn:
row = dict(conn.execute('SELECT * FROM configuration WHERE id=1').fetchone())
row['values'] = json.loads(row.pop('settings'))
return row
def public(self, section=None):
snap = self.snapshot()
result = {'revision': snap['revision'], 'phase': snap['phase'], 'sections': [],
'encryption': {'keyId': snap['values'].get('BACKUP_KEY_ID', ''),
'legacy': bool(snap['values'].get('BACKUP_ARCHIVE_PASSWORD') and not snap['values'].get('BACKUP_KEY_ID'))}}
for name, label in SECTIONS.items():
if section and section != name:
continue
fields = []
for key, spec in FIELDS.items():
if spec['section'] != name:
continue
value = snap['values'].get(key, spec['default'])
secret = spec['kind'] in ('secret', 'secretpem', 'secreturl')
fields.append(dict(spec, key=key, value='' if secret else value, configured=bool(value) if secret else False))
if spec['kind'] == 'secreturl' and value:
url = urllib.parse.urlsplit(value)
fields[-1]['summary'] = urllib.parse.urlunsplit((url.scheme, url.hostname + (':' + str(url.port) if url.port else ''), url.path, '', ''))
result['sections'].append({'id': name, 'label': label, 'fields': fields})
return result
def save(self, changes, revision, *, bootstrap=False):
if not isinstance(changes, dict) or any(name not in FIELDS for name in changes):
raise ValueError('Unbekannte Einstellung')
normalized = {name: validate(name, value) for name, value in changes.items()}
if not bootstrap and any(name in normalized for name in ('REALM', 'WORKGROUP')):
current = self.snapshot()['values']
if any(normalized[name] != current[name] for name in ('REALM', 'WORKGROUP') if name in normalized):
raise ValueError('Ein Wechsel der AD-Domäne erfordert einen erneuten Domänenbeitritt')
with self.connect() as conn:
conn.execute('BEGIN IMMEDIATE')
snap = dict(conn.execute('SELECT * FROM configuration WHERE id=1').fetchone())
if revision != snap['revision']:
raise Conflict('Einstellungen wurden inzwischen geändert; bitte erneut laden')
values = json.loads(snap['settings'])
values.update(normalized)
if values['WEB_TLS_MODE'] == 'files' and not (values.get('WEB_TLS_CERT_PEM') and values.get('WEB_TLS_KEY_PEM')) and not (values.get('WEB_TLS_CERT_FILE') and values.get('WEB_TLS_KEY_FILE')):
raise ValueError('Bitte HTTPS-Zertifikat und privaten Schlüssel gemeinsam hochladen')
if 'BACKUP_ENCRYPTION_ENABLED' in normalized and values.get('BACKUP_KEY_ID'):
values['BACKUP_NAMESPACE'] = 'keys/' + values['BACKUP_KEY_ID'] if values['BACKUP_ENCRYPTION_ENABLED'] else 'plain'
if values['BACKUP_DESTINATION'] and values['BACKUP_ENCRYPTION_ENABLED'] and not values.get('BACKUP_KEY_ID'):
raise ValueError('Bitte zuerst eine Wiederherstellungsphrase erzeugen und bestätigen')
if values['WEB_TLS_MODE'] == 'files' and (values.get('WEB_TLS_CERT_PEM') or values.get('WEB_TLS_KEY_PEM')):
try:
from .tls_configuration import validate_pair
except ImportError:
from tls_configuration import validate_pair
validate_pair(values['WEB_TLS_CERT_PEM'], values['WEB_TLS_KEY_PEM'])
previous = json.loads(snap['settings'])
if values == previous:
return self.public()
service_change = any(FIELDS[key]['section'] != 'backup' and (not bootstrap or FIELDS[key]['section'] != 'groups') and values[key] != previous.get(key) for key in normalized)
conn.execute('UPDATE configuration SET settings=?,revision=revision+1,service_revision=service_revision+? WHERE id=1',
(json.dumps(values), int(service_change)))
return self.public()
def phase(self, value):
with self.connect() as conn:
conn.execute('UPDATE configuration SET phase=?,revision=revision+1 WHERE id=1', (value,))
def bootstrap_code(self):
path = self.root / 'setup-code'
try:
return path.read_text().strip()
except FileNotFoundError:
code = secrets.token_urlsafe(32)
try:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
except FileExistsError:
return path.read_text().strip()
with os.fdopen(fd, 'w') as handle:
handle.write(code)
return code
def accepts_bootstrap(self, supplied):
return self.snapshot()['phase'] != 'configured' and bool(supplied) and hmac.compare_digest(supplied.encode(), self.bootstrap_code().encode())
def finish(self, revision):
with self.connect() as conn:
conn.execute('BEGIN IMMEDIATE')
row = conn.execute('SELECT * FROM configuration WHERE id=1').fetchone()
if row['revision'] != revision:
raise Conflict('Einstellungen wurden inzwischen geändert')
values = json.loads(row['settings'])
required = ('REALM', 'WORKGROUP', 'DOMAIN', 'DOMAIN_USERS_SID', 'DOMAIN_ADMINS_SID', 'FSLOGIX_GROUP_SID')
if any(not values.get(key) for key in required):
raise ValueError('Domäne und Gruppen müssen vollständig eingerichtet sein')
conn.execute("UPDATE configuration SET phase='configured',revision=revision+1,service_revision=service_revision+1 WHERE id=1")
(self.root / 'setup-code').unlink(missing_ok=True)
def generate_key(self, owner):
result = backup_keys.generate()
nonce = secrets.token_urlsafe(32)
with self.connect() as conn:
conn.execute('DELETE FROM pending_backup_keys WHERE expires<?', (time.time(),))
revision = conn.execute('SELECT revision FROM configuration WHERE id=1').fetchone()[0]
conn.execute('INSERT INTO pending_backup_keys VALUES(?,?,?,?,?,?,?)',
(nonce, owner, time.time() + 900, revision, result['password'], result['keyId'], result['format']))
return {key: result[key] for key in ('phrase', 'keyId', 'format')} | {'nonce': nonce}
def activate_key(self, owner, nonce, written_down, acknowledge_old):
if written_down is not True:
raise ValueError('Bitte bestätigen, dass die Phrase sicher notiert wurde')
with self.connect() as conn:
conn.execute('BEGIN IMMEDIATE')
pending = conn.execute('SELECT * FROM pending_backup_keys WHERE nonce=? AND owner=? AND expires>?', (nonce, owner, time.time())).fetchone()
current = conn.execute('SELECT * FROM configuration WHERE id=1').fetchone()
if not pending or pending['revision'] != current['revision']:
raise Conflict('Schlüsselerzeugung ist abgelaufen oder Einstellungen wurden geändert')
values = json.loads(current['settings'])
if values.get('BACKUP_ARCHIVE_PASSWORD') and acknowledge_old is not True:
raise ValueError('Alte Sicherungen benötigen weiterhin ihre alte Phrase bzw. ihr altes Passwort; ohne diese sind deren Daten verloren')
values.update(BACKUP_ARCHIVE_PASSWORD=pending['password'], BACKUP_KEY_ID=pending['key_id'],
BACKUP_KEY_FORMAT=pending['format'], BACKUP_NAMESPACE='keys/' + pending['key_id'], BACKUP_ENCRYPTION_ENABLED=True)
conn.execute('UPDATE configuration SET settings=?,revision=revision+1 WHERE id=1', (json.dumps(values),))
conn.execute('DELETE FROM pending_backup_keys WHERE nonce=?', (nonce,))
return self.public('backup')
def import_legacy(self, values):
snap = self.snapshot()
if snap['phase'] == 'configured' or snap['revision'] != 0:
raise Conflict('Die Erstübernahme wurde bereits durchgeführt')
public = {key: validate(key, value) for key, value in values.items() if key in FIELDS}
private = {key: value for key, value in values.items() if key in PRIVATE_FIELDS}
if private.get('TLS_CA_PROVISIONER_PASSWORD'):
public['TLS_CA_PASSWORD'] = private.pop('TLS_CA_PROVISIONER_PASSWORD')
if private.get('TLS_CA_PROVISIONER_PASSWORD_FILE') and Path(private['TLS_CA_PROVISIONER_PASSWORD_FILE']).is_file():
public['TLS_CA_PASSWORD'] = Path(private.pop('TLS_CA_PROVISIONER_PASSWORD_FILE')).read_text().rstrip('\r\n')
if not public.get('WEB_TLS_MODE'):
public['WEB_TLS_MODE'] = 'acme' if public.get('ACME_CA_SERVER') else 'ca' if public.get('TLS_CA_URL') else 'files' if private.get('WEB_TLS_CERT_FILE') else 'self-signed'
if not all(public.get(key) for key in ('REALM', 'WORKGROUP', 'DOMAIN', 'DOMAIN_USERS_SID', 'DOMAIN_ADMINS_SID')):
return False
public.setdefault('FSLOGIX_GROUP_SID', public['DOMAIN_USERS_SID'])
# Keep the legacy format and password until encryption is deliberately
# enabled/renewed. Existing remote snapshots remain at their old path.
public['BACKUP_ENCRYPTION_ENABLED'] = False
public.setdefault('BACKUP_AUTO_ENABLED', True)
combined = snap['values'] | public | private
with self.connect() as conn:
conn.execute('BEGIN IMMEDIATE')
changed = conn.execute("UPDATE configuration SET settings=?,phase='configured',revision=1,service_revision=1 WHERE id=1 AND revision=0", (json.dumps(combined),)).rowcount
if not changed:
raise Conflict('Einstellungen wurden inzwischen geändert')
return True
def environment(self, materialize=True):
values = self.snapshot()['values']
result = {name: ('true' if value else 'false') if isinstance(value, bool) else str(value)
for name, value in values.items() if name in FIELDS or name in PRIVATE_FIELDS}
for name in ('LDAP_URI', 'LDAP_BASE_DN', 'AD_DNS_NAME'):
if not result.get(name):
result.pop(name, None)
if values.get('REALM') and not result.get('LDAP_BASE_DN'):
result['LDAP_BASE_DN'] = ','.join('DC=' + part for part in values['REALM'].lower().split('.'))
if values.get('REALM') and not result.get('AD_DNS_NAME'):
hostname = values.get('SAMBA_HOSTNAME', 'adsambafsrv').lower()
result['AD_DNS_NAME'] = hostname if '.' in hostname else hostname + '.' + values['REALM'].lower()
result.update(WEB_ENABLED='true', STATE_ROOT=str(self.root), STATE_DB_PATH=values.get('STATE_DB_PATH', str(self.root / 'shares.db')),
WEB_TLS_CERT_FILE=values.get('WEB_TLS_CERT_FILE', str(self.root / 'tls' / 'web.crt')),
WEB_TLS_KEY_FILE=values.get('WEB_TLS_KEY_FILE', str(self.root / 'tls' / 'web.key')),
WEB_BIND_PORT=values.get('WEB_BIND_PORT', '8443'), WEB_HTTPS_PORT=values.get('WEB_HTTPS_PORT', '443'),
ACME_HTTP_LISTEN='127.0.0.1:8080', ACME_CA_CERTIFICATES=values.get('ACME_CA_CERTIFICATES') or
(str(self.root / 'tls' / 'acme-ca-certificates.pem') if values.get('ACME_CA_CERTIFICATES_PEM') or values.get('ACME_CA_CERTIFICATES_URL') else '/etc/ssl/certs/ca-certificates.crt'))
for key, filename in (('ACME_CA_CERTIFICATES_PEM', 'acme-ca-certificates.pem'), ('TLS_CA_ROOT_PEM', 'ca-root.pem'),
('TLS_CA_PASSWORD', 'ca-password')):
if values.get(key):
directory = self.root / 'tls'
directory.mkdir(mode=0o700, exist_ok=True)
target = directory / filename
if materialize and (not target.exists() or target.read_text() != values[key]):
try:
from .tls_configuration import write_private
except ImportError:
from tls_configuration import write_private
write_private(target, values[key])
if key == 'TLS_CA_ROOT_PEM':
result['TLS_CA_ROOT'] = str(target)
if not result.get('TLS_CA_FINGERPRINT'):
result['TLS_CA_FINGERPRINT'] = hashlib.sha256(ssl.PEM_cert_to_DER_cert(values[key])).hexdigest()
if key == 'ACME_CA_CERTIFICATES_PEM':
result['ACME_CA_CERTIFICATES'] = str(target)
if key == 'TLS_CA_PASSWORD':
result['TLS_CA_PROVISIONER_PASSWORD_FILE'] = str(target)
elif key == 'TLS_CA_PASSWORD' and materialize:
(self.root / 'tls' / filename).unlink(missing_ok=True)
return result
def service_environment(self, inherited=None):
result = dict(os.environ if inherited is None else inherited)
for name in set(FIELDS) | PRIVATE_FIELDS:
result.pop(name, None)
result.update(self.environment())
return result
def parse_legacy(text):
result = {}
for line in text.splitlines():
line = line.strip()
if not line or line.startswith('#'):
continue
if line.startswith('export '):
line = line[7:]
key, sep, value = line.partition('=')
if not sep or key not in FIELDS and key not in PRIVATE_FIELDS:
continue
tokens = shlex.split(value, comments=True, posix=True)
result[key] = ' '.join(tokens)
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument('action', choices=['import-legacy', 'import-runtime', 'export-shell'])
args = parser.parse_args()
store = Store()
if args.action in ('import-legacy', 'import-runtime'):
payload = sys.stdin.read(1024 * 1024)
if store.snapshot()['revision'] != 0:
print('Persistent configuration already exists; legacy import skipped.')
return
if args.action == 'import-runtime':
items = json.loads(payload)
if not isinstance(items, list) or any(not isinstance(item, str) for item in items):
raise ValueError('Invalid container configuration')
values = dict(item.split('=', 1) for item in items if '=' in item)
else:
values = parse_legacy(payload)
if not store.import_legacy(values):
if args.action == 'import-runtime':
print('No legacy domain configuration found; continue web setup.')
return
raise ValueError('Unvollständige frühere Konfiguration')
print('Imported existing configuration without changing data or the domain join.')
else:
for key, value in store.environment().items():
print('export ' + key + '=' + shlex.quote(value))
if __name__ == '__main__':
main()
+133
View File
@@ -0,0 +1,133 @@
"""Keep setup HTTPS available while AD services join, start, or recover."""
import datetime as dt
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
import configuration
import tls_configuration
import http_setup
APP = Path(__file__).parent
def stop(process):
if process is None:
return
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
return
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
process.wait()
def start(command, store, extra=None):
environment = store.service_environment()
environment.update(extra or {})
return subprocess.Popen(command, env=environment, start_new_session=True)
def write_status(store, **changes):
target = store.root / 'services-status.json'
temporary = target.with_suffix('.tmp')
temporary.write_text(json.dumps(changes))
os.chmod(temporary, 0o600)
os.replace(temporary, target)
def main():
store = configuration.Store()
if store.snapshot()['revision'] == 0:
store.import_legacy(dict(os.environ))
if store.snapshot()['phase'] != 'configured':
print('[setup] Open http://<server>/ for HTTPS only. HTTPS setup code: ' + http_setup.setup_code(store), flush=True)
print('[setup] Open https://<server>/ and enter setup code: ' + store.bootstrap_code(), flush=True)
tls_configuration.prepare(store)
ui = service = backup = certificate = None
http = start([sys.executable, str(APP / 'http_setup.py')], store)
revision = -1
running = True
next_retry = 0
next_tls_retry = 0
def terminate(*args):
nonlocal running
running = False
signal.signal(signal.SIGTERM, terminate)
signal.signal(signal.SIGINT, terminate)
try:
while running:
snap = store.snapshot()
if snap['service_revision'] != revision:
stop(service)
stop(certificate)
stop(ui)
service = ui = certificate = None
Path('/run/adfs-domain-ready').unlink(missing_ok=True)
Path('/run/adfs-services-ready').unlink(missing_ok=True)
revision = snap['service_revision']
next_retry = 0
next_tls_retry = 0
try:
tls_configuration.prepare(store)
except (OSError, ValueError, subprocess.SubprocessError):
write_status(store, state='failed', message='HTTPS-Zertifikat konnte nicht eingerichtet werden')
if ui is None or ui.poll() is not None:
ui = start([sys.executable, str(APP / 'run_service.py'), 'web_ui.py'], store)
if http.poll() is not None:
http = start([sys.executable, str(APP / 'http_setup.py')], store)
tls_marker = Path(store.environment()['WEB_TLS_CERT_FILE']).parent / 'bootstrap-certificate'
wants_acme = snap['values']['WEB_TLS_MODE'] == 'acme' and bool(snap['values']['ACME_CA_SERVER'])
if certificate is not None and certificate.poll() is not None:
succeeded = certificate.returncode == 0
stop(certificate)
certificate = None
tls_configuration.write_private(store.root / 'https-status.json', json.dumps({'state': 'ready' if succeeded else 'failed', 'message': 'HTTPS ist eingerichtet. Über HTTPS fortfahren.' if succeeded else 'ACME-Zertifikat konnte nicht angefordert werden. Hostname, CA und Erreichbarkeit von Port 80 prüfen.'}))
if wants_acme and tls_marker.exists() and certificate is None and time.monotonic() >= next_tls_retry:
tls_configuration.write_private(store.root / 'https-status.json', json.dumps({'state': 'working', 'message': 'ACME-Zertifikat wird angefordert'}))
certificate = start([str(APP / 'init.sh'), '--configure-tls'], store, {'ADFS_SUPERVISED': 'true'})
next_tls_retry = time.monotonic() + 60
desired = snap['phase'] in ('joining', 'groups', 'configured') and all(snap['values'].get(key) for key in ('REALM', 'WORKGROUP', 'DOMAIN'))
if wants_acme and (certificate is not None or tls_marker.exists()):
desired = False
if desired and (service is None or service.poll() is not None) and time.monotonic() >= next_retry:
mode = [] if snap['phase'] == 'configured' else ['--bootstrap-domain']
write_status(store, state='starting', message='AD-Dienste werden gestartet')
service = start([str(APP / 'init.sh'), *mode], store, {'ADFS_SUPERVISED': 'true'})
next_retry = time.monotonic() + 30
if service is not None and service.poll() is not None:
code = service.returncode
stop(service)
service = None
Path('/run/adfs-services-ready').unlink(missing_ok=True)
write_status(store, state='failed', message=f'AD-Dienste konnten nicht gestartet werden (Status {code}); Einstellungen prüfen')
elif service is not None and Path('/run/adfs-domain-ready').exists():
if snap['phase'] == 'joining':
store.phase('groups')
write_status(store, state='running', message='Domänenverbindung hergestellt')
if backup is not None and backup.poll() is not None:
backup = None
values = snap['values']
now = dt.datetime.now(dt.timezone.utc)
if snap['phase'] == 'configured' and backup is None and values['BACKUP_DESTINATION'] and values['BACKUP_AUTO_ENABLED'] and now.hour == values['BACKUP_START_HOUR']:
slot = now.strftime('%Y-%m-%dT%H')
with store.connect() as conn:
claimed = conn.execute('INSERT OR IGNORE INTO scheduled_backups VALUES(?)', (slot,)).rowcount
if claimed:
backup = start([sys.executable, str(APP / 'run_service.py'), 'backup_to_destination.py'], store, {'BACKUP_TRIGGER': 'automatic'})
time.sleep(1)
finally:
stop(service)
stop(ui)
stop(backup)
stop(certificate)
stop(http)
return 0
if __name__ == '__main__':
sys.exit(main())
+5
View File
@@ -0,0 +1,5 @@
import ssl
import urllib.request
response = urllib.request.urlopen('https://127.0.0.1:8443/healthz', context=ssl._create_unverified_context(), timeout=3)
raise SystemExit(0 if response.status == 200 else 1)
+166
View File
@@ -0,0 +1,166 @@
"""HTTP exposes public HTTPS setup only; credentials always require TLS."""
import hmac
import http.client
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import secrets
import ssl
import threading
import urllib.parse
try:
from . import configuration
from .tls_configuration import write_private
except ImportError:
import configuration
from tls_configuration import write_private
APP = Path(__file__).parent
TLS_FIELDS = {'WEB_HOSTNAME', 'ACME_CA_SERVER', 'ACME_CA_CERTIFICATES_PEM'}
def setup_code(store):
path = store.root / 'https-setup-code'
try:
return path.read_text().strip()
except FileNotFoundError:
code = secrets.token_urlsafe(32)
try:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
except FileExistsError:
return path.read_text().strip()
with os.fdopen(fd, 'w') as handle:
handle.write(code)
return code
class Server(ThreadingHTTPServer):
daemon_threads = True
allow_reuse_address = True
capacity = threading.BoundedSemaphore(32)
def process_request(self, request, address):
if not self.capacity.acquire(blocking=False):
self.shutdown_request(request)
return
try:
super().process_request(request, address)
except BaseException:
self.capacity.release()
raise
def process_request_thread(self, request, address):
try:
request.settimeout(10)
super().process_request_thread(request, address)
finally:
self.capacity.release()
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
pass # Never log setup codes, URLs or request bodies.
def reply(self, status, value, content_type='application/json'):
payload = json.dumps(value).encode() if content_type == 'application/json' else value
self.send_response(status)
self.send_header('Content-Type', content_type)
self.send_header('Content-Length', str(len(payload)))
self.send_header('Cache-Control', 'no-store')
self.send_header('X-Content-Type-Options', 'nosniff')
self.send_header('Referrer-Policy', 'no-referrer')
self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
self.end_headers()
self.wfile.write(payload)
def do_GET(self):
path = urllib.parse.urlsplit(self.path).path
if path.startswith('/.well-known/acme-challenge/'):
# The ACME standalone responder listens on loopback, never port 80.
proxy = http.client.HTTPConnection('127.0.0.1', 8080, timeout=5)
try:
proxy.request('GET', self.path, headers={'Host': self.headers.get('Host', '')})
response = proxy.getresponse()
payload = response.read(16385)
if len(payload) > 16384:
raise ValueError('Challenge too large')
self.reply(response.status, payload, 'text/plain')
except (OSError, ValueError, http.client.HTTPException):
self.reply(404, {'error': 'Keine aktive ACME-Challenge'})
finally:
proxy.close()
return
store = configuration.Store()
snap = store.snapshot()
port = str(snap['values'].get('WEB_HTTPS_PORT', '443'))
https_url = 'https://' + snap['values']['WEB_HOSTNAME'] + (':' + port if port != '443' else '') + '/'
if path == '/api/https/status':
try:
progress = json.loads((store.root / 'https-status.json').read_text())
except (OSError, ValueError):
progress = {'state': 'waiting'}
self.reply(200, {'state': progress.get('state'), 'message': progress.get('message', ''),
'hostname': snap['values']['WEB_HOSTNAME'], 'httpsUrl': https_url,
'configured': snap['phase'] == 'configured'})
return
if snap['phase'] == 'configured':
self.send_response(308)
self.send_header('Location', https_url)
self.send_header('Content-Length', '0')
self.end_headers()
return
files = {'/': ('https-setup.html', 'text/html; charset=utf-8'),
'/assets/https-setup.js': ('https-setup.js', 'text/javascript; charset=utf-8'),
'/assets/styles.css': ('styles.css', 'text/css; charset=utf-8')}
if path not in files:
self.reply(403, {'error': 'Über HTTP ist ausschließlich die HTTPS-Einrichtung verfügbar'})
return
filename, kind = files[path]
self.reply(200, (APP / 'web' / filename).read_bytes(), kind)
def do_POST(self):
store = configuration.Store()
if self.path != '/api/https/configure' or store.snapshot()['phase'] == 'configured':
self.reply(403, {'error': 'Über HTTP ist ausschließlich die HTTPS-Einrichtung verfügbar'})
return
if self.headers.get_content_type() != 'application/json' or self.headers.get('Sec-Fetch-Site') in {'same-site', 'cross-site'}:
self.reply(403, {'error': 'Anfrage muss vom selben Origin stammen'})
return
if self.headers.get('Origin') != 'http://' + self.headers.get('Host', ''):
self.reply(403, {'error': 'Ungültiger Origin'})
return
supplied = self.headers.get('X-HTTPS-Setup-Code', '')
if not supplied or not hmac.compare_digest(supplied.encode(), setup_code(store).encode()):
self.reply(403, {'error': 'Ungültiger HTTPS-Einrichtungscode'})
return
try:
length = int(self.headers.get('Content-Length', '0'))
if not 0 < length <= 131072:
raise ValueError('Ungültige Anfragelänge')
body = json.loads(self.rfile.read(length))
if not isinstance(body, dict) or set(body) - TLS_FIELDS:
raise ValueError('Nur HTTPS-Hostname, ACME-Adresse und CA-Zertifikat sind zulässig')
if not body.get('WEB_HOSTNAME') or not body.get('ACME_CA_SERVER'):
raise ValueError('HTTPS-Hostname und ACME-Adresse sind erforderlich')
url = urllib.parse.urlsplit(body['ACME_CA_SERVER'])
if url.username is not None or url.password is not None:
raise ValueError('Die HTTP-Einrichtung darf keine Zugangsdaten enthalten')
if body.get('ACME_CA_CERTIFICATES_PEM'):
try:
ssl.create_default_context().load_verify_locations(cadata=body['ACME_CA_CERTIFICATES_PEM'])
except (ssl.SSLError, TypeError) as exc:
raise ValueError('CA-Zertifikat ist kein gültiges PEM-Zertifikat') from exc
body['WEB_TLS_MODE'] = 'acme'
snap = store.snapshot()
store.save(body, snap['revision'], bootstrap=True)
# Force re-issuance on an explicit retry, including a changed root CA.
write_private(Path(store.environment()['WEB_TLS_CERT_FILE']).parent / 'bootstrap-certificate', '1')
write_private(store.root / 'https-status.json', json.dumps({'state': 'pending', 'message': 'ACME-Zertifikat wird angefordert'}))
self.reply(202, {'accepted': True})
except (ValueError, TypeError, OSError) as exc:
self.reply(400, {'error': str(exc)})
if __name__ == '__main__':
Server(('0.0.0.0', 80), Handler).serve_forever()
+41 -6
View File
@@ -355,7 +355,7 @@ selected_tls_mode() {
printf 'ca' printf 'ca'
fi fi
;; ;;
acme|ca|files) printf '%s' "$WEB_TLS_MODE" ;; acme|ca|files|self-signed) printf '%s' "$WEB_TLS_MODE" ;;
*) return 1 ;; *) return 1 ;;
esac esac
} }
@@ -458,7 +458,7 @@ configure_web_tls() {
local provisioner_password_file="" local provisioner_password_file=""
if ! tls_mode="$(selected_tls_mode)"; then if ! tls_mode="$(selected_tls_mode)"; then
printf '[init] ERROR: WEB_TLS_MODE must be acme, ca, or files\n' >&2 printf '[init] ERROR: WEB_TLS_MODE must be self-signed, acme, ca, or files\n' >&2
return 1 return 1
fi fi
export ACTIVE_WEB_TLS_MODE="$tls_mode" export ACTIVE_WEB_TLS_MODE="$tls_mode"
@@ -469,6 +469,10 @@ configure_web_tls() {
export STEPPATH="${TLS_CA_STATE_DIR:-/state/tls-client}" export STEPPATH="${TLS_CA_STATE_DIR:-/state/tls-client}"
mkdir -p "$(dirname "$WEB_TLS_CERT_FILE")" "$(dirname "$WEB_TLS_KEY_FILE")" "$STEPPATH" mkdir -p "$(dirname "$WEB_TLS_CERT_FILE")" "$(dirname "$WEB_TLS_KEY_FILE")" "$STEPPATH"
if [[ "$tls_mode" == "self-signed" ]]; then
return
fi
if [[ "$tls_mode" == "files" ]]; then if [[ "$tls_mode" == "files" ]]; then
if [[ ! -s "$WEB_TLS_CERT_FILE" || ! -s "$WEB_TLS_KEY_FILE" ]]; then if [[ ! -s "$WEB_TLS_CERT_FILE" || ! -s "$WEB_TLS_KEY_FILE" ]]; then
printf '[init] ERROR: WEB_TLS_MODE=files requires %s and %s\n' "$WEB_TLS_CERT_FILE" "$WEB_TLS_KEY_FILE" >&2 printf '[init] ERROR: WEB_TLS_MODE=files requires %s and %s\n' "$WEB_TLS_CERT_FILE" "$WEB_TLS_KEY_FILE" >&2
@@ -481,8 +485,9 @@ configure_web_tls() {
require_env ACME_CA_SERVER require_env ACME_CA_SERVER
require_env ACME_CA_CERTIFICATES require_env ACME_CA_CERTIFICATES
ensure_acme_ca_certificates ensure_acme_ca_certificates
if [[ ! -s "$WEB_TLS_CERT_FILE" || ! -s "$WEB_TLS_KEY_FILE" ]]; then if [[ ! -s "$WEB_TLS_CERT_FILE" || ! -s "$WEB_TLS_KEY_FILE" || -f "$(dirname "$WEB_TLS_CERT_FILE")/bootstrap-certificate" ]]; then
request_acme_certificate request_acme_certificate
rm -f "$(dirname "$WEB_TLS_CERT_FILE")/bootstrap-certificate"
fi fi
return return
fi fi
@@ -495,7 +500,7 @@ configure_web_tls() {
step ca bootstrap --force --ca-url "$TLS_CA_URL" --fingerprint "$TLS_CA_FINGERPRINT" step ca bootstrap --force --ca-url "$TLS_CA_URL" --fingerprint "$TLS_CA_FINGERPRINT"
fi fi
if [[ ! -s "$WEB_TLS_CERT_FILE" || ! -s "$WEB_TLS_KEY_FILE" ]]; then if [[ ! -s "$WEB_TLS_CERT_FILE" || ! -s "$WEB_TLS_KEY_FILE" || -f "$(dirname "$WEB_TLS_CERT_FILE")/bootstrap-certificate" ]]; then
log "Requesting HTTPS certificate for ${WEB_HOSTNAME}" log "Requesting HTTPS certificate for ${WEB_HOSTNAME}"
if [[ -n "${TLS_CA_TOKEN:-}" ]]; then if [[ -n "${TLS_CA_TOKEN:-}" ]]; then
step ca certificate "$WEB_HOSTNAME" "$WEB_TLS_CERT_FILE" "$WEB_TLS_KEY_FILE" --token "$TLS_CA_TOKEN" --force step ca certificate "$WEB_HOSTNAME" "$WEB_TLS_CERT_FILE" "$WEB_TLS_KEY_FILE" --token "$TLS_CA_TOKEN" --force
@@ -522,6 +527,7 @@ configure_web_tls() {
fi fi
chmod 0600 "$WEB_TLS_KEY_FILE" chmod 0600 "$WEB_TLS_KEY_FILE"
chmod 0644 "$WEB_TLS_CERT_FILE" chmod 0644 "$WEB_TLS_CERT_FILE"
rm -f "$(dirname "$WEB_TLS_CERT_FILE")/bootstrap-certificate"
} }
start_acme_renewal_daemon() { start_acme_renewal_daemon() {
@@ -546,7 +552,17 @@ start_observability_services() {
log 'Starting Samba audit collector' log 'Starting Samba audit collector'
python3 /app/audit_collector.py & python3 /app/audit_collector.py &
if web_should_start; then if [[ "${ADFS_SUPERVISED:-false}" == "true" ]]; then
configure_web_tls
if env_is_true "${WEB_TLS_AUTORENEW:-true}"; then
case "$ACTIVE_WEB_TLS_MODE" in
acme) start_acme_renewal_daemon ;;
ca) step ca renew --daemon --force "$WEB_TLS_CERT_FILE" "$WEB_TLS_KEY_FILE" & ;;
esac
fi
log 'Starting document search and OCR worker'
python3 /app/document_index.py &
elif web_should_start; then
ensure_web_jwt_secret ensure_web_jwt_secret
configure_web_tls configure_web_tls
unset TLS_CA_PROVISIONER_PASSWORD TLS_CA_TOKEN unset TLS_CA_PROVISIONER_PASSWORD TLS_CA_TOKEN
@@ -582,7 +598,7 @@ PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
17 * * * * root source /app/runtime.env && /usr/bin/python3 /app/trash.py --cleanup 17 * * * * root source /app/runtime.env && /usr/bin/python3 /app/trash.py --cleanup
EOF EOF
if [[ -n "${BACKUP_DESTINATION:-}" ]] && env_is_true "${BACKUP_AUTO_ENABLED:-true}"; then if [[ "${ADFS_SUPERVISED:-false}" != "true" ]] && [[ -n "${BACKUP_DESTINATION:-}" ]] && env_is_true "${BACKUP_AUTO_ENABLED:-true}"; then
cat >> /etc/cron.d/reconcile-shares <<EOF cat >> /etc/cron.d/reconcile-shares <<EOF
0 ${BACKUP_START_HOUR} * * * root source /app/runtime.env && BACKUP_TRIGGER=automatic /usr/bin/python3 /app/backup_to_destination.py 0 ${BACKUP_START_HOUR} * * * root source /app/runtime.env && BACKUP_TRIGGER=automatic /usr/bin/python3 /app/backup_to_destination.py
EOF EOF
@@ -591,6 +607,17 @@ EOF
chmod 0644 /etc/cron.d/reconcile-shares chmod 0644 /etc/cron.d/reconcile-shares
} }
if [[ "${ADFS_SUPERVISED:-false}" == "true" ]]; then
source <(python3 /app/configuration.py export-shell)
fi
if [[ "${1:-}" == "--configure-tls" ]]; then
configure_web_tls
exit 0
fi
if [[ "${1:-}" == "--bootstrap-domain" ]]; then
export DOMAIN_USERS_SID="${DOMAIN_USERS_SID:-S-1-5-32-545}"
export DOMAIN_ADMINS_SID="${DOMAIN_ADMINS_SID:-S-1-5-32-544}"
fi
require_env REALM require_env REALM
require_env WORKGROUP require_env WORKGROUP
require_env DOMAIN require_env DOMAIN
@@ -624,8 +651,15 @@ ensure_machine_keytab
log 'Starting winbindd' log 'Starting winbindd'
winbindd -F --no-process-group & winbindd -F --no-process-group &
winbind_pid=$!
wait_for_winbind wait_for_winbind
touch /run/adfs-domain-ready
if [[ "${1:-}" == "--bootstrap-domain" ]]; then
log 'Domain joined; waiting for web setup to select groups.'
wait "$winbind_pid"
exit "$?"
fi
register_ad_dns_record register_ad_dns_record
resolve_share_groups_from_sids resolve_share_groups_from_sids
@@ -654,4 +688,5 @@ log 'Starting cron daemon'
cron -f & cron -f &
log 'Starting smbd in foreground' log 'Starting smbd in foreground'
touch /run/adfs-services-ready
exec smbd -F --no-process-group exec smbd -F --no-process-group
+31
View File
@@ -0,0 +1,31 @@
"""Offline recovery; never accept a recovery phrase through argv/environment."""
import argparse
import getpass
from pathlib import Path
import subprocess
try:
from .backup_keys import archive_key
except ImportError:
from backup_keys import archive_key
def main():
parser = argparse.ArgumentParser(description='Decrypt a backup archive into a new recovery directory; never overwrite live data.')
parser.add_argument('archive', type=Path)
parser.add_argument('output', type=Path)
args = parser.parse_args()
if args.output.exists():
parser.error('The recovery output must be a new directory')
if not args.archive.is_file():
parser.error('Archive does not exist')
password = archive_key(getpass.getpass('24-word recovery phrase: '))
args.output.mkdir(mode=0o700, parents=True)
result = subprocess.run(['7z', 'x', '-aos', '-o' + str(args.output.resolve()), '--', str(args.archive.resolve())],
input=(password + '\n').encode(), capture_output=True)
if result.returncode:
raise SystemExit('Recovery failed. Check the phrase, archive, and available disk space. No live data was changed.')
print('Recovered into ' + str(args.output) + '; inspect before copying to live storage.')
if __name__ == '__main__':
main()
+17
View File
@@ -0,0 +1,17 @@
"""Start a service from a single persisted configuration snapshot."""
import os
from pathlib import Path
import runpy
import sys
import configuration
if __name__ == '__main__':
environment = configuration.Store().service_environment()
os.environ.clear()
os.environ.update(environment)
allowed = {'web_ui.py', 'backup_to_destination.py', 'document_index.py', 'audit_collector.py', 'reconcile_shares.py', 'trash.py'}
if len(sys.argv) < 2 or sys.argv[1] not in allowed:
raise SystemExit('Unknown service')
target = Path(__file__).parent / sys.argv[1]
sys.argv = [str(target), *sys.argv[2:]]
runpy.run_path(str(target), run_name='__main__')
+80
View File
@@ -0,0 +1,80 @@
"""Provision persistent bootstrap TLS and validate uploaded certificate pairs."""
import os
import json
from pathlib import Path
import socket
import ssl
import subprocess
import tempfile
import time
def write_private(path, value):
path = Path(path)
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
fd, temp = tempfile.mkstemp(prefix='.tls-', dir=path.parent)
try:
os.fchmod(fd, 0o600)
with os.fdopen(fd, 'w') as handle:
handle.write(value)
handle.flush()
os.fsync(handle.fileno())
os.replace(temp, path)
finally:
if os.path.exists(temp):
os.unlink(temp)
def validate_pair(cert, key):
with tempfile.TemporaryDirectory() as root:
cert_path, key_path = Path(root) / 'cert', Path(root) / 'key'
write_private(cert_path, cert)
write_private(key_path, key)
try:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert_path, key_path)
except (OSError, ssl.SSLError) as exc:
raise ValueError('Zertifikat und privater Schlüssel sind ungültig oder passen nicht zusammen') from exc
def prepare(store):
values = store.snapshot()['values']
environment = store.environment()
cert = Path(environment['WEB_TLS_CERT_FILE'])
key = Path(environment['WEB_TLS_KEY_FILE'])
mode = values['WEB_TLS_MODE']
marker = cert.parent / 'bootstrap-certificate'
identity_path = cert.parent / 'configuration.json'
identity = {'hostname': values['WEB_HOSTNAME'], 'mode': mode}
try:
previous = json.loads(identity_path.read_text())
except (OSError, ValueError):
previous = None
if mode == 'files' and values.get('WEB_TLS_CERT_PEM') and values.get('WEB_TLS_KEY_PEM'):
validate_pair(values['WEB_TLS_CERT_PEM'], values['WEB_TLS_KEY_PEM'])
if not cert.exists() or cert.read_text() != values['WEB_TLS_CERT_PEM'] or not key.exists() or key.read_text() != values['WEB_TLS_KEY_PEM']:
write_private(key, values['WEB_TLS_KEY_PEM'])
write_private(cert, values['WEB_TLS_CERT_PEM'])
marker.unlink(missing_ok=True)
write_private(identity_path, json.dumps(identity))
return
if cert.is_file() and key.is_file() and (previous is None or previous == identity):
valid = True
try:
validate_pair(cert.read_text(), key.read_text())
expired = ssl.cert_time_to_seconds(ssl._ssl._test_decode_cert(str(cert))['notAfter']) <= time.time() + 86400 * 7
except (OSError, ValueError, ssl.SSLError):
valid = False
expired = True
if valid and (not expired or mode != 'self-signed'):
write_private(identity_path, json.dumps(identity))
return
cert.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
hostname = values['WEB_HOSTNAME'] or 'localhost'
with tempfile.TemporaryDirectory(dir=cert.parent) as root:
generated_cert, generated_key = Path(root) / 'cert', Path(root) / 'key'
command = ['step', 'certificate', 'create', hostname, str(generated_cert), str(generated_key),
'--profile', 'self-signed', '--subtle', '--no-password', '--insecure', '--not-after', '8760h',
'--san', 'localhost', '--san', '127.0.0.1', '--san', hostname, '--san', socket.gethostname()]
subprocess.run(command, check=True, capture_output=True, timeout=30)
write_private(key, generated_key.read_text())
write_private(cert, generated_cert.read_text())
write_private(marker, '1')
write_private(identity_path, json.dumps(identity))
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2013-2016 Pavol Rusnak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+7
View File
@@ -0,0 +1,7 @@
The English BIP39 wordlist is vendored from Bitcoin BIPs:
https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt
The identical list is distributed by Trezor's python-mnemonic under the included MIT license:
https://github.com/trezor/python-mnemonic
SHA-256 of english.txt: 2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda
+2048
View File
File diff suppressed because it is too large. Load diff
+7 -1
View File
@@ -108,6 +108,7 @@ function empty(message) { return `<div class="empty">${esc(message)}</div>`; }
function badge(text, kind = "") { return `<span class="badge ${kind}">${esc(text)}</span>`; } function badge(text, kind = "") { return `<span class="badge ${kind}">${esc(text)}</span>`; }
function routeFor(path) { function routeFor(path) {
if (path.startsWith('/admin/settings') || path.startsWith('/settings')) return 'settings';
path = path.replace(/^\/admin(?=\/|$)/, "") || "/overview"; path = path.replace(/^\/admin(?=\/|$)/, "") || "/overview";
if (path.startsWith("/storage/data")) return "storage-data"; if (path.startsWith("/storage/data")) return "storage-data";
if (path.startsWith("/storage/users")) return "storage-users"; if (path.startsWith("/storage/users")) return "storage-users";
@@ -152,6 +153,10 @@ async function navigate(path, replace = false) {
if (route === "backup") await renderBackup(); if (route === "backup") await renderBackup();
if (route === "report") await renderReport(); if (route === "report") await renderReport();
if (route === "system") await renderSystem(); if (route === "system") await renderSystem();
if (route === 'settings') {
content.innerHTML = pageHead('Einstellungen', 'Serverkonfiguration dauerhaft speichern.') + '<div id="configuration-settings"></div>';
await ConfigurationUI.mount(document.querySelector('#configuration-settings'), {api, notice, onDirty: dirty => { state.accessDirty = dirty; }});
}
content.focus(); content.focus();
} catch (error) { } catch (error) {
content.innerHTML = pageHead("Seite konnte nicht geladen werden", error.message) + `<section class="panel">${empty("Dienststatus prüfen und erneut versuchen.")}</section>`; content.innerHTML = pageHead("Seite konnte nicht geladen werden", error.message) + `<section class="panel">${empty("Dienststatus prüfen und erneut versuchen.")}</section>`;
@@ -563,7 +568,8 @@ async function renderBackup() {
"Sicherungen", "Sicherungen",
"Sicherungen manuell starten sowie Fortschritt und Ausgabe verfolgen.", "Sicherungen manuell starten sowie Fortschritt und Ausgabe verfolgen.",
'<button id="start-backup" type="button">Sicherung jetzt starten</button>' '<button id="start-backup" type="button">Sicherung jetzt starten</button>'
) + '<div id="backup-body"></div>'; ) + '<details class="panel"><summary>Sicherungsziel, Zeitplan und Verschlüsselung</summary><div id="backup-settings" class="settings-advanced"></div></details><div id="backup-body"></div>';
void ConfigurationUI.mount(document.querySelector('#backup-settings'), {api, notice, section:'backup', onDirty: dirty => { state.accessDirty = dirty; }}).catch(error => notice(error.message));
const button = document.querySelector("#start-backup"); const button = document.querySelector("#start-backup");
const body = document.querySelector("#backup-body"); const body = document.querySelector("#backup-body");
let logLines = []; let logLines = [];
+1
View File
@@ -0,0 +1 @@
<!doctype html><html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>HTTPS einrichten · Dateiserver</title><link rel="stylesheet" href="/assets/styles.css"></head><body><header class="portal-header"><strong>Dateiserver · HTTPS einrichten</strong></header><main class="setup-main"><h1>HTTPS zuerst einrichten</h1><p>Über HTTP können Sie ausschließlich das HTTPS-Zertifikat einrichten. Domänenbeitritt und alle Zugangsdaten werden anschließend über HTTPS konfiguriert.</p><section class="panel"><form id="https-form" class="stack"><label>HTTPS-Einrichtungscode<input name="code" type="password" autocomplete="off" required></label><small class="muted">Den Code finden Sie unter „HTTPS setup code“ in <code>docker compose logs samba</code>.</small><label>HTTPS-Hostname<input name="hostname" required placeholder="files.example.org"></label><label>ACME-Verzeichnisadresse<input name="acme" type="url" required placeholder="https://ca.example.org/acme/acme/directory"></label><label>Eigenes Root-CA-Zertifikat (optional, PEM)<input name="root" type="file" accept=".pem,.crt,.cer"></label><small class="muted">Ohne eigenen Upload werden die öffentlichen System-CAs verwendet.</small><p id="https-error" class="error" role="alert" hidden></p><button type="submit">HTTPS einrichten</button></form></section><p id="https-status" role="status"></p><a id="https-next" hidden>Über HTTPS mit der Einrichtung fortfahren</a></main><script src="/assets/https-setup.js" defer></script></body></html>
+21
View File
@@ -0,0 +1,21 @@
(() => {
const form = document.querySelector('#https-form'), status = document.querySelector('#https-status'), errorBox = document.querySelector('#https-error'), next = document.querySelector('#https-next');
form.elements.hostname.value = location.hostname;
form.onsubmit = async event => {
event.preventDefault(); errorBox.hidden = true; const button = form.querySelector('button'); button.disabled = true;
try {
const root = form.elements.root.files[0];
const response = await fetch('/api/https/configure', {method:'POST', headers:{'Content-Type':'application/json', 'X-HTTPS-Setup-Code':form.elements.code.value}, body:JSON.stringify({WEB_HOSTNAME:form.elements.hostname.value, ACME_CA_SERVER:form.elements.acme.value, ACME_CA_CERTIFICATES_PEM:root ? await root.text() : ''})});
const data = await response.json(); if (!response.ok) throw new Error(data.error);
form.elements.code.value = ''; status.textContent = 'ACME-Zertifikat wird angefordert …';
} catch (error) { errorBox.textContent = error.message; errorBox.hidden = false; }
finally { button.disabled = false; }
};
setInterval(async () => {
try {
const data = await (await fetch('/api/https/status')).json(); status.textContent = data.message || '';
next.hidden = !(data.state === 'ready' || data.configured);
if (!next.hidden) { next.href = data.httpsUrl; }
} catch { status.textContent = 'Dienst wird neu gestartet …'; }
}, 2000);
})();
+2
View File
@@ -37,6 +37,7 @@
<a href="/admin/backup" data-route="backup">Sicherungen</a> <a href="/admin/backup" data-route="backup">Sicherungen</a>
<a href="/admin/report" data-route="report">PDF-Bericht</a> <a href="/admin/report" data-route="report">PDF-Bericht</a>
<a href="/admin/system" data-route="system">System</a> <a href="/admin/system" data-route="system">System</a>
<a href="/admin/settings" data-route="settings">Einstellungen</a>
</nav> </nav>
<div class="sidebar-footer"><a href="/">Dateiansicht</a><span id="session-user"></span><button id="logout" class="link-button">Abmelden</button></div> <div class="sidebar-footer"><a href="/">Dateiansicht</a><span id="session-user"></span><button id="logout" class="link-button">Abmelden</button></div>
</aside> </aside>
@@ -44,6 +45,7 @@
<main id="content" class="content" tabindex="-1"></main> <main id="content" class="content" tabindex="-1"></main>
</div> </div>
<div id="toast" class="toast" role="status" hidden></div> <div id="toast" class="toast" role="status" hidden></div>
<script src="/assets/settings.js" defer></script>
<script src="/assets/app.js" defer></script> <script src="/assets/app.js" defer></script>
</body> </body>
</html> </html>
+121
View File
@@ -0,0 +1,121 @@
/* Configuration controls share the application's existing form styles. */
(() => {
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;'}[c]));
const labels = {'self-signed':'Selbstsigniert', acme:'ACME', ca:'Smallstep CA', files:'Zertifikat und Schlüssel hochladen'};
function fieldMarkup(field, groups = [], bootstrap = false) {
const {key, kind, label, value, configured} = field;
const id = 'setting-' + key;
let input;
if (kind === 'bool') return `<label class="settings-check"><input id="${id}" name="${key}" type="checkbox" ${value ? 'checked' : ''}>${esc(label)}</label>`;
if (kind === 'group') {
const options = [...groups];
if (value && !options.some(group => group.sid === value)) options.push({sid:value, name:value});
input = `<select id="${id}" name="${key}" required>${options.map(group => `<option value="${esc(group.sid)}" ${group.sid === value ? 'selected' : ''}>${esc(group.name)}</option>`).join('')}</select>`;
} else if (kind === 'choice') input = `<select id="${id}" name="${key}">${field.choices.map(option => `<option value="${esc(option)}" ${value === option ? 'selected' : ''}>${esc(labels[option] || option)}</option>`).join('')}</select>`;
else if (kind.includes('pem')) input = `<textarea id="${id}" name="${key}" rows="5" spellcheck="false" autocomplete="off" placeholder="${configured ? 'Gespeichert; leer lassen zum Beibehalten' : '-----BEGIN …-----'}">${esc(value)}</textarea>`;
else input = `<input id="${id}" name="${key}" type="${kind === 'int' ? 'number' : ['secret', 'secreturl'].includes(kind) ? 'password' : 'text'}" value="${esc(value)}" ${kind === 'int' ? `min="${field.minimum}" max="${field.maximum}" step="1"` : ''} ${!bootstrap && ['REALM','WORKGROUP'].includes(key) ? 'readonly' : ''} ${field.required ? 'required' : ''} autocomplete="${kind === 'secret' ? 'new-password' : 'off'}" placeholder="${configured ? 'Gespeichert; leer lassen zum Beibehalten' : key === 'BACKUP_DESTINATION' ? 'sftp://benutzer:passwort@server/pfad' : ''}">`;
const hint = field.summary ? `<small class="muted">Aktuelles Ziel: ${esc(field.summary)}</small>` : key === 'BACKUP_DESTINATION' ? '<small class="muted">Unterstützt rsync, SFTP, SMB und WebDAV. Zugangsdaten in der Adresse bitte URL-kodieren.</small>' : '';
input = input.replace(/^<(input|select|textarea)\b/, `<$1 aria-label="${esc(label)}"`);
const clear = configured && ['secret','secretpem'].includes(kind) ? `<label class="settings-check"><input name="clear-${key}" type="checkbox">Gespeicherten Wert löschen</label>` : '';
return `<div data-setting="${key}"><label>${esc(label)}${input}${hint}</label>${clear}</div>`;
}
function readValues(form, fields) {
const values = {};
for (const field of fields) {
const input = form.elements.namedItem(field.key);
if (!input || input.disabled) continue;
if (form.elements.namedItem('clear-' + field.key)?.checked) { values[field.key] = ''; continue; }
if (['secret','secreturl','secretpem'].includes(field.kind) && !input.value) continue;
values[field.key] = field.kind === 'bool' ? input.checked : field.kind === 'int' ? Number(input.value) : input.value;
}
return values;
}
function tlsVisibility(form) {
const mode = form.elements.namedItem('WEB_TLS_MODE');
if (!mode) return;
const update = () => form.querySelectorAll('[data-setting]').forEach(label => {
const key = label.dataset.setting;
const active = key.startsWith('ACME_') ? mode.value === 'acme' : key.startsWith('TLS_CA_') ? mode.value === 'ca' : ['WEB_TLS_CERT_PEM','WEB_TLS_KEY_PEM'].includes(key) ? mode.value === 'files' : true;
label.hidden = !active;
label.querySelectorAll('input,textarea,select').forEach(input => { input.disabled = !active; });
});
mode.addEventListener('change', update); update();
}
async function recoveryDialog(api, configuration, refreshed) {
const result = await api('/api/settings/backup-key/generate', {method:'POST', body:'{}'});
const oldKey = configuration.encryption.keyId || configuration.encryption.legacy;
const dialog = document.createElement('dialog');
dialog.className = 'access-dialog settings-key-dialog';
dialog.setAttribute('aria-labelledby', 'recovery-title');
dialog.innerHTML = `<h2 id="recovery-title">Wiederherstellungsphrase notieren</h2><p>Diese Phrase wird nur jetzt angezeigt. Sie entschlüsselt die vollständige Sicherung, einschließlich Zugangsdaten und Serverzustand. Bewahren Sie sie getrennt vom Server auf.</p><ol class="recovery-words">${result.phrase.split(' ').map(word => `<li>${esc(word)}</li>`).join('')}</ol><p class="muted">Schlüsselkennung: ${esc(result.keyId)}</p><form class="stack"><label class="settings-check"><input name="written" type="checkbox" required>Ich habe alle 24 Wörter in der richtigen Reihenfolge sicher notiert.</label>${oldKey ? '<p class="error">Alte Sicherungen bleiben erhalten und benötigen weiterhin ihre alte Phrase bzw. ihr altes Passwort. Geht diese Information verloren, sind die darin gespeicherten Daten nicht wiederherstellbar.</p><label class="settings-check"><input name="old" type="checkbox" required>Ich bewahre auch die bisherige Phrase bzw. das bisherige Passwort auf.</label>' : ''}<p class="error" role="alert" hidden></p><div class="access-dialog-actions"><button type="button" data-close>Abbrechen</button><button type="submit">Schlüssel aktivieren</button></div></form>`;
// The phrase stays in this dialog only; it is never stored in browser storage.
result.phrase = '';
document.body.append(dialog);
dialog.addEventListener('close', () => { dialog.replaceChildren(); dialog.remove(); }, {once:true});
dialog.querySelector('[data-close]').onclick = () => dialog.close();
dialog.querySelector('form').onsubmit = async event => {
event.preventDefault(); const form = event.currentTarget, button = form.querySelector('[type=submit]'); button.disabled = true;
try {
await api('/api/settings/backup-key/activate', {method:'POST', body:JSON.stringify({nonce:result.nonce, writtenDown:form.elements.written.checked, acknowledgeOldBackups:oldKey ? form.elements.old.checked : false})});
dialog.close(); await refreshed();
} catch (error) { const target = form.querySelector('[role=alert]'); target.textContent = error.message; target.hidden = false; button.disabled = false; }
};
dialog.showModal();
}
async function mount(host, {api, notice, section = '', initialSection = '', onDirty = () => {}}) {
const data = await api('/api/settings' + (section ? '?section=' + section : ''));
if (!host.isConnected) return;
let selected = section || initialSection || data.sections[0].id;
const render = async () => {
const current = data.sections.find(item => item.id === selected);
let groups = [];
if (selected === 'groups') groups = (await api('/api/settings/groups')).groups;
if (!host.isConnected) return;
host.innerHTML = `${!section ? `<div class="settings-tabs" role="group" aria-label="Einstellungen">${data.sections.map(item => `<button type="button" data-section="${item.id}" aria-pressed="${item.id === selected}">${esc(item.label)}</button>`).join('')}</div>` : ''}<section class="panel"><h2>${esc(current.label)}</h2><form class="stack settings-form">${current.fields.map(field => fieldMarkup(field, groups)).join('')}${selected === 'backup' ? `<div class="settings-encryption"><strong>Verschlüsselungsschlüssel</strong><p>${data.encryption.keyId ? 'Aktiver Schlüssel: ' + esc(data.encryption.keyId) : data.encryption.legacy ? 'Bisheriges Archivpasswort übernommen. Eine neue Phrase aktiviert die Verschlüsselung aller Sicherungsdaten.' : 'Noch kein Wiederherstellungsschlüssel eingerichtet.'}</p><button type="button" data-generate>${data.encryption.keyId || data.encryption.legacy ? 'Neue Wiederherstellungsphrase erzeugen' : 'Wiederherstellungsphrase erzeugen'}</button></div><label class="settings-check"><input type="checkbox" name="clearDestination">Sicherungsziel entfernen und Sicherungen deaktivieren</label>` : ''}<p class="error" role="alert" hidden></p><div class="toolbar"><button type="submit">Änderungen speichern</button><span class="muted" role="status"></span></div></form></section>`;
const form = host.querySelector('form'); tlsVisibility(form);
form.addEventListener('input', () => onDirty(true));
host.querySelectorAll('[data-section]').forEach(button => { button.onclick = async () => {
if (form.dataset.dirty === 'true' && !confirm('Ungespeicherte Änderungen verwerfen?')) return;
onDirty(false); selected = button.dataset.section; await render();
}; });
form.addEventListener('input', () => { form.dataset.dirty = 'true'; });
if (selected === 'backup') host.querySelector('[data-generate]').onclick = async () => {
try {
const draft = form.dataset.dirty === 'true' ? readValues(form, current.fields) : null;
const clearDestination = form.elements.clearDestination?.checked;
await recoveryDialog(api, data, async () => {
onDirty(false);
await mount(host, {api, notice, section, initialSection:selected, onDirty});
if (draft) {
draft.BACKUP_ENCRYPTION_ENABLED = true;
const next = host.querySelector('form');
for (const [key, value] of Object.entries(draft)) {
const input = next.elements.namedItem(key);
if (input) { if (input.type === 'checkbox') input.checked = value; else input.value = value; }
}
if (next.elements.clearDestination) next.elements.clearDestination.checked = clearDestination;
next.dataset.dirty = 'true'; onDirty(true);
}
notice('Verschlüsselungsschlüssel aktiviert.');
});
} catch (error) { notice(error.message); }
};
form.onsubmit = async event => {
event.preventDefault(); const button = form.querySelector('[type=submit]'); button.disabled = true;
const errorBox = form.querySelector('[role=alert]'); errorBox.hidden = true;
try {
const values = readValues(form, current.fields);
if (form.elements.clearDestination?.checked) { values.BACKUP_DESTINATION = ''; values.BACKUP_AUTO_ENABLED = false; }
const saved = await api('/api/settings', {method:'POST', body:JSON.stringify({revision:data.revision, values})});
onDirty(false); form.dataset.dirty = 'false';
Object.assign(data, saved);
form.querySelector('[role=status]').textContent = saved.restartRequired ? 'Gespeichert. Dienste starten neu; anschließend die Seite neu laden.' : 'Gespeichert.';
form.querySelectorAll('input[type=password],textarea[name=WEB_TLS_KEY_PEM]').forEach(input => { input.value = ''; });
} catch (error) { errorBox.textContent = error.message; errorBox.hidden = false; }
finally { button.disabled = false; }
};
};
await render();
}
window.ConfigurationUI = {mount, fieldMarkup, readValues, tlsVisibility};
})();
+7
View File
@@ -0,0 +1,7 @@
<!doctype html>
<html lang="de"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Dateiserver einrichten</title><link rel="stylesheet" href="/assets/styles.css"></head><body>
<header class="portal-header"><strong>Dateiserver · Ersteinrichtung</strong></header>
<main class="setup-main"><h1>Dateiserver einrichten</h1><p id="setup-status" role="status"></p><p id="setup-error" class="error" role="alert" hidden></p>
<section id="setup-unlock" class="panel"><h2>Einrichtung entsperren</h2><p>Den einmaligen Einrichtungscode finden Sie im Containerprotokoll: <code>docker compose logs samba</code>.</p><form class="stack"><label>Einrichtungscode<input name="code" type="password" autocomplete="off" required autofocus></label><button type="submit">Weiter</button></form></section>
<div id="setup-content" hidden></div></main>
<script src="/assets/settings.js" defer></script><script src="/assets/setup.js" defer></script></body></html>
+62
View File
@@ -0,0 +1,62 @@
(() => {
let token = '', snapshot = null, polling = false;
const content = document.querySelector('#setup-content'), errorBox = document.querySelector('#setup-error'), status = document.querySelector('#setup-status');
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;', "'":'&#39;'}[c]));
const showError = error => { errorBox.textContent = error.message; errorBox.hidden = false; };
async function api(path, options = {}) {
const response = await fetch('/api/bootstrap/' + path, {...options, headers:{'Content-Type':'application/json', 'X-Setup-Token':token}, credentials:'same-origin'});
const result = await response.json();
if (!response.ok) throw new Error(result.error || 'Einrichtung konnte nicht geladen werden');
return result;
}
async function refresh() {
snapshot = await api('settings');
status.textContent = snapshot.services?.message || '';
if (snapshot.phase === 'groups' && !content.querySelector('#setup-groups')) await renderGroups();
}
async function renderGroups() {
const {groups} = await api('groups');
const fields = snapshot.sections.find(item => item.id === 'groups').fields.map(field => ({...field, value:field.value || groups.find(group => group.sid.endsWith(field.key === 'DOMAIN_ADMINS_SID' ? '-512' : '-513'))?.sid || groups[0]?.sid || ''}));
content.innerHTML = `<section class="panel"><h2>Gruppen auswählen</h2><p>Diese Gruppen steuern SMB-Anmeldung, Verwaltung und FSLogix. Dateizugriffe werden später individuell pro Benutzer zugeordnet.</p><form id="setup-groups" class="stack">${fields.map(field => ConfigurationUI.fieldMarkup(field, groups, true)).join('')}<label>Administratorkonto für die erste Anmeldung<input name="username" value="${esc(snapshot.sections.find(item => item.id === 'domain').fields.find(field => field.key === 'JOIN_USER').value)}" autocomplete="username" required></label><label>Passwort<input name="password" type="password" autocomplete="current-password" required></label><button type="submit">Einrichtung abschließen</button></form></section>`;
content.querySelector('form').onsubmit = async event => {
event.preventDefault(); const form = event.currentTarget, button = form.querySelector('button'); button.disabled = true; errorBox.hidden = true;
try {
await refresh();
await api('finish', {method:'POST', body:JSON.stringify({revision:snapshot.revision, values:ConfigurationUI.readValues(form, fields), username:form.elements.username.value, password:form.elements.password.value})});
form.elements.password.value = ''; token = ''; status.textContent = 'Einrichtung abgeschlossen. Dienste werden gestartet.';
content.innerHTML = '<section class="panel"><a href="/">Zur Anmeldung</a></section>';
polling = false;
} catch (error) { showError(error); button.disabled = false; }
};
}
function renderDomain() {
const essentials = new Set(['REALM','WORKGROUP','DOMAIN','JOIN_USER','JOIN_PASSWORD','NETBIOS_NAME','SAMBA_HOSTNAME','WEB_HOSTNAME','WEB_TLS_MODE','AD_DNS_IP','AD_DNS_NAME']);
const fields = snapshot.sections.filter(section => ['domain','network','tls'].includes(section.id)).flatMap(section => section.fields);
const hostname = fields.find(field => field.key === 'WEB_HOSTNAME');
if (hostname.value === 'localhost') hostname.value = location.hostname;
content.innerHTML = `<section class="panel"><h2>Domäne und Server</h2><form id="setup-domain" class="stack">${fields.filter(field => essentials.has(field.key)).map(field => ConfigurationUI.fieldMarkup(field, [], true)).join('')}<details><summary>LDAP- und Zertifikatseinstellungen</summary><div class="stack settings-advanced">${fields.filter(field => !essentials.has(field.key)).map(field => ConfigurationUI.fieldMarkup(field, [], true)).join('')}</div></details><button type="submit">Domäne beitreten</button></form></section><details class="panel"><summary>Bestehende Installation übernehmen</summary><p>Die bisherige .env-Datei einmalig importieren. Dateien, bestehender Domänenbeitritt, Rechte und Sicherungen bleiben erhalten.</p><form id="setup-import" class="stack"><label>Bisherige Konfigurationsdatei<input type="file" name="legacy" required></label><button type="submit">Konfiguration importieren</button></form></details>`;
const form = content.querySelector('#setup-domain'); ConfigurationUI.tlsVisibility(form);
form.onsubmit = async event => {
event.preventDefault(); errorBox.hidden = true; const button = form.querySelector('[type=submit]'); button.disabled = true;
try {
await refresh();
snapshot = await api('domain', {method:'POST', body:JSON.stringify({revision:snapshot.revision, values:ConfigurationUI.readValues(form, fields)})});
form.elements.JOIN_PASSWORD.value = ''; status.textContent = 'Domänenbeitritt läuft. Bei einem Fehler können Sie die Angaben korrigieren und erneut versuchen.';
polling = true;
} catch (error) { showError(error); }
finally { button.disabled = false; }
};
content.querySelector('#setup-import').onsubmit = async event => {
event.preventDefault(); errorBox.hidden = true;
try { const text = await event.currentTarget.elements.legacy.files[0].text(); await api('import', {method:'POST', body:JSON.stringify({text})}); token = ''; location.assign('/'); }
catch (error) { showError(error); }
};
}
document.querySelector('#setup-unlock form').onsubmit = async event => {
event.preventDefault(); const form = event.currentTarget; errorBox.hidden = true; token = form.elements.code.value;
try { await refresh(); form.elements.code.value = ''; document.querySelector('#setup-unlock').hidden = true; content.hidden = false; if (snapshot.phase !== 'groups') renderDomain(); polling = snapshot.phase !== 'unconfigured'; }
catch (error) { token = ''; showError(error); }
};
setInterval(async () => { if (polling && token) { try { await refresh(); } catch (error) { showError(error); } } }, 3000);
api('status').then(result => { if (result.configured) location.replace('/'); }).catch(showError);
})();
+16
View File
@@ -251,3 +251,19 @@ mark { background: #fff0a0; color: #111; }
.document-dialog-head { gap: .5rem; } .document-dialog-head { gap: .5rem; }
.document-dialog-head .row-actions { flex-wrap: nowrap; } .document-dialog-head .row-actions { flex-wrap: nowrap; }
} }
/* Setup and configuration use the existing typography, borders and controls. */
.setup-main { max-width: 780px; margin: 2rem auto; padding: 0 1rem 2rem; }
.settings-form { max-width: 700px; }
.settings-form textarea, .settings-advanced textarea { width: 100%; padding: .4rem; font: inherit; border: 1px solid #999; resize: vertical; }
.settings-check { display: flex; align-items: flex-start; gap: .5rem; }
.settings-check input { width: auto; flex-shrink: 0; margin-top: .25rem; }
.settings-tabs { display: flex; flex-wrap: wrap; gap: .4rem; margin-bottom: 1rem; }
.settings-tabs button[aria-pressed=true] { font-weight: bold; border-color: #111; background: #ddd; }
.settings-encryption { padding: .8rem 0; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; }
.settings-encryption p { margin: .4rem 0; overflow-wrap: anywhere; }
.settings-advanced { margin-top: .8rem; }
.recovery-words { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: .5rem 1.5rem; padding-left: 2rem; font-family: monospace; }
.settings-key-dialog { width: min(660px,calc(100vw - 2rem)); }
html:has(.settings-key-dialog[open]), body:has(.settings-key-dialog[open]) { overflow: hidden; }
@media (max-width: 480px) { .recovery-words { grid-template-columns: repeat(2,minmax(0,1fr)); } .settings-encryption button { white-space: normal; } }
+4
View File
@@ -67,6 +67,10 @@ class Sessions:
with self.connection() as conn, conn: with self.connection() as conn, conn:
conn.execute('DELETE FROM web_sessions WHERE id=?', (self.key(jti),)) conn.execute('DELETE FROM web_sessions WHERE id=?', (self.key(jti),))
def recheck_all(self):
with self.connection() as conn, conn:
conn.execute('UPDATE web_sessions SET checked=0')
def close(self): def close(self):
with self.lock: with self.lock:
if self.memory is not None: if self.memory is not None:
+170 -6
View File
@@ -27,11 +27,11 @@ from typing import Dict, List, Optional, Tuple
try: try:
from app import reconcile_shares as directory from app import reconcile_shares as directory
from app import trash, access_control, documents, web_security from app import trash, access_control, documents, web_security, configuration
from app.account_policy import is_excluded_user from app.account_policy import is_excluded_user
except ImportError: # Container execution uses /app as the import root. except ImportError: # Container execution uses /app as the import root.
import reconcile_shares as directory import reconcile_shares as directory
import trash, access_control, documents, web_security import trash, access_control, documents, web_security, configuration
from account_policy import is_excluded_user from account_policy import is_excluded_user
try: try:
@@ -130,6 +130,8 @@ class ActionConflict(RuntimeError):
def launch_background(command: List[str], extra_env: Dict[str, str]) -> None: def launch_background(command: List[str], extra_env: Dict[str, str]) -> None:
environment = os.environ.copy() environment = os.environ.copy()
environment.update(extra_env) environment.update(extra_env)
if CONFIG is not None:
environment.update(CONFIG.environment())
try: try:
process = subprocess.Popen( process = subprocess.Popen(
command, command,
@@ -148,7 +150,7 @@ def launch_background(command: List[str], extra_env: Dict[str, str]) -> None:
def start_backup_action(username: str) -> Dict[str, object]: def start_backup_action(username: str) -> Dict[str, object]:
if not os.getenv("BACKUP_DESTINATION", "").strip(): if not os.getenv("BACKUP_DESTINATION", "").strip():
raise ActionConflict("Es ist kein Sicherungsziel eingerichtet") raise ActionConflict("Es ist kein Sicherungsziel eingerichtet")
if not os.getenv("BACKUP_ARCHIVE_PASSWORD", ""): if env_bool('BACKUP_ENCRYPTION_ENABLED', False) and not os.getenv("BACKUP_ARCHIVE_PASSWORD", ""):
raise ActionConflict("BACKUP_ARCHIVE_PASSWORD ist nicht gesetzt") raise ActionConflict("BACKUP_ARCHIVE_PASSWORD ist nicht gesetzt")
with ACTION_LAUNCH_LOCK: with ACTION_LAUNCH_LOCK:
if lock_is_held(BACKUP_LOCK_FILE): if lock_is_held(BACKUP_LOCK_FILE):
@@ -438,7 +440,7 @@ def authenticate_user(username: str, password: str) -> Optional[Dict[str, str]]:
return current_identity(user_sid_match.group(0)) return current_identity(user_sid_match.group(0))
def current_identity(sid: str): def current_identity(sid: str, admin_sid=None):
try: try:
group_result = subprocess.run(["wbinfo", "--user-sids", sid], capture_output=True, group_result = subprocess.run(["wbinfo", "--user-sids", sid], capture_output=True,
text=True, timeout=15, check=False) text=True, timeout=15, check=False)
@@ -446,7 +448,7 @@ def current_identity(sid: str):
return None return None
if group_result.returncode != 0: if group_result.returncode != 0:
return None return None
admin_sid = os.environ["DOMAIN_ADMINS_SID"].casefold() admin_sid = (admin_sid or os.environ["DOMAIN_ADMINS_SID"]).casefold()
group_sids = {value.casefold() for value in SID_RE.findall(group_result.stdout)} group_sids = {value.casefold() for value in SID_RE.findall(group_result.stdout)}
try: try:
resolved = subprocess.run(["wbinfo", "--sid-to-name", sid], capture_output=True, text=True, timeout=15, check=False) resolved = subprocess.run(["wbinfo", "--sid-to-name", sid], capture_output=True, text=True, timeout=15, check=False)
@@ -863,6 +865,7 @@ class App:
APP: Optional[App] = None APP: Optional[App] = None
CONFIG = None
class Handler(BaseHTTPRequestHandler): class Handler(BaseHTTPRequestHandler):
@@ -871,6 +874,133 @@ class Handler(BaseHTTPRequestHandler):
def log_message(self, fmt: str, *args) -> None: def log_message(self, fmt: str, *args) -> None:
log(f"{self.client_address[0]} {fmt % args}") log(f"{self.client_address[0]} {fmt % args}")
def reload_configuration(self):
if CONFIG is not None:
for name in ('LDAP_URI', 'LDAP_BASE_DN', 'AD_DNS_NAME'):
os.environ.pop(name, None)
os.environ.update(CONFIG.environment(materialize=False))
def domain_groups(self):
entries = directory.search_directory_entries('(objectClass=group)', access_control.ATTRS)
result = []
for entry in entries:
principal = directory.parse_principal_from_entry(entry)
if principal and directory.is_group_principal(principal):
sid = str(principal.get('objectSid') or '')
if SID_RE.fullmatch(sid):
result.append({'sid': sid, 'name': str(principal.get('samAccountName') or sid)})
return sorted(result, key=lambda row: row['name'].casefold())
def bootstrap(self, path, mutation=False):
if CONFIG is None:
self.send_error_json(HTTPStatus.NOT_FOUND, 'Nicht gefunden')
return
snap = CONFIG.snapshot()
if path == '/api/bootstrap/status' and not mutation:
self.send_json({'phase': snap['phase'], 'configured': snap['phase'] == 'configured'})
return
if not CONFIG.accepts_bootstrap(self.headers.get('X-Setup-Token', '')):
self.send_error_json(HTTPStatus.FORBIDDEN, 'Ungültiger Einrichtungscode oder Einrichtung abgeschlossen')
return
if mutation:
if self.headers.get_content_type() != 'application/json' or self.headers.get('Sec-Fetch-Site') in {'cross-site', 'same-site'}:
self.send_error_json(HTTPStatus.FORBIDDEN, 'Einrichtung erfordert JSON vom selben Origin')
return
origin = self.headers.get('Origin')
if origin:
try:
if web_security.origin(origin) != web_security.origin('https://' + self.headers.get('Host', '')):
raise ValueError()
except ValueError:
self.send_error_json(HTTPStatus.FORBIDDEN, 'Ungültiger Einrichtungs-Origin')
return
try:
if not mutation and path == '/api/bootstrap/settings':
value = CONFIG.public()
value['services'] = read_json(str(CONFIG.root / 'services-status.json'), {'state': 'waiting'})
self.send_json(value)
elif not mutation and path == '/api/bootstrap/groups':
if not os.path.exists('/run/adfs-domain-ready'):
raise ValueError('Domänenbeitritt ist noch nicht abgeschlossen')
self.send_json({'groups': self.domain_groups()})
elif mutation and path == '/api/bootstrap/domain':
body = self.read_json_body(262144)
changes = body.get('values', {})
if not isinstance(changes, dict) or any(key not in configuration.FIELDS or configuration.FIELDS[key]['section'] not in {'domain', 'network', 'tls'} for key in changes):
raise ValueError('Nur Domänen-, Server- und HTTPS-Einstellungen sind hier zulässig')
if not all(changes.get(key) or snap['values'].get(key) for key in ('REALM', 'WORKGROUP', 'DOMAIN', 'JOIN_USER', 'JOIN_PASSWORD')):
raise ValueError('Domäne und Zugangsdaten für den Beitritt sind erforderlich')
CONFIG.save(changes, body.get('revision'), bootstrap=True)
CONFIG.phase('joining')
self.reload_configuration()
self.send_json(CONFIG.public(), HTTPStatus.ACCEPTED)
elif mutation and path == '/api/bootstrap/finish':
if not os.path.exists('/run/adfs-domain-ready'):
raise ValueError('Domänenbeitritt ist noch nicht abgeschlossen')
body = self.read_json_body()
changes = body.get('values', {})
if not isinstance(changes, dict) or set(changes) != {'DOMAIN_USERS_SID', 'DOMAIN_ADMINS_SID', 'FSLOGIX_GROUP_SID'}:
raise ValueError('Benutzer-, Administratoren- und FSLogix-Gruppe auswählen')
groups = {row['sid'] for row in self.domain_groups()}
if any(sid not in groups for sid in changes.values()):
raise ValueError('Ausgewählte Gruppe ist nicht im aktuellen AD vorhanden')
identity = authenticate_user(body.get('username', snap['values']['JOIN_USER']), body.get('password', snap['values']['JOIN_PASSWORD']))
administrator = current_identity(identity['sid'], admin_sid=changes['DOMAIN_ADMINS_SID']) if identity else None
if not administrator or administrator['role'] != 'domain-admin':
raise ValueError('Das Einrichtungskonto muss zur ausgewählten Administratorengruppe gehören')
result = CONFIG.save(changes, body.get('revision'), bootstrap=True)
CONFIG.finish(result['revision'])
self.send_json({'configured': True, 'hostname': CONFIG.snapshot()['values']['WEB_HOSTNAME']})
elif mutation and path == '/api/bootstrap/import':
body = self.read_json_body(262144)
if not CONFIG.import_legacy(configuration.parse_legacy(body.get('text', ''))):
raise ValueError('Frühere Konfiguration ist unvollständig')
self.reload_configuration()
self.send_json({'configured': True})
else:
self.send_error_json(HTTPStatus.NOT_FOUND, 'Nicht gefunden')
except configuration.Conflict as exc:
self.send_error_json(HTTPStatus.CONFLICT, str(exc))
except (ValueError, TypeError, OSError, RuntimeError) as exc:
self.send_error_json(HTTPStatus.BAD_REQUEST, str(exc))
def settings_write(self, path, user):
if CONFIG is None:
self.send_error_json(HTTPStatus.SERVICE_UNAVAILABLE, 'Einstellungen nicht verfügbar')
return
try:
body = self.read_json_body(262144)
with ACTION_LAUNCH_LOCK:
if lock_is_held(BACKUP_LOCK_FILE):
raise configuration.Conflict('Während einer Sicherung können Einstellungen und Schlüssel nicht geändert werden')
if path == '/api/settings':
values = body.get('values', {})
if isinstance(values, dict) and any(key in values for key in ('DOMAIN_USERS_SID', 'DOMAIN_ADMINS_SID', 'FSLOGIX_GROUP_SID')):
groups = {row['sid'] for row in self.domain_groups()}
if any(values[key] not in groups for key in values if key in ('DOMAIN_USERS_SID', 'DOMAIN_ADMINS_SID', 'FSLOGIX_GROUP_SID')):
raise ValueError('Ausgewählte Gruppe ist nicht im aktuellen AD vorhanden')
if 'DOMAIN_ADMINS_SID' in values:
identity = current_identity(user['sid'], admin_sid=values['DOMAIN_ADMINS_SID'])
if not identity or identity['role'] != 'domain-admin':
raise ValueError('Sie müssen Mitglied der ausgewählten Administratorengruppe sein')
result = CONFIG.save(values, body.get('revision'))
if 'DOMAIN_ADMINS_SID' in values:
APP.tokens.sessions.recheck_all()
result['restartRequired'] = any(configuration.FIELDS[key]['section'] != 'backup' for key in values)
elif path == '/api/settings/backup-key/generate':
result = CONFIG.generate_key(str(user['jti']))
elif path == '/api/settings/backup-key/activate':
result = CONFIG.activate_key(str(user['jti']), body.get('nonce'), body.get('writtenDown'), body.get('acknowledgeOldBackups'))
else:
self.send_error_json(HTTPStatus.NOT_FOUND, 'Nicht gefunden')
return
self.reload_configuration()
self.send_json(result)
except configuration.Conflict as exc:
self.send_error_json(HTTPStatus.CONFLICT, str(exc))
except (ValueError, TypeError, OSError) as exc:
self.send_error_json(HTTPStatus.BAD_REQUEST, str(exc))
def security_headers(self, cache_control: str = "no-store", pdf_viewer: bool = False) -> None: def security_headers(self, cache_control: str = "no-store", pdf_viewer: bool = False) -> None:
self.send_header("Strict-Transport-Security", "max-age=31536000; includeSubDomains") self.send_header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
self.send_header( self.send_header(
@@ -1019,6 +1149,13 @@ class Handler(BaseHTTPRequestHandler):
def do_POST(self) -> None: # pylint: disable=invalid-name def do_POST(self) -> None: # pylint: disable=invalid-name
parsed = urllib.parse.urlparse(self.path) parsed = urllib.parse.urlparse(self.path)
self.reload_configuration()
if parsed.path.startswith('/api/bootstrap/'):
self.bootstrap(parsed.path, mutation=True)
return
if CONFIG is not None and CONFIG.snapshot()['phase'] != 'configured':
self.send_error_json(HTTPStatus.SERVICE_UNAVAILABLE, 'Ersteinrichtung erforderlich')
return
if not self.check_write_origin(): if not self.check_write_origin():
return return
if parsed.path == "/api/login": if parsed.path == "/api/login":
@@ -1076,6 +1213,9 @@ class Handler(BaseHTTPRequestHandler):
if administrator is None: if administrator is None:
return return
parsed = parsed._replace(path=parsed.path[len("/admin"):]) parsed = parsed._replace(path=parsed.path[len("/admin"):])
if parsed.path == '/api/settings' or parsed.path.startswith('/api/settings/'):
self.settings_write(parsed.path, administrator)
return
if parsed.path == "/api/documents/control": if parsed.path == "/api/documents/control":
conn = documents.connect() conn = documents.connect()
try: try:
@@ -1186,10 +1326,23 @@ class Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None: # pylint: disable=invalid-name,too-many-return-statements def do_GET(self) -> None: # pylint: disable=invalid-name,too-many-return-statements
parsed = urllib.parse.urlparse(self.path) parsed = urllib.parse.urlparse(self.path)
self.reload_configuration()
path = parsed.path path = parsed.path
if path.startswith('/api/bootstrap/'):
self.bootstrap(path)
return
if path == "/healthz": if path == "/healthz":
if CONFIG is not None and CONFIG.snapshot()['phase'] == 'configured' and not os.path.exists('/run/adfs-services-ready'):
self.send_json({'status': 'starting', 'message': 'Dateidienste werden gestartet'}, HTTPStatus.SERVICE_UNAVAILABLE)
return
self.send_json({"status": "ok"}) self.send_json({"status": "ok"})
return return
if CONFIG is not None and CONFIG.snapshot()['phase'] != 'configured' and not path.startswith('/assets/'):
if path.startswith('/api/') or path.startswith('/admin/api/'):
self.send_error_json(HTTPStatus.SERVICE_UNAVAILABLE, 'Ersteinrichtung erforderlich')
else:
self.serve_static('/setup')
return
if path.startswith("/api/"): if path.startswith("/api/"):
user = self.require_user() user = self.require_user()
if user is None: if user is None:
@@ -1220,6 +1373,12 @@ class Handler(BaseHTTPRequestHandler):
conn.close() conn.close()
elif path == "/api/overview": elif path == "/api/overview":
self.send_json(APP.overview()) self.send_json(APP.overview())
elif path == '/api/settings':
if CONFIG is None:
raise ValueError('Einstellungen nicht verfügbar')
self.send_json(CONFIG.public(params.get('section', [''])[0] or None))
elif path == '/api/settings/groups':
self.send_json({'groups': self.domain_groups()})
elif path == "/api/access": elif path == "/api/access":
conn = directory.open_db() conn = directory.open_db()
try: try:
@@ -1383,6 +1542,9 @@ class Handler(BaseHTTPRequestHandler):
self.wfile.write(body) self.wfile.write(body)
return return
files = { files = {
'/setup': ('setup.html', 'text/html; charset=utf-8'),
'/assets/setup.js': ('setup.js', 'text/javascript; charset=utf-8'),
'/assets/settings.js': ('settings.js', 'text/javascript; charset=utf-8'),
"/assets/portal.js": ("portal.js", "text/javascript; charset=utf-8"), "/assets/portal.js": ("portal.js", "text/javascript; charset=utf-8"),
"/assets/pdf-viewer.js": ("pdf-viewer.js", "text/javascript; charset=utf-8"), "/assets/pdf-viewer.js": ("pdf-viewer.js", "text/javascript; charset=utf-8"),
"/assets/pdf-viewer.css": ("pdf-viewer.css", "text/css; charset=utf-8"), "/assets/pdf-viewer.css": ("pdf-viewer.css", "text/css; charset=utf-8"),
@@ -1473,7 +1635,9 @@ def serve_https() -> None:
def main() -> int: def main() -> int:
global APP global APP, CONFIG
CONFIG = configuration.Store()
os.environ.update(CONFIG.environment())
if not os.path.isfile(TLS_CERT_FILE) or not os.path.isfile(TLS_KEY_FILE): if not os.path.isfile(TLS_CERT_FILE) or not os.path.isfile(TLS_KEY_FILE):
raise RuntimeError("TLS certificate or key is missing") raise RuntimeError("TLS certificate or key is missing")
APP = App() APP = App()
+9 -1
View File
@@ -46,6 +46,7 @@ HTTP_OPENER = urllib.request.build_opener(
urllib.request.ProxyHandler({}), urllib.request.ProxyHandler({}),
urllib.request.HTTPSHandler(context=TLS_CONTEXT), urllib.request.HTTPSHandler(context=TLS_CONTEXT),
) )
TOKEN_CSRF = {}
@dataclass @dataclass
@@ -97,12 +98,19 @@ def http(
headers["Content-Type"] = "application/json" headers["Content-Type"] = "application/json"
if token: if token:
headers["Authorization"] = f"Bearer {token}" headers["Authorization"] = f"Bearer {token}"
if method == 'POST':
headers['Origin'] = BASE_URL
headers['X-CSRF-Token'] = 'login' if path == '/api/login' else TOKEN_CSRF.get(token, '')
request = urllib.request.Request( request = urllib.request.Request(
f"{BASE_URL}{path}", data=body, headers=headers, method=method f"{BASE_URL}{path}", data=body, headers=headers, method=method
) )
try: try:
with HTTP_OPENER.open(request, timeout=30) as response: with HTTP_OPENER.open(request, timeout=30) as response:
return Response(response.status, response.headers, response.read()) result = Response(response.status, response.headers, response.read())
if path == '/api/login' and result.status == 200:
session = result.json()
TOKEN_CSRF[session['token']] = session['csrfToken']
return result
except urllib.error.HTTPError as exc: except urllib.error.HTTPError as exc:
return Response(exc.code, exc.headers, exc.read()) return Response(exc.code, exc.headers, exc.read())
+4 -9
View File
@@ -3,18 +3,13 @@ services:
build: build:
context: . context: .
container_name: ad-samba-file-server container_name: ad-samba-file-server
hostname: ${SAMBA_HOSTNAME:-adsambafsrv} hostname: adsambafsrv
restart: unless-stopped restart: unless-stopped
env_file:
- .env
environment:
TZ: Etc/UTC
NETBIOS_NAME: ${NETBIOS_NAME:-ADSAMBAFSRV}
ports: ports:
- "445:445" - "445:445"
- "139:139" - "139:139"
- "${ACME_HTTP_PORT:-80}:80" - "80:80"
- "${WEB_HTTPS_PORT:-443}:${WEB_BIND_PORT:-8443}" - "443:8443"
volumes: volumes:
- private_data:/data/private - private_data:/data/private
- fslogix_data:/data/fslogix - fslogix_data:/data/fslogix
@@ -22,7 +17,7 @@ services:
- state_data:/state - state_data:/state
- samba_lib_data:/var/lib/samba - samba_lib_data:/var/lib/samba
healthcheck: healthcheck:
test: ["CMD-SHELL", "wbinfo -t >/dev/null 2>&1 && testparm -s >/dev/null 2>&1"] test: ["CMD", "python3", "/app/healthcheck.py"]
interval: 30s interval: 30s
timeout: 10s timeout: 10s
retries: 5 retries: 5
+5 -162
View File
@@ -1,166 +1,9 @@
#!/usr/bin/env bash #!/usr/bin/env bash
set -euo pipefail set -euo pipefail
cd "$(dirname "$0")"
log() { printf '[redeploy] Pulling latest changes\n'
printf '[redeploy] %s\n' "$*"
}
read_env_value() {
local key="$1"
local line=""
if [[ ! -f .env ]]; then
return 1
fi
while IFS= read -r line || [[ -n "$line" ]]; do
if [[ "$line" == "${key}="* ]]; then
printf '%s\n' "${line#*=}"
return 0
fi
done < .env
return 1
}
upsert_env_value() {
local key="$1"
local value="$2"
local temp_file=""
local line=""
local found=0
temp_file="$(mktemp)"
while IFS= read -r line || [[ -n "$line" ]]; do
if [[ "$line" == "${key}="* ]]; then
printf '%s=%s\n' "$key" "$value" >> "$temp_file"
found=1
else
printf '%s\n' "$line" >> "$temp_file"
fi
done < .env
if [[ "$found" -eq 0 ]]; then
printf '%s=%s\n' "$key" "$value" >> "$temp_file"
fi
chmod --reference=.env "$temp_file" 2>/dev/null || chmod 600 "$temp_file"
mv "$temp_file" .env
}
parse_route_source_ip() {
local route="$1"
local previous=""
local token
for token in $route; do
if [[ "$previous" == "src" ]]; then
printf '%s\n' "$token"
return 0
fi
previous="$token"
done
return 1
}
detect_ad_dns_ip() {
local lookup_name="$1"
local target_ip=""
local route=""
if ! command -v ip >/dev/null 2>&1; then
return 1
fi
if [[ -n "$lookup_name" ]] && command -v getent >/dev/null 2>&1; then
while read -r target_ip _; do
if [[ ! "$target_ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
continue
fi
route="$(ip -o -4 route get "$target_ip" 2>/dev/null || true)"
parse_route_source_ip "$route" && return 0
done < <(getent ahostsv4 "$lookup_name" 2>/dev/null)
fi
route="$(ip -o -4 route get 1.1.1.1 2>/dev/null || true)"
parse_route_source_ip "$route"
}
refresh_ad_dns_env() {
local auto=""
local domain=""
local detected_ip=""
local samba_hostname=""
local netbios_name=""
local host_part=""
if [[ ! -f .env ]]; then
log '.env missing; skipping AD DNS IP refresh'
return
fi
auto="$(read_env_value AD_DNS_IP_AUTO || true)"
case "${auto,,}" in
0|false|no)
log 'AD_DNS_IP_AUTO disabled; keeping configured AD_DNS_IP'
return
;;
esac
domain="$(read_env_value DOMAIN || true)"
if [[ -z "$domain" ]]; then
log 'DOMAIN missing in .env; skipping AD DNS IP refresh'
return
fi
detected_ip="$(detect_ad_dns_ip "$domain" || true)"
if [[ -z "$detected_ip" ]]; then
log 'Unable to detect host LAN IP; keeping configured AD_DNS_IP'
return
fi
upsert_env_value AD_DNS_IP "$detected_ip"
if ! read_env_value AD_DNS_NAME >/dev/null; then
samba_hostname="$(read_env_value SAMBA_HOSTNAME || true)"
netbios_name="$(read_env_value NETBIOS_NAME || true)"
host_part="${samba_hostname:-${netbios_name,,}}"
host_part="${host_part:-adsambafsrv}"
upsert_env_value AD_DNS_NAME "${host_part}.${domain}"
fi
upsert_env_value AD_DNS_IP_AUTO "1"
log "Updated AD_DNS_IP=${detected_ip}"
}
if [[ ! -d .git ]]; then
printf '[redeploy] ERROR: run this script from the repository root.\n' >&2
exit 1
fi
refresh_ad_dns_env
OLD_COMPOSE_FILE="$(mktemp)"
cleanup() {
if [[ -f "$OLD_COMPOSE_FILE" ]]; then
rm -f "$OLD_COMPOSE_FILE"
fi
}
trap cleanup EXIT
log 'Capturing current compose configuration'
docker compose config > "$OLD_COMPOSE_FILE"
log 'Pulling latest git changes'
git pull git pull
printf '[redeploy] Building while the current service remains running\n'
log 'Building updated images while current stack is running'
docker compose build --no-cache docker compose build --no-cache
./setup --skip-build
log 'Stopping previous stack using captured configuration' printf '[redeploy] Complete; configuration and data volumes retained.\n'
docker compose --project-directory "$PWD" -f "$OLD_COMPOSE_FILE" down
log 'Starting stack'
docker compose up -d
log 'Redeploy complete'
+155 -68
View File
@@ -24,11 +24,15 @@ else
fi fi
run_e2e=${DEV_RUN_E2E:-0} run_e2e=${DEV_RUN_E2E:-0}
onboarding=0
[[ $# -le 1 ]] || die 'use either --e2e or --onboarding'
case "${1:-}" in case "${1:-}" in
--e2e) run_e2e=1 ;; --e2e) run_e2e=1 ;;
--onboarding) onboarding=1 ;;
'') ;; '') ;;
*) die "unknown argument: $1" ;; *) die "unknown argument: $1" ;;
esac esac
[[ $onboarding != 1 || $run_e2e != 1 ]] || die '--onboarding cannot be combined with DEV_RUN_E2E=1'
dev_realm=${DEV_REALM:-DEV.TEST} dev_realm=${DEV_REALM:-DEV.TEST}
dev_workgroup=${DEV_WORKGROUP:-DEV} dev_workgroup=${DEV_WORKGROUP:-DEV}
@@ -46,6 +50,7 @@ dev_backup_auto_enabled=${DEV_BACKUP_AUTO_ENABLED:-true}
dev_ca_password=${DEV_CA_PASSWORD:-PreviewCa123!} dev_ca_password=${DEV_CA_PASSWORD:-PreviewCa123!}
dev_ca_provisioner=${DEV_CA_PROVISIONER:-preview} dev_ca_provisioner=${DEV_CA_PROVISIONER:-preview}
dev_https_port=${DEV_HTTPS_PORT:-8443} dev_https_port=${DEV_HTTPS_PORT:-8443}
dev_http_port=${DEV_HTTP_PORT:-8080}
dev_activity_interval=${DEV_ACTIVITY_INTERVAL_SECONDS:-4} dev_activity_interval=${DEV_ACTIVITY_INTERVAL_SECONDS:-4}
dev_backup_interval=${DEV_BACKUP_INTERVAL_SECONDS:-120} dev_backup_interval=${DEV_BACKUP_INTERVAL_SECONDS:-120}
@@ -90,6 +95,7 @@ volumes=(
network_created=0 network_created=0
watchdog_pid= watchdog_pid=
log_pid= log_pid=
server_wait_pid=
backup_driver_pid= backup_driver_pid=
ca_root_file= ca_root_file=
@@ -133,6 +139,10 @@ cleanup() {
kill "$log_pid" >/dev/null 2>&1 || true kill "$log_pid" >/dev/null 2>&1 || true
wait "$log_pid" 2>/dev/null || true wait "$log_pid" 2>/dev/null || true
fi fi
if [[ -n ${server_wait_pid:-} ]]; then
kill "$server_wait_pid" >/dev/null 2>&1 || true
wait "$server_wait_pid" 2>/dev/null || true
fi
if [[ -n ${watchdog_pid:-} ]]; then if [[ -n ${watchdog_pid:-} ]]; then
kill "$watchdog_pid" >/dev/null 2>&1 || true kill "$watchdog_pid" >/dev/null 2>&1 || true
wait "$watchdog_pid" 2>/dev/null || true wait "$watchdog_pid" 2>/dev/null || true
@@ -179,6 +189,22 @@ wait_for_exec() {
return 1 return 1
} }
follow_server() {
local file_status
"$engine" logs -f "$files_container" &
log_pid=$!
# Bash can handle termination immediately while waiting on a background job.
"$engine" wait "$files_container" >/dev/null 2>&1 &
server_wait_pid=$!
wait "$server_wait_pid" || die 'unable to wait for the file server'
server_wait_pid=
file_status=$("$engine" inspect -f '{{.State.ExitCode}}' "$files_container" 2>/dev/null || printf '1')
case "$file_status" in
''|*[!0-9]*) exit 1 ;;
*) exit "$file_status" ;;
esac
}
create_network() { create_network() {
local attempt local attempt
local second local second
@@ -281,68 +307,104 @@ if ! wait_for_exec "$dc_container" 150 test -f /run/preview-ready; then
fi fi
domain_sid=$("$engine" exec "$dc_container" cat /run/domain-sid) domain_sid=$("$engine" exec "$dc_container" cat /run/domain-sid)
printf 'seeding preview files\n' if [[ $onboarding == 1 ]]; then
"$engine" run --rm \ printf 'starting fresh file server for HTTP-to-HTTPS onboarding\n'
--network "$network_name" \ "$engine" run -d \
-e "DEV_SEED_MB=${DEV_SEED_MB:-8}" \ --name "$files_container" \
-v "$private_volume:/data/private" \ --hostname files \
-v "$fslogix_volume:/data/fslogix" \ --network "$network_name" \
-v "$groups_volume:/data/groups" \ --ip "$files_ip" \
-v "$state_volume:/state" \ --dns "$dc_ip" \
--entrypoint /usr/local/bin/preview-seed-files \ --dns-search "$dev_dns_domain" \
"$ad_image" -p "127.0.0.1:${dev_http_port}:80" \
-p "127.0.0.1:${dev_https_port}:8443" \
-v "$private_volume:/data/private" \
-v "$fslogix_volume:/data/fslogix" \
-v "$groups_volume:/data/groups" \
-v "$state_volume:/state" \
-v "$samba_volume:/var/lib/samba" \
"$server_image" python3 -c '
import json, os, sys
sys.path.insert(0, "/app")
import configuration
# Only the external port mapping is supplied by the launcher. Domain, TLS,
# credentials, groups and backups remain unconfigured until entered in the UI.
port = int(sys.argv[1])
if not 1 <= port <= 65535:
raise ValueError("Invalid development HTTPS port")
store = configuration.Store()
values = store.snapshot()["values"]
values["WEB_HTTPS_PORT"] = str(port)
with store.connect() as conn:
conn.execute("UPDATE configuration SET settings=? WHERE id=1", (json.dumps(values),))
os.execv(sys.executable, [sys.executable, "/app/entrypoint.py"])
' "$dev_https_port" >/dev/null
else
printf 'seeding preview files\n'
"$engine" run --rm \
--network "$network_name" \
-e "DEV_SEED_MB=${DEV_SEED_MB:-8}" \
-v "$private_volume:/data/private" \
-v "$fslogix_volume:/data/fslogix" \
-v "$groups_volume:/data/groups" \
-v "$state_volume:/state" \
--entrypoint /usr/local/bin/preview-seed-files \
"$ad_image"
printf 'starting actual file server and HTTPS web UI\n' printf 'starting actual file server and HTTPS web UI\n'
"$engine" run -d \ "$engine" run -d \
--name "$files_container" \ --name "$files_container" \
--hostname files \ --hostname files \
--network "$network_name" \ --network "$network_name" \
--ip "$files_ip" \ --ip "$files_ip" \
--dns "$dc_ip" \ --dns "$dc_ip" \
--dns-search "$dev_dns_domain" \ --dns-search "$dev_dns_domain" \
-p "127.0.0.1:${dev_https_port}:8443" \ -p "127.0.0.1:${dev_https_port}:8443" \
-e "REALM=${dev_realm}" \ -e "REALM=${dev_realm}" \
-e "WORKGROUP=${dev_workgroup}" \ -e "WORKGROUP=${dev_workgroup}" \
-e "DOMAIN=dc.${dev_dns_domain}" \ -e "DOMAIN=dc.${dev_dns_domain}" \
-e "LDAP_URI=ldap://dc.${dev_dns_domain}" \ -e "LDAP_URI=ldap://dc.${dev_dns_domain}" \
-e "LDAP_BASE_DN=${dev_base_dn}" \ -e "LDAP_BASE_DN=${dev_base_dn}" \
-e "JOIN_USER=Administrator" \ -e "JOIN_USER=Administrator" \
-e "JOIN_PASSWORD=${dev_dc_password}" \ -e "JOIN_PASSWORD=${dev_dc_password}" \
-e "DOMAIN_USERS_SID=${domain_sid}-513" \ -e "DOMAIN_USERS_SID=${domain_sid}-513" \
-e "DOMAIN_ADMINS_SID=${domain_sid}-512" \ -e "DOMAIN_ADMINS_SID=${domain_sid}-512" \
-e "FSLOGIX_GROUP_SID=${domain_sid}-513" \ -e "FSLOGIX_GROUP_SID=${domain_sid}-513" \
-e "SAMBA_HOSTNAME=files" \ -e "SAMBA_HOSTNAME=files" \
-e "NETBIOS_NAME=FILES" \ -e "NETBIOS_NAME=FILES" \
-e "AD_DNS_NAME=files.${dev_dns_domain}" \ -e "AD_DNS_NAME=files.${dev_dns_domain}" \
-e "WEB_ENABLED=true" \ -e "WEB_ENABLED=true" \
-e "WEB_HOSTNAME=${dev_web_hostname}" \ -e "WEB_HOSTNAME=${dev_web_hostname}" \
-e "WEB_BIND_PORT=8443" \ -e "WEB_BIND_PORT=8443" \
-e "WEB_HTTPS_PORT=${dev_https_port}" \ -e "WEB_HTTPS_PORT=${dev_https_port}" \
-e "WEB_JWT_SECRET=preview-only-jwt-secret-with-at-least-32-bytes" \ -e "WEB_LOGIN_ATTEMPTS_PER_5_MIN=100" \
-e "WEB_TLS_MODE=acme" \ -e "WEB_LOGIN_ACCOUNT_ATTEMPTS_PER_5_MIN=100" \
-e "ACME_CA_SERVER=https://ca.${dev_dns_domain}:9000/acme/acme/directory" \ -e "WEB_JWT_SECRET=preview-only-jwt-secret-with-at-least-32-bytes" \
-e "ACME_CA_CERTIFICATES=/state/tls/acme-ca-certificates.pem" \ -e "WEB_TLS_MODE=acme" \
-e "ACME_CA_CERTIFICATES_URL=https://ca.${dev_dns_domain}:9000/roots.pem" \ -e "ACME_CA_SERVER=https://ca.${dev_dns_domain}:9000/acme/acme/directory" \
-e "ACME_CA_CERTIFICATES_INSECURE_DOWNLOAD=true" \ -e "ACME_CA_CERTIFICATES=/state/tls/acme-ca-certificates.pem" \
-e "ACME_HTTP_LISTEN=:80" \ -e "ACME_CA_CERTIFICATES_URL=https://ca.${dev_dns_domain}:9000/roots.pem" \
-e "WEB_USAGE_SCAN_INTERVAL_SECONDS=60" \ -e "ACME_CA_CERTIFICATES_INSECURE_DOWNLOAD=true" \
-e "WEB_DIRECTORY_CACHE_SECONDS=30" \ -e "ACME_HTTP_LISTEN=:80" \
-e "AUDIT_POLL_SECONDS=0.25" \ -e "WEB_USAGE_SCAN_INTERVAL_SECONDS=60" \
-e "BACKUP_DESTINATION=rsync://${dev_backup_user}:${dev_backup_password}@backup.${dev_dns_domain}/backups/fileserver" \ -e "WEB_DIRECTORY_CACHE_SECONDS=30" \
-e "BACKUP_ARCHIVE_PASSWORD=${dev_archive_password}" \ -e "AUDIT_POLL_SECONDS=0.25" \
-e "BACKUP_AUTO_ENABLED=${dev_backup_auto_enabled}" \ -e "BACKUP_DESTINATION=rsync://${dev_backup_user}:${dev_backup_password}@backup.${dev_dns_domain}/backups/fileserver" \
-e "BACKUP_PROGRESS=never" \ -e "BACKUP_ARCHIVE_PASSWORD=${dev_archive_password}" \
-e "BACKUP_PROGRESS_INTERVAL_SECONDS=1" \ -e "BACKUP_AUTO_ENABLED=${dev_backup_auto_enabled}" \
-e "BACKUP_RETENTION_DAILY=3" \ -e "BACKUP_PROGRESS=never" \
-e "BACKUP_RETENTION_WEEKLY=2" \ -e "BACKUP_PROGRESS_INTERVAL_SECONDS=1" \
-e "BACKUP_RETENTION_MONTHLY=1" \ -e "BACKUP_RETENTION_DAILY=3" \
-e "BACKUP_RETENTION_YEARLY=1" \ -e "BACKUP_RETENTION_WEEKLY=2" \
-v "$private_volume:/data/private" \ -e "BACKUP_RETENTION_MONTHLY=1" \
-v "$fslogix_volume:/data/fslogix" \ -e "BACKUP_RETENTION_YEARLY=1" \
-v "$groups_volume:/data/groups" \ -v "$private_volume:/data/private" \
-v "$state_volume:/state" \ -v "$fslogix_volume:/data/fslogix" \
-v "$samba_volume:/var/lib/samba" \ -v "$groups_volume:/data/groups" \
"$server_image" >/dev/null -v "$state_volume:/state" \
-v "$samba_volume:/var/lib/samba" \
"$server_image" >/dev/null
fi
if ! wait_for_exec "$files_container" 240 python3 -c \ if ! wait_for_exec "$files_container" 240 python3 -c \
'import ssl,urllib.request; print(urllib.request.urlopen("https://127.0.0.1:8443/healthz", context=ssl._create_unverified_context(), timeout=3).status)'; then 'import ssl,urllib.request; print(urllib.request.urlopen("https://127.0.0.1:8443/healthz", context=ssl._create_unverified_context(), timeout=3).status)'; then
@@ -350,6 +412,37 @@ if ! wait_for_exec "$files_container" 240 python3 -c \
die 'file server web UI did not become healthy' die 'file server web UI did not become healthy'
fi fi
if [[ $onboarding == 1 ]]; then
if ! wait_for_exec "$files_container" 30 python3 -c \
'import urllib.request; assert urllib.request.urlopen("http://127.0.0.1/api/https/status", timeout=3).status == 200'; then
show_logs
die 'HTTP HTTPS-setup UI did not become ready'
fi
printf '\nOnboarding preview ready (fresh configuration; no automatic domain join)\n'
printf ' Start here: http://%s:%s/\n' "$dev_web_hostname" "$dev_http_port"
printf ' HTTPS afterwards: https://%s:%s/\n' "$dev_web_hostname" "$dev_https_port"
printf ' HTTPS setup code: %s\n' "$("$engine" exec "$files_container" cat /state/https-setup-code)"
printf ' Setup code: %s\n' "$("$engine" exec "$files_container" cat /state/setup-code)"
printf '\nStep 1 — HTTP: configure ACME and upload the disposable CA root\n'
printf ' HTTPS hostname: %s\n' "$dev_web_hostname"
printf ' ACME directory: https://ca.%s:9000/acme/acme/directory\n' "$dev_dns_domain"
printf ' CA root to upload: %s\n' "$ca_root_file"
printf '\nStep 2 — HTTPS: join the disposable domain and select groups\n'
printf ' Realm / NetBIOS: %s / %s\n' "$dev_realm" "$dev_workgroup"
printf ' Domain controller: dc.%s\n' "$dev_dns_domain"
printf ' Join account: Administrator / %s\n' "$dev_dc_password"
printf ' Server / NetBIOS: files / FILES\n'
printf ' Advanced LDAP URI: ldap://dc.%s (development DC only)\n' "$dev_dns_domain"
printf ' User / Admin group: Domain Users / Domain Admins\n'
printf ' Initial admin: %s\\%s / %s\n' "$dev_workgroup" "$dev_admin_user" "$dev_admin_password"
printf '\nOptional backup destination — configure under /admin/settings after setup\n'
printf ' Destination: rsync://%s:%s@backup.%s/backups/fileserver\n' "$dev_backup_user" "$dev_backup_password" "$dev_dns_domain"
printf '\nTrust the disposable CA root temporarily before continuing over HTTPS.\n'
printf 'Files, permissions and backups start empty; no SMB traffic or backup driver is started.\n'
printf 'Press Ctrl-C to remove this run, including its configuration and test data.\n\n'
follow_server
fi
if [[ $run_e2e == 1 ]]; then if [[ $run_e2e == 1 ]]; then
printf 'validating one-time untrusted CA root retrieval across a restart\n' printf 'validating one-time untrusted CA root retrieval across a restart\n'
initial_ca_bundle_stat=$("$engine" exec "$files_container" stat -c '%i:%s:%Y' /state/tls/acme-ca-certificates.pem) initial_ca_bundle_stat=$("$engine" exec "$files_container" stat -c '%i:%s:%Y' /state/tls/acme-ca-certificates.pem)
@@ -437,10 +530,4 @@ printf ' CA root: %s\n' "$ca_root_file"
printf '\nThe CA is disposable, so import the displayed root only as temporary trust.\n' printf '\nThe CA is disposable, so import the displayed root only as temporary trust.\n'
printf 'SMB activity and backups repeat in the background. Press Ctrl-C to remove everything.\n\n' printf 'SMB activity and backups repeat in the background. Press Ctrl-C to remove everything.\n\n'
"$engine" logs -f "$files_container" & follow_server
log_pid=$!
file_status=$("$engine" wait "$files_container" 2>/dev/null || printf '1')
case "$file_status" in
''|*[!0-9]*) exit 1 ;;
*) exit "$file_status" ;;
esac
+17 -456
View File
@@ -1,460 +1,21 @@
#!/usr/bin/env bash #!/usr/bin/env bash
set -euo pipefail set -euo pipefail
cd "$(dirname "$0")"
ENV_FILE=".env" case "${1:-}" in
SERVICE_ACCOUNT_NAME="FileShare_ServiceAccount" '') docker compose build ;;
--skip-build) ;;
BOOTSTRAP_ENV_FILE="" *) printf 'Usage: ./setup [--skip-build]\n' >&2; exit 1 ;;
ORIGINAL_ENV_BACKUP="" esac
BOOTSTRAP_ENV_WRITTEN=0 # Import once into the existing state volume. Never source/evaluate legacy .env.
FINAL_ENV_WRITTEN=0 # The import container does not join AD, reconcile permissions, or touch files.
ENV_PREEXISTED=0 previous_container="$(docker compose ps --all -q samba)"
if [[ -n "$previous_container" ]]; then
cleanup() { # Resolved values preserve Compose interpolation and literal password bytes.
if [[ -n "$BOOTSTRAP_ENV_FILE" && -f "$BOOTSTRAP_ENV_FILE" ]]; then docker inspect "$previous_container" --format '{{json .Config.Env}}' |
rm -f "$BOOTSTRAP_ENV_FILE" docker compose run --rm --no-deps -T samba python3 /app/configuration.py import-runtime
fi elif [[ -f .env ]]; then
docker compose run --rm --no-deps -T samba python3 /app/configuration.py import-legacy < .env
if [[ "$BOOTSTRAP_ENV_WRITTEN" -eq 1 && "$FINAL_ENV_WRITTEN" -eq 0 ]]; then
if [[ "$ENV_PREEXISTED" -eq 1 && -n "$ORIGINAL_ENV_BACKUP" && -f "$ORIGINAL_ENV_BACKUP" ]]; then
cp "$ORIGINAL_ENV_BACKUP" "$ENV_FILE"
chmod 600 "$ENV_FILE"
printf "Restored original %s after setup failure.\n" "$ENV_FILE" >&2
else
rm -f "$ENV_FILE"
printf "Removed temporary %s after setup failure.\n" "$ENV_FILE" >&2
fi
fi
if [[ -n "$ORIGINAL_ENV_BACKUP" && -f "$ORIGINAL_ENV_BACKUP" ]]; then
rm -f "$ORIGINAL_ENV_BACKUP"
fi
}
trap cleanup EXIT
sanitize_netbios_name() {
local raw_name="$1"
local upper_name="${raw_name^^}"
local cleaned_name
cleaned_name="$(printf '%s' "$upper_name" | tr -cd 'A-Z0-9')"
if [[ -z "$cleaned_name" ]]; then
cleaned_name="ADSAMBAFSRV"
fi
printf '%s' "${cleaned_name:0:15}"
}
sanitize_sam_account_name() {
local raw_name="$1"
local cleaned_name
cleaned_name="$(printf '%s' "$raw_name" | tr -cd 'A-Za-z0-9._-')"
if [[ "$cleaned_name" == "FileShare_ServiceAccount" ]]; then
printf '%s' "FileShare_ServiceAcc"
return
fi
if [[ -z "$cleaned_name" ]]; then
cleaned_name="FileShareSvc"
fi
printf '%s' "${cleaned_name:0:20}"
}
parse_route_source_ip() {
local route="$1"
local previous=""
local token
for token in $route; do
if [[ "$previous" == "src" ]]; then
printf '%s\n' "$token"
return 0
fi
previous="$token"
done
return 1
}
detect_ad_dns_ip() {
local lookup_name="$1"
local target_ip=""
local route=""
if ! command -v ip >/dev/null 2>&1; then
return 1
fi
if [[ -n "$lookup_name" ]] && command -v getent >/dev/null 2>&1; then
while read -r target_ip _; do
if [[ ! "$target_ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
continue
fi
route="$(ip -o -4 route get "$target_ip" 2>/dev/null || true)"
parse_route_source_ip "$route" && return 0
done < <(getent ahostsv4 "$lookup_name" 2>/dev/null)
fi
route="$(ip -o -4 route get 1.1.1.1 2>/dev/null || true)"
parse_route_source_ip "$route"
}
prompt_value() {
local var_name="$1"
local prompt_text="$2"
local is_secret="${3:-false}"
local value=""
while [[ -z "$value" ]]; do
if [[ "$is_secret" == "true" ]]; then
read -r -s -p "$prompt_text: " value
printf "\n"
else
read -r -p "$prompt_text: " value
fi
done
printf -v "$var_name" '%s' "$value"
}
write_env_file() {
local realm=""
local workgroup=""
local domain=""
local admin_user=""
local admin_password=""
local domain_users_sid=""
local domain_admins_sid=""
local fslogix_group_sid=""
local backup_destination=""
local backup_archive_password=""
local backup_auto_enabled="true"
local backup_auto_input=""
local backup_start_hour="2"
local backup_retention_daily="3"
local backup_retention_weekly="2"
local backup_retention_monthly="2"
local backup_retention_yearly="1"
local samba_hostname="adsambafsrv"
local netbios_name="ADSAMBAFSRV"
local ad_dns_ip=""
local ad_dns_name=""
local ad_dns_ip_auto="0"
local service_password=""
local web_hostname=""
local web_https_port="443"
local web_jwt_secret=""
local acme_ca_server=""
local acme_ca_certificates_source=""
local acme_ca_certificates_source_dir=""
local acme_ca_certificates_url=""
local acme_ca_certificates_insecure_download="false"
local acme_ca_certificates_insecure_input=""
local acme_http_port="80"
local acme_http_port_input=""
local web_hostname_input=""
local service_account_sam=""
local fslogix_group_prompt=""
local samba_hostname_input=""
local netbios_name_input=""
local ad_dns_ip_input=""
local ad_dns_name_input=""
local detected_ad_dns_ip=""
local sanitized_netbios_name=""
prompt_value realm "REALM (e.g. EXAMPLE.COM)"
prompt_value workgroup "WORKGROUP (NetBIOS, e.g. EXAMPLE)"
prompt_value domain "DOMAIN (AD DNS name or reachable DC FQDN)"
prompt_value admin_user "Initial admin user (for provisioning service account)"
prompt_value admin_password "Initial admin password" true
prompt_value domain_users_sid "DOMAIN_USERS_SID (e.g. ...-513)"
prompt_value domain_admins_sid "DOMAIN_ADMINS_SID (e.g. ...-512)"
fslogix_group_prompt="FSLOGIX_GROUP_SID (press Enter to reuse DOMAIN_USERS_SID)"
read -r -p "${fslogix_group_prompt}: " fslogix_group_sid
if [[ -z "$fslogix_group_sid" ]]; then
fslogix_group_sid="$domain_users_sid"
fi
read -r -p "SAMBA_HOSTNAME [adsambafsrv]: " samba_hostname_input
if [[ -n "${samba_hostname_input:-}" ]]; then
samba_hostname="$samba_hostname_input"
fi
read -r -p "NETBIOS_NAME [ADSAMBAFSRV]: " netbios_name_input
if [[ -n "${netbios_name_input:-}" ]]; then
netbios_name="$netbios_name_input"
fi
sanitized_netbios_name="$(sanitize_netbios_name "$netbios_name")"
if [[ "$sanitized_netbios_name" != "$netbios_name" ]]; then
printf "Using sanitized NETBIOS_NAME: %s\n" "$sanitized_netbios_name"
fi
netbios_name="$sanitized_netbios_name"
detected_ad_dns_ip="$(detect_ad_dns_ip "$domain" || true)"
if [[ -n "$detected_ad_dns_ip" ]]; then
read -r -p "AD_DNS_IP (host LAN IP to publish in AD DNS) [${detected_ad_dns_ip}]: " ad_dns_ip_input
if [[ -n "$ad_dns_ip_input" ]]; then
ad_dns_ip="$ad_dns_ip_input"
else
ad_dns_ip="$detected_ad_dns_ip"
ad_dns_ip_auto="1"
fi
else
prompt_value ad_dns_ip "AD_DNS_IP (host LAN IP to publish in AD DNS)"
fi
ad_dns_name="${samba_hostname}.${domain}"
read -r -p "AD_DNS_NAME [${ad_dns_name}]: " ad_dns_name_input
if [[ -n "$ad_dns_name_input" ]]; then
ad_dns_name="$ad_dns_name_input"
fi
read -r -p "BACKUP_DESTINATION (optional URL, press Enter to disable): " backup_destination
if [[ -n "$backup_destination" ]]; then
prompt_value backup_archive_password "BACKUP_ARCHIVE_PASSWORD (encrypts group archives)" true
read -r -p "Enable automatic daily backups? [Y/n]: " backup_auto_input
case "${backup_auto_input,,}" in
n|no) backup_auto_enabled="false" ;;
*) backup_auto_enabled="true" ;;
esac
fi
read -r -p "BACKUP_START_HOUR [2]: " backup_start_hour
backup_start_hour="${backup_start_hour:-2}"
read -r -p "BACKUP_RETENTION_DAILY [3]: " backup_retention_daily
backup_retention_daily="${backup_retention_daily:-3}"
read -r -p "BACKUP_RETENTION_WEEKLY [2]: " backup_retention_weekly
backup_retention_weekly="${backup_retention_weekly:-2}"
read -r -p "BACKUP_RETENTION_MONTHLY [2]: " backup_retention_monthly
backup_retention_monthly="${backup_retention_monthly:-2}"
read -r -p "BACKUP_RETENTION_YEARLY [1]: " backup_retention_yearly
backup_retention_yearly="${backup_retention_yearly:-1}"
web_hostname="$ad_dns_name"
read -r -p "WEB_HOSTNAME [${web_hostname}]: " web_hostname_input
web_hostname="${web_hostname_input:-$web_hostname}"
read -r -p "WEB_HTTPS_PORT [443]: " web_https_port
web_https_port="${web_https_port:-443}"
prompt_value acme_ca_server "ACME_CA_SERVER (e.g. https://ca.internal/acme/acme/directory)"
read -r -p "ACME_CA_CERTIFICATES_URL (optional one-time download; Enter to import a local PEM file): " acme_ca_certificates_url
if [[ -n "$acme_ca_certificates_url" ]]; then
case "$acme_ca_certificates_url" in
https://*) ;;
*)
printf "ACME_CA_CERTIFICATES_URL must use https://\n" >&2
return 1
;;
esac
read -r -p "Allow untrusted TLS for this one-time root download? [y/N]: " acme_ca_certificates_insecure_input
case "$acme_ca_certificates_insecure_input" in
y|Y|yes|YES) acme_ca_certificates_insecure_download=true ;;
*) acme_ca_certificates_insecure_download=false ;;
esac
else
prompt_value acme_ca_certificates_source "ACME CA root bundle (PEM file on this host)"
if [[ ! -s "$acme_ca_certificates_source" ]]; then
printf "ACME CA root bundle is not a readable file: %s\n" "$acme_ca_certificates_source" >&2
return 1
fi
acme_ca_certificates_source_dir="$(cd "$(dirname "$acme_ca_certificates_source")" && pwd)"
acme_ca_certificates_source="${acme_ca_certificates_source_dir}/$(basename "$acme_ca_certificates_source")"
fi
read -r -p "ACME_HTTP_PORT (HTTP-01 host port) [80]: " acme_http_port_input
acme_http_port="${acme_http_port_input:-80}"
web_jwt_secret="$(python3 - <<'PY'
import secrets
print(secrets.token_urlsafe(48))
PY
)"
service_account_sam="$(sanitize_sam_account_name "$SERVICE_ACCOUNT_NAME")"
if [[ "$service_account_sam" != "$SERVICE_ACCOUNT_NAME" ]]; then
printf "Using sAMAccountName '%s' (AD limit is 20 chars; requested '%s').\n" "$service_account_sam" "$SERVICE_ACCOUNT_NAME"
fi
service_password="$(python3 - <<'PY'
import secrets
import string
alphabet = string.ascii_letters + string.digits + '@#%+=:_-'
print(''.join(secrets.choice(alphabet) for _ in range(48)))
PY
)"
if [[ -f "$ENV_FILE" ]]; then
ENV_PREEXISTED=1
ORIGINAL_ENV_BACKUP="$(mktemp)"
cp "$ENV_FILE" "$ORIGINAL_ENV_BACKUP"
chmod 600 "$ORIGINAL_ENV_BACKUP"
fi
BOOTSTRAP_ENV_FILE="$(mktemp)"
chmod 600 "$BOOTSTRAP_ENV_FILE"
cat > "$BOOTSTRAP_ENV_FILE" <<EOF
REALM=${realm}
WORKGROUP=${workgroup}
DOMAIN=${domain}
JOIN_USER=${admin_user}
JOIN_PASSWORD=${admin_password}
SERVICE_ACCOUNT_NAME=${SERVICE_ACCOUNT_NAME}
SERVICE_ACCOUNT_SAM=${service_account_sam}
SERVICE_ACCOUNT_PASSWORD=${service_password}
DOMAIN_USERS_SID=${domain_users_sid}
DOMAIN_ADMINS_SID=${domain_admins_sid}
FSLOGIX_GROUP_SID=${fslogix_group_sid}
AD_DNS_IP=${ad_dns_ip}
AD_DNS_NAME=${ad_dns_name}
AD_DNS_IP_AUTO=${ad_dns_ip_auto}
BACKUP_DESTINATION=${backup_destination}
BACKUP_ARCHIVE_PASSWORD=${backup_archive_password}
BACKUP_AUTO_ENABLED=${backup_auto_enabled}
BACKUP_START_HOUR=${backup_start_hour}
BACKUP_RETENTION_DAILY=${backup_retention_daily}
BACKUP_RETENTION_WEEKLY=${backup_retention_weekly}
BACKUP_RETENTION_MONTHLY=${backup_retention_monthly}
BACKUP_RETENTION_YEARLY=${backup_retention_yearly}
SAMBA_HOSTNAME=${samba_hostname}
NETBIOS_NAME=${netbios_name}
WEB_ENABLED=true
WEB_HOSTNAME=${web_hostname}
WEB_HTTPS_PORT=${web_https_port}
WEB_JWT_SECRET=${web_jwt_secret}
WEB_TLS_MODE=acme
ACME_CA_SERVER=${acme_ca_server}
ACME_CA_CERTIFICATES=/state/tls/acme-ca-certificates.pem
ACME_CA_CERTIFICATES_URL=${acme_ca_certificates_url}
ACME_CA_CERTIFICATES_INSECURE_DOWNLOAD=${acme_ca_certificates_insecure_download}
ACME_HTTP_LISTEN=:80
ACME_HTTP_PORT=${acme_http_port}
EOF
cp "$BOOTSTRAP_ENV_FILE" "$ENV_FILE"
chmod 600 "$ENV_FILE"
BOOTSTRAP_ENV_WRITTEN=1
printf "Building image...\n"
docker compose build samba
if [[ -n "$acme_ca_certificates_source" ]]; then
printf "Importing ACME CA root bundle...\n"
docker compose run --rm --no-deps -T \
--entrypoint /bin/bash samba -lc \
'install -d -m 0755 "$(dirname "$ACME_CA_CERTIFICATES")" && dd of="$ACME_CA_CERTIFICATES" status=none && chmod 0644 "$ACME_CA_CERTIFICATES"' \
< "$acme_ca_certificates_source"
fi
printf "Provisioning service account %s...\n" "$SERVICE_ACCOUNT_NAME"
docker compose run --rm --entrypoint /bin/bash samba -lc '
set -euo pipefail
cat > /tmp/bootstrap-smb.conf <<EOF
[global]
security = ADS
kerberos method = secrets and keytab
realm = ${REALM}
workgroup = ${WORKGROUP}
netbios name = ${NETBIOS_NAME}
EOF
run_net() {
net -s /tmp/bootstrap-smb.conf -A /tmp/bootstrap.auth -S "$DOMAIN" "$@"
}
cat > /tmp/bootstrap.auth <<EOF
username = ${JOIN_USER}
password = ${JOIN_PASSWORD}
domain = ${WORKGROUP}
EOF
chmod 600 /tmp/bootstrap.auth
if run_net ads search "(&(objectClass=user)(sAMAccountName=${SERVICE_ACCOUNT_SAM}))" sAMAccountName | grep -q "^sAMAccountName: ${SERVICE_ACCOUNT_SAM}$"; then
run_net ads password "${SERVICE_ACCOUNT_SAM}" "${SERVICE_ACCOUNT_PASSWORD}"
else
run_net ads user add "${SERVICE_ACCOUNT_SAM}" "${SERVICE_ACCOUNT_PASSWORD}"
fi fi
'
cat > "$ENV_FILE" <<EOF
REALM=${realm}
WORKGROUP=${workgroup}
DOMAIN=${domain}
JOIN_USER=${service_account_sam}
JOIN_PASSWORD=${service_password}
DOMAIN_USERS_SID=${domain_users_sid}
DOMAIN_ADMINS_SID=${domain_admins_sid}
FSLOGIX_GROUP_SID=${fslogix_group_sid}
AD_DNS_IP=${ad_dns_ip}
AD_DNS_NAME=${ad_dns_name}
AD_DNS_IP_AUTO=${ad_dns_ip_auto}
BACKUP_DESTINATION=${backup_destination}
BACKUP_ARCHIVE_PASSWORD=${backup_archive_password}
BACKUP_AUTO_ENABLED=${backup_auto_enabled}
BACKUP_START_HOUR=${backup_start_hour}
BACKUP_RETENTION_DAILY=${backup_retention_daily}
BACKUP_RETENTION_WEEKLY=${backup_retention_weekly}
BACKUP_RETENTION_MONTHLY=${backup_retention_monthly}
BACKUP_RETENTION_YEARLY=${backup_retention_yearly}
SAMBA_HOSTNAME=${samba_hostname}
NETBIOS_NAME=${netbios_name}
WEB_ENABLED=true
WEB_HOSTNAME=${web_hostname}
WEB_HTTPS_PORT=${web_https_port}
WEB_JWT_SECRET=${web_jwt_secret}
WEB_TLS_MODE=acme
ACME_CA_SERVER=${acme_ca_server}
ACME_CA_CERTIFICATES=/state/tls/acme-ca-certificates.pem
ACME_CA_CERTIFICATES_URL=${acme_ca_certificates_url}
ACME_CA_CERTIFICATES_INSECURE_DOWNLOAD=${acme_ca_certificates_insecure_download}
ACME_HTTP_LISTEN=:80
ACME_HTTP_PORT=${acme_http_port}
# Optional overrides:
# LDAP_URI=ldaps://${domain}
# LDAP_BASE_DN=DC=example,DC=com
# PRIVATE_SKIP_USERS=svc_backup,svc_sql
# PRIVATE_SKIP_PREFIXES=svc_,sql_
# BACKUP_DESTINATION=rsync://user:pass@backup.example.com/samba-backups
# BACKUP_DESTINATION=smb://DOMAIN%5Cuser:pass@backup.example.com/Backups/samba
# BACKUP_DESTINATION=davfs://user:pass@webdav.example.com/remote.php/dav/files/backup
# BACKUP_DESTINATION=sftp://user:pass@sftp.example.com/exports/samba
# BACKUP_ARCHIVE_PASSWORD=use-a-long-random-secret
# BACKUP_AUTO_ENABLED=true
# BACKUP_ARCHIVE_TEMP_DIR=/tmp
# BACKUP_START_HOUR=2
# BACKUP_RETENTION_DAILY=3
# BACKUP_RETENTION_WEEKLY=2
# BACKUP_RETENTION_MONTHLY=2
# BACKUP_RETENTION_YEARLY=1
# BACKUP_LOG_FILE=/var/log/backup.log
# BACKUP_PROGRESS=auto
# BACKUP_PROGRESS_INTERVAL_SECONDS=10
# WEB_JWT_TTL_SECONDS=28800
# WEB_USAGE_SCAN_INTERVAL_SECONDS=900
# WEB_DIRECTORY_CACHE_SECONDS=300
# STATE_DB_PATH=/state/shares.db
# AUDIT_QUERY_MAX_DAYS=31
# AUDIT_SKIP_USER_SUFFIXES=_svc,_ServiceAcc
# ACME_RENEW_CHECK_SECONDS=900
# WEB_TLS_CERT_FILE=/state/tls/web.crt
# WEB_TLS_KEY_FILE=/state/tls/web.key
EOF
chmod 600 "$ENV_FILE"
FINAL_ENV_WRITTEN=1
printf "Created %s\n" "$ENV_FILE"
}
if [[ -f "$ENV_FILE" ]]; then
read -r -p ".env already exists. Overwrite? [y/N]: " overwrite
case "$overwrite" in
y|Y|yes|YES)
write_env_file
;;
*)
printf "Keeping existing .env\n"
;;
esac
else
write_env_file
fi
docker compose up -d docker compose up -d
printf "Samba service started.\n" printf '\nOpen http://<server>/ to configure HTTPS, then continue over HTTPS.\n'
printf 'First-launch setup codes: docker compose logs samba\n'
+53
View File
@@ -0,0 +1,53 @@
"""Disposable browser fixture; AD is simulated, settings APIs are real."""
import json
import os
from pathlib import Path
import signal
import ssl
import tempfile
from types import SimpleNamespace
from app import configuration, state_db, web_security, web_ui
def main():
with tempfile.TemporaryDirectory(prefix='adfs-configuration-browser-') as root:
store = configuration.Store(root)
web_ui.CONFIG = store
identity = {'sub':'EXAMPLE\\admin','sid':'S-1-5-21-1-2-3-1100','uid':1000,'role':'domain-admin'}
groups = [{'sid':'S-1-5-21-1-2-3-512','name':'Domain Admins'}, {'sid':'S-1-5-21-1-2-3-513','name':'Domain Users'}]
web_ui.authenticate_user = lambda username, password: identity if username == 'admin' and password == 'fixture-password' else None
web_ui.current_identity = lambda sid, admin_sid=None: identity
web_ui.directory.open_db = lambda: state_db.connect_state_db(str(Path(root) / 'shares.db'))
tokens = web_ui.TokenManager(store.snapshot()['values']['WEB_JWT_SECRET'], 600, web_security.Sessions(str(Path(root) / 'shares.db')), identity_resolver=lambda sid: identity)
web_ui.APP = SimpleNamespace(tokens=tokens, backup=lambda include_log=True: {'enabled':False,'manualEnabled':False,'state':'disabled','log':[]})
web_ui.STATIC_ROOT = str(Path(__file__).resolve().parents[1] / 'app/web')
original_exists = os.path.exists
os.path.exists = lambda path: True if str(path) in ('/run/adfs-domain-ready','/run/adfs-services-ready') else original_exists(path)
class Handler(web_ui.Handler):
def domain_groups(self):
return groups
def do_POST(self):
super().do_POST()
if self.path == '/api/bootstrap/domain' and store.snapshot()['phase'] == 'joining':
store.phase('groups')
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
fixture = Path(__file__).parent / 'fixtures'
context.load_cert_chain(fixture / 'web-test.crt', fixture / 'web-test.key')
server = web_ui.ReusableHTTPServer(('127.0.0.1',0),Handler,context)
port = server.server_address[1]
with store.connect() as conn:
values = store.snapshot()['values']
values.update(WEB_HOSTNAME='files.example.test', WEB_HTTPS_PORT=str(port))
conn.execute('UPDATE configuration SET settings=?', (json.dumps(values),))
signal.signal(signal.SIGTERM, lambda *args: (_ for _ in ()).throw(SystemExit()))
print(json.dumps({'port':port, 'code':store.bootstrap_code()}), flush=True)
try:
server.serve_forever()
finally:
server.server_close()
if __name__ == '__main__':
main()
+86
View File
@@ -0,0 +1,86 @@
import assert from 'node:assert/strict';
import {spawn} from 'node:child_process';
import {createRequire} from 'node:module';
import {createInterface} from 'node:readline';
import {fileURLToPath} from 'node:url';
import {mkdir} from 'node:fs/promises';
const require = createRequire(import.meta.url);
const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const root = fileURLToPath(new URL('../',import.meta.url));
const fixture = spawn('python3',['-m','tests.configuration_browser_fixture'],{cwd:root,stdio:['ignore','pipe','pipe']});
let logs='', browser; fixture.stderr.on('data',chunk=>{logs+=chunk;});
const output = '/tmp/adfs-configuration-screenshots'; await mkdir(output,{recursive:true});
try {
const info = await new Promise((resolve,reject)=>{
const lines=createInterface({input:fixture.stdout}); const timeout=setTimeout(()=>reject(new Error('Fixture timeout: '+logs)),10000);
lines.on('line',line=>{if(line.startsWith('{')){clearTimeout(timeout);resolve(JSON.parse(line));}});
fixture.once('exit',code=>reject(new Error('Fixture failed: '+code+' '+logs)));
});
browser=await chromium.launch({headless:true,...(process.env.CHROMIUM_EXECUTABLE_PATH?{executablePath:process.env.CHROMIUM_EXECUTABLE_PATH}:{}),args:['--no-proxy-server','--host-resolver-rules=MAP files.example.test 127.0.0.1']});
const context=await browser.newContext({ignoreHTTPSErrors:true,viewport:{width:1360,height:1000}});
const page=await context.newPage(); const errors=[];page.on('pageerror',error=>errors.push(error.message));
const target=`https://files.example.test:${info.port}`;
await page.goto(target+'/');
await page.getByLabel('Einrichtungscode',{exact:true}).fill(info.code);
await page.getByRole('button',{name:'Weiter',exact:true}).click();
await page.getByLabel('Kerberos-Domäne').fill('EXAMPLE.TEST');
await page.getByLabel('NetBIOS-Domäne',{exact:true}).fill('EXAMPLE');
await page.getByLabel('Domänencontroller / AD-DNS-Name').fill('example.test');
await page.getByLabel('Konto für Domänenbeitritt und LDAP',{exact:true}).fill('admin');
await page.getByLabel('Passwort für Domänenbeitritt und LDAP',{exact:true}).fill('fixture-password');
await page.screenshot({path:output+'/https-domain-desktop.png',fullPage:true});
await page.getByRole('button',{name:'Domäne beitreten',exact:true}).click();
await page.getByRole('heading',{name:'Gruppen auswählen'}).waitFor();
await page.getByLabel('Passwort',{exact:true}).fill('fixture-password');
await page.getByRole('button',{name:'Einrichtung abschließen'}).click();
await page.getByRole('link',{name:'Zur Anmeldung'}).waitFor();
assert.equal(await page.evaluate(async code=>(await fetch('/api/bootstrap/settings',{headers:{'X-Setup-Token':code}})).status,info.code),403);
await page.goto(target+'/admin/settings');
await page.getByLabel('Benutzername',{exact:true}).fill('admin');
await page.getByLabel('Passwort',{exact:true}).fill('fixture-password');
await page.getByRole('button',{name:'Anmelden',exact:true}).click();
await page.getByRole('button',{name:'Sicherungen',exact:true}).click();
await page.getByLabel('Sicherungsziel',{exact:true}).fill('sftp://backup:fixture-secret@backup.example.test/files');
await page.getByRole('button',{name:'Wiederherstellungsphrase erzeugen',exact:true}).click();
const dialog=page.getByRole('dialog'); await dialog.waitFor();
assert.equal(await dialog.locator('.recovery-words li').count(),24);
const phrase=await dialog.locator('.recovery-words li').allTextContents();
assert.equal((await dialog.getByRole('button',{name:'Schlüssel aktivieren'}).isEnabled()),true);
await dialog.getByRole('button',{name:'Schlüssel aktivieren'}).click();
assert.equal(await dialog.isVisible(),true);
await dialog.getByLabel('Ich habe alle 24 Wörter',{exact:false}).check();
await dialog.getByRole('button',{name:'Schlüssel aktivieren'}).click();
await dialog.waitFor({state:'detached'});
assert.equal(await page.getByLabel('Sicherungsziel',{exact:true}).inputValue(),'sftp://backup:fixture-secret@backup.example.test/files');
await page.getByLabel('Sicherungsziel',{exact:true}).fill('sftp://backup:fixture-secret@backup.example.test/files');
await page.getByLabel('Automatische Sicherungen',{exact:true}).check();
await page.getByRole('button',{name:'Änderungen speichern'}).click();
await page.getByText('Gespeichert.',{exact:true}).waitFor();
assert.equal(await page.getByLabel('Sicherungsziel',{exact:true}).inputValue(),'');
await page.getByRole('button',{name:'Neue Wiederherstellungsphrase erzeugen',exact:true}).click();
const renew=page.getByRole('dialog'); await renew.waitFor();
await renew.getByLabel('Ich habe alle 24 Wörter',{exact:false}).check();
await renew.getByRole('button',{name:'Schlüssel aktivieren'}).click();
assert.equal(await renew.isVisible(),true);
await renew.getByLabel('Ich bewahre auch die bisherige Phrase',{exact:false}).check();
await renew.getByRole('button',{name:'Schlüssel aktivieren'}).click();
await renew.waitFor({state:'detached'});
const text=await page.locator('body').innerText(); assert.ok(!text.includes(phrase.join(' ')));assert.ok(!text.includes('fixture-secret'));
await page.locator('#toast').waitFor({state:'hidden'});
await page.screenshot({path:output+'/backup-settings-desktop.png',fullPage:true});
await page.setViewportSize({width:390,height:844});
await page.screenshot({path:output+'/backup-settings-mobile.png',fullPage:true});
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth));
assert.deepEqual(errors,[]);
// Inspect the actual zero-env container's HTTP-only onboarding page too.
if (process.env.CONFIG_HTTP_URL) {
const httpPage=await context.newPage();
await httpPage.goto(process.env.CONFIG_HTTP_URL);
await httpPage.getByRole('heading',{name:'HTTPS zuerst einrichten'}).waitFor();
assert.equal(await httpPage.locator('input[name=password],input[name=username]').count(),0);
assert.equal(await httpPage.evaluate(async()=>(await fetch('/api/login',{method:'POST',body:'{}'})).status),403);
await httpPage.screenshot({path:output+'/http-acme-desktop.png',fullPage:true});
}
console.log('PASS: HTTPS bootstrap, admin settings, phrase confirmation and rotation, secret redaction, responsive layout; optional HTTP onboarding check. Screenshots: '+output);
} finally { if(browser) await browser.close(); fixture.kill('SIGTERM'); }
+343
View File
@@ -0,0 +1,343 @@
import hashlib
import io
import http.client
import json
import os
from pathlib import Path
import shutil
import sqlite3
import subprocess
import tempfile
import threading
import unittest
from unittest import mock
from app import backup_keys, backup_to_destination as backup, configuration, tls_configuration
LEGACY = {'REALM': 'EXAMPLE.TEST', 'WORKGROUP': 'EXAMPLE', 'DOMAIN': 'example.test',
'JOIN_USER': 'service', 'JOIN_PASSWORD': 'old-secret',
'DOMAIN_USERS_SID': 'S-1-5-21-1-2-3-513', 'DOMAIN_ADMINS_SID': 'S-1-5-21-1-2-3-512',
'BACKUP_DESTINATION': 'rsync://backup:old-password@backup.test/target',
'BACKUP_ARCHIVE_PASSWORD': 'old-archive-password'}
class RecoveryPhraseTests(unittest.TestCase):
def test_official_bip39_vector_and_checksum(self):
phrase = 'abandon ' * 11 + 'about'
self.assertEqual(backup_keys.phrase_from_entropy(bytes(16)), phrase)
expected = 'c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04'
self.assertEqual(backup_keys.seed(phrase, 'TREZOR').hex(), expected)
with self.assertRaises(ValueError):
backup_keys.archive_key('abandon ' * 12)
with self.assertRaises(ValueError):
backup_keys.archive_key('not a phrase')
def test_generated_key_recovers_from_the_phrase(self):
result = backup_keys.generate()
self.assertEqual(len(result['phrase'].split()), 24)
self.assertEqual(backup_keys.archive_key(result['phrase']), result['password'])
self.assertEqual(len(result['keyId']), 24)
self.assertEqual(hashlib.sha256((Path(backup_keys.__file__).parent / 'vendor/bip39/english.txt').read_bytes()).hexdigest(),
'2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda')
class ConfigurationTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.store = configuration.Store(self.root)
def test_first_launch_is_persistent_and_private(self):
self.assertEqual(self.store.snapshot()['phase'], 'unconfigured')
secret = self.store.snapshot()['values']['WEB_JWT_SECRET']
code = self.store.bootstrap_code()
self.assertEqual(configuration.Store(self.root).bootstrap_code(), code)
self.assertEqual(configuration.Store(self.root).snapshot()['values']['WEB_JWT_SECRET'], secret)
self.assertTrue(self.store.accepts_bootstrap(code))
self.assertFalse(self.store.accepts_bootstrap('wrong'))
self.assertEqual(self.store.path.stat().st_mode & 0o777, 0o600)
def test_import_preserves_paths_credentials_data_and_only_runs_once(self):
original = self.root / 'important-file'
original.write_bytes(b'production\x00fixture')
self.assertTrue(self.store.import_legacy(LEGACY | {'GROUP_ROOT':'/data/groups', 'TLS_CA_PROVISIONER_PASSWORD':'ca-secret'}))
snap = self.store.snapshot()
self.assertEqual(snap['values']['GROUP_ROOT'], '/data/groups')
self.assertEqual(snap['values']['TLS_CA_PASSWORD'], 'ca-secret')
self.assertEqual(snap['values']['BACKUP_ARCHIVE_PASSWORD'], 'old-archive-password')
self.assertFalse(snap['values']['BACKUP_ENCRYPTION_ENABLED'])
self.assertFalse(self.store.accepts_bootstrap(self.store.bootstrap_code()))
self.assertEqual(original.read_bytes(), b'production\x00fixture')
with self.assertRaises(configuration.Conflict):
self.store.import_legacy(LEGACY)
public = json.dumps(self.store.public())
for secret in ('old-secret','old-password','old-archive-password','ca-secret'):
self.assertNotIn(secret, public)
self.assertIn('rsync://backup.test/target', public)
def test_resolved_container_import_preserves_literal_password_bytes(self):
values=LEGACY | {'JOIN_PASSWORD':'literal-$VALUE-$(never-execute)-$$'}
payload=json.dumps([key+'='+value for key,value in values.items()])
with mock.patch.object(configuration,'Store',return_value=self.store), mock.patch.object(configuration.sys,'argv',['configuration','import-runtime']), mock.patch.object(configuration.sys,'stdin',io.StringIO(payload)), mock.patch.object(configuration.sys,'stdout',io.StringIO()):
configuration.main()
self.assertEqual(self.store.snapshot()['values']['JOIN_PASSWORD'],values['JOIN_PASSWORD'])
with mock.patch.object(configuration,'Store',return_value=self.store), mock.patch.object(configuration.sys,'argv',['configuration','import-runtime']), mock.patch.object(configuration.sys,'stdin',io.StringIO('[]')), mock.patch.object(configuration.sys,'stdout',io.StringIO()):
configuration.main()
self.assertEqual(self.store.snapshot()['values']['JOIN_PASSWORD'],values['JOIN_PASSWORD'])
def test_legacy_parser_never_executes_shell(self):
marker = self.root / 'must-not-exist'
text = 'JOIN_PASSWORD="$(touch ' + str(marker) + ')"\nWORKGROUP=EXAMPLE # comment\n'
parsed = configuration.parse_legacy(text)
self.assertEqual(parsed['JOIN_PASSWORD'], '$(touch ' + str(marker) + ')')
self.assertEqual(parsed['WORKGROUP'], 'EXAMPLE')
self.assertFalse(marker.exists())
def test_key_owner_confirmation_expiry_and_configuration_revision(self):
self.store.import_legacy(LEGACY)
pending = self.store.generate_key('owner')
with self.assertRaises(ValueError):
self.store.activate_key('owner', pending['nonce'], False, True)
with self.assertRaises(configuration.Conflict):
self.store.activate_key('attacker', pending['nonce'], True, True)
with self.assertRaises(ValueError):
self.store.activate_key('owner', pending['nonce'], True, False)
self.store.save({'BACKUP_START_HOUR': 3}, self.store.snapshot()['revision'])
with self.assertRaises(configuration.Conflict):
self.store.activate_key('owner', pending['nonce'], True, True)
pending = self.store.generate_key('owner')
with mock.patch.object(configuration.time, 'time', return_value=10**12):
with self.assertRaises(configuration.Conflict):
self.store.activate_key('owner', pending['nonce'], True, True)
def test_rotation_preserves_old_keys_and_uses_new_destination_namespace(self):
self.store.import_legacy(LEGACY)
first = self.store.generate_key('owner')
self.store.activate_key('owner', first['nonce'], True, True)
old_password = self.store.snapshot()['values']['BACKUP_ARCHIVE_PASSWORD']
second = self.store.generate_key('owner')
self.store.activate_key('owner', second['nonce'], True, True)
values = self.store.snapshot()['values']
self.assertEqual(values['BACKUP_NAMESPACE'], 'keys/' + second['keyId'])
self.assertNotEqual(first['keyId'], second['keyId'])
self.assertEqual(backup_keys.archive_key(first['phrase']), old_password)
self.assertEqual(backup_keys.archive_key(second['phrase']), values['BACKUP_ARCHIVE_PASSWORD'])
self.assertNotIn(second['phrase'], self.store.path.read_bytes().decode(errors='ignore'))
self.store.save({'BACKUP_ENCRYPTION_ENABLED':False}, self.store.snapshot()['revision'])
self.assertEqual(self.store.snapshot()['values']['BACKUP_NAMESPACE'], 'plain')
self.store.save({'BACKUP_ENCRYPTION_ENABLED':True}, self.store.snapshot()['revision'])
self.assertEqual(self.store.snapshot()['values']['BACKUP_NAMESPACE'], 'keys/' + second['keyId'])
def test_invalid_values_and_stale_writes_cannot_change_configuration(self):
for name, value in [('BACKUP_DESTINATION','sftp://user:abc%0Aevil@server/path'), ('DOCUMENT_OCR_DPI',10000), ('WORKGROUP','a'*16), ('WEB_TRUSTED_ORIGINS','https://a/path')]:
with self.assertRaises(ValueError):
self.store.save({name:value}, 0)
self.store.save({'BACKUP_START_HOUR': 4}, 0)
with self.assertRaises(configuration.Conflict):
self.store.save({'BACKUP_START_HOUR': 5}, 0)
self.assertEqual(self.store.snapshot()['values']['BACKUP_START_HOUR'], 4)
def test_defaults_use_the_realm_when_a_controller_hostname_is_selected(self):
self.store.save({'REALM':'EXAMPLE.TEST','DOMAIN':'dc.example.test'},0,bootstrap=True)
environment=self.store.environment()
self.assertEqual(environment['LDAP_BASE_DN'],'DC=example,DC=test')
self.assertEqual(environment['AD_DNS_NAME'],'adsambafsrv.example.test')
def test_enabling_full_encryption_requires_a_confirmed_phrase(self):
self.store.import_legacy(LEGACY)
with self.assertRaises(ValueError):
self.store.save({'BACKUP_ENCRYPTION_ENABLED':True},self.store.snapshot()['revision'])
self.assertFalse(self.store.snapshot()['values']['BACKUP_ENCRYPTION_ENABLED'])
def test_database_configuration_removes_stale_environment_overrides(self):
environment = self.store.service_environment({'LDAP_URI':'ldap://old', 'JOIN_PASSWORD':'external', 'PATH':'/bin'})
self.assertNotIn('LDAP_URI', environment)
self.assertEqual(environment['JOIN_PASSWORD'], '')
self.assertEqual(environment['PATH'], '/bin')
def test_invalid_tls_pair_does_not_overwrite_existing_certificate(self):
cert = self.root / 'tls/web.crt'
tls_configuration.write_private(cert, 'old certificate')
with self.assertRaises(ValueError):
self.store.save({'WEB_TLS_MODE':'files','WEB_TLS_CERT_PEM':'invalid','WEB_TLS_KEY_PEM':'invalid'}, 0)
self.assertEqual(cert.read_text(), 'old certificate')
self.assertEqual(self.store.snapshot()['revision'], 0)
def test_configuration_is_snapshotted_from_sqlite_without_live_wal_files(self):
self.store.import_legacy(LEGACY)
conn = sqlite3.connect(self.root / 'shares.db')
conn.execute('CREATE TABLE fixture(value TEXT)')
conn.execute("INSERT INTO fixture VALUES('important')")
conn.commit(); conn.close()
temporary, staged = backup.prepare_state_snapshot(str(self.root), str(self.root / 'shares.db'))
self.addCleanup(shutil.rmtree, temporary)
self.assertFalse((Path(staged) / 'configuration.db-wal').exists())
copied = sqlite3.connect(Path(staged) / 'configuration.db')
self.assertEqual(copied.execute('PRAGMA quick_check').fetchone()[0], 'ok')
self.assertEqual(json.loads(copied.execute('SELECT settings FROM configuration').fetchone()[0])['JOIN_PASSWORD'], 'old-secret')
copied.close()
@unittest.skipUnless(shutil.which('7z'), '7z is required for native encrypted recovery checks')
class EncryptedBackupTests(unittest.TestCase):
def test_all_sources_encrypted_and_recovered_and_wrong_phrase_rejected(self):
with tempfile.TemporaryDirectory() as root:
sources = []
for name in ('private','groups','fslogix','state','samba-private'):
source = Path(root) / name; source.mkdir()
(source / 'confidential.txt').write_text('secret-content-' + name)
sources.append((str(source), name))
key = backup_keys.generate()
temporary, staged = backup.prepare_encrypted_sources(sources, key['password'], root)
try:
encrypted = Path(staged[0][0])
self.assertEqual(len(list(encrypted.glob('*.7z'))), len(sources))
for archive in encrypted.glob('*.7z'):
self.assertNotIn(b'secret-content', archive.read_bytes())
wrong = subprocess.run(['7z','l','-pwrong',str(archive)], capture_output=True)
self.assertNotEqual(wrong.returncode, 0)
target = Path(root) / ('recovered-' + archive.stem)
recovery = subprocess.run(['7z','x','-o' + str(target),str(archive)], input=(backup_keys.archive_key(key['phrase'])+'\n').encode(),capture_output=True)
self.assertEqual(recovery.returncode, 0, recovery.stderr)
self.assertEqual(next(target.rglob('confidential.txt')).read_text(), 'secret-content-' + archive.stem)
finally:
shutil.rmtree(temporary)
class HttpOnboardingTests(unittest.TestCase):
def setUp(self):
from app import http_setup
self.http_setup = http_setup
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.store = configuration.Store(self.temp.name)
self.code = http_setup.setup_code(self.store)
self.patch = mock.patch.object(http_setup.configuration, 'Store', return_value=self.store)
self.patch.start(); self.addCleanup(self.patch.stop)
self.server = http_setup.Server(('127.0.0.1', 0), http_setup.Handler)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start(); self.addCleanup(self.close)
self.host = '%s:%s' % self.server.server_address
def close(self):
self.server.shutdown(); self.server.server_close(); self.thread.join(timeout=5)
def request(self, path, method='POST', value=None, code=None):
conn = http.client.HTTPConnection(*self.server.server_address, timeout=5)
try:
conn.request(method, path, body=json.dumps(value or {}), headers={'Content-Type':'application/json','Origin':'http://' + self.host, 'X-HTTPS-Setup-Code': self.code if code is None else code})
response = conn.getresponse(); body = response.read()
return response.status, body
finally:
conn.close()
def test_http_exposes_no_credential_or_admin_endpoints(self):
for path in ('/api/login','/api/bootstrap/domain','/api/bootstrap/import','/admin/api/settings','/api/bootstrap/finish'):
self.assertEqual(self.request(path, value={'JOIN_PASSWORD':'secret'})[0], 403)
for path in ('/admin/access','/api/bootstrap/settings','/assets/setup.js','/assets/settings.js'):
self.assertEqual(self.request(path, method='GET')[0], 403)
self.assertEqual(self.store.snapshot()['revision'], 0)
def test_https_link_and_redirect_respect_external_port(self):
status, body = self.request('/api/https/status', method='GET')
self.assertEqual(status, 200)
self.assertEqual(json.loads(body)['httpsUrl'], 'https://localhost/')
values = self.store.snapshot()['values']
values.update(WEB_HOSTNAME='files.localhost', WEB_HTTPS_PORT='18445')
with self.store.connect() as conn:
conn.execute('UPDATE configuration SET settings=? WHERE id=1', (json.dumps(values),))
status, body = self.request('/api/https/status', method='GET')
self.assertEqual(status, 200)
self.assertEqual(json.loads(body)['httpsUrl'], 'https://files.localhost:18445/')
self.assertEqual(self.store.snapshot()['phase'], 'unconfigured')
with self.store.connect() as conn:
conn.execute("UPDATE configuration SET phase='configured' WHERE id=1")
connection = http.client.HTTPConnection(*self.server.server_address, timeout=5)
try:
connection.request('GET', '/')
response = connection.getresponse()
response.read()
self.assertEqual(response.status, 308)
self.assertEqual(response.getheader('Location'), 'https://files.localhost:18445/')
finally:
connection.close()
def test_https_and_http_setup_capabilities_are_separate(self):
https_code = self.store.bootstrap_code()
self.assertNotEqual(https_code, self.code)
self.assertFalse(self.store.accepts_bootstrap(self.code))
value = {'WEB_HOSTNAME':'files.example.test','ACME_CA_SERVER':'https://ca.example.test/acme/directory'}
self.assertEqual(self.request('/api/https/configure', value=value, code=https_code)[0], 403)
self.assertEqual(self.request('/api/https/configure', value=value)[0], 202)
self.assertEqual(self.store.snapshot()['values']['WEB_TLS_MODE'], 'acme')
self.assertEqual(self.store.snapshot()['phase'], 'unconfigured')
def test_http_tls_fields_cannot_include_credentials_or_invalid_root(self):
value = {'WEB_HOSTNAME':'files.example.test','ACME_CA_SERVER':'https://ca.example.test/acme/directory'}
for changes in ({'JOIN_USER':'admin'}, {'JOIN_PASSWORD':'secret'}, {'BACKUP_DESTINATION':'sftp://secret@server/path'}, {'ACME_CA_SERVER':'https://user:password@server/acme'}, {'ACME_CA_CERTIFICATES_PEM':'not a certificate'}):
self.assertEqual(self.request('/api/https/configure', value=value | changes)[0], 400)
self.assertEqual(self.store.snapshot()['revision'], 0)
def test_uploaded_ca_is_validated_and_persisted_for_acme(self):
root = (Path(__file__).parent / 'fixtures/web-test.crt').read_text()
value = {'WEB_HOSTNAME':'files.example.test','ACME_CA_SERVER':'https://ca.example.test/acme/directory','ACME_CA_CERTIFICATES_PEM':root}
self.assertEqual(self.request('/api/https/configure', value=value)[0], 202)
self.assertEqual(Path(self.store.environment()['ACME_CA_CERTIFICATES']).read_text().strip(), root.strip())
class SettingsAuthorizationTests(unittest.TestCase):
def setUp(self):
from app import web_ui, web_security, state_db
from types import SimpleNamespace
self.web_ui = web_ui
self.temp = tempfile.TemporaryDirectory(); self.addCleanup(self.temp.cleanup)
self.store = configuration.Store(self.temp.name)
self.store.import_legacy(LEGACY | {'WEB_HOSTNAME':'files.example.test'})
db = str(Path(self.temp.name) / 'shares.db')
self.tokens = web_ui.TokenManager(self.store.snapshot()['values']['WEB_JWT_SECRET'],600,web_security.Sessions(db))
for patch in (mock.patch.object(web_ui,'CONFIG',self.store),
mock.patch.object(web_ui,'APP',SimpleNamespace(tokens=self.tokens)),
mock.patch.object(web_ui,'lock_is_held',return_value=False),
mock.patch.dict(os.environ,clear=False)):
patch.start();self.addCleanup(patch.stop)
self.server = web_ui.ReusableHTTPServer(('127.0.0.1',0),web_ui.Handler)
self.thread = threading.Thread(target=self.server.serve_forever,daemon=True);self.thread.start();self.addCleanup(self.close)
self.admin, _ = self.tokens.issue('EXAMPLE\\admin','S-1-5-21-1-2-3-1100','domain-admin',1000)
self.user, _ = self.tokens.issue('EXAMPLE\\user','S-1-5-21-1-2-3-1101','user',1001)
def close(self):
self.server.shutdown();self.server.server_close();self.thread.join(timeout=5)
def request(self,path,method='GET',value=None,token=None,csrf=True):
token = self.admin if token is None else token
headers = {'Content-Type':'application/json','Origin':'https://files.example.test'}
if token:
headers['Cookie'] = self.web_ui.JWT_COOKIE + '=' + token
if csrf:headers['X-CSRF-Token'] = self.tokens.csrf(self.tokens.verify(token))
conn = http.client.HTTPConnection(*self.server.server_address,timeout=5)
try:
conn.request(method,path,headers=headers,body=json.dumps(value or {}))
response=conn.getresponse();return response.status,json.loads(response.read())
finally:
conn.close()
def test_settings_and_keys_require_an_administrator_and_csrf(self):
for token,status in (('',401),(self.user,403)):
self.assertEqual(self.request('/admin/api/settings',token=token)[0],status)
self.assertEqual(self.request('/admin/api/settings/backup-key/generate','POST',token=token)[0],status)
self.assertEqual(self.request('/admin/api/settings/backup-key/generate','POST',csrf=False)[0],403)
status,public=self.request('/admin/api/settings')
self.assertEqual(status,200)
self.assertNotIn('old-secret',json.dumps(public))
with self.store.connect() as conn:
self.assertEqual(conn.execute('SELECT COUNT(*) FROM pending_backup_keys').fetchone()[0],0)
def test_authenticated_save_uses_revision_and_keeps_imported_secrets(self):
revision=self.store.snapshot()['revision']
status,_=self.request('/admin/api/settings','POST',{'revision':revision,'values':{'BACKUP_START_HOUR':8}})
self.assertEqual(status,200)
self.assertEqual(self.store.snapshot()['values']['JOIN_PASSWORD'],'old-secret')
self.assertEqual(self.request('/admin/api/settings','POST',{'revision':revision,'values':{'BACKUP_START_HOUR':9}})[0],409)
self.assertEqual(self.store.snapshot()['values']['BACKUP_START_HOUR'],8)
+1 -1
View File
@@ -226,7 +226,7 @@ class AdministrationActionTests(unittest.TestCase):
): ):
with mock.patch.dict( with mock.patch.dict(
os.environ, os.environ,
{"BACKUP_DESTINATION": "rsync://backup.example.test/target"}, {"BACKUP_DESTINATION": "rsync://backup.example.test/target", "BACKUP_ENCRYPTION_ENABLED": "true"},
clear=True, clear=True,
): ):
with self.assertRaisesRegex( with self.assertRaisesRegex(