is an open-source password manager that businesses can run on their own servers. That means their own certificates, mail, storage and updates, and their own questions when one of those goes wrong.
So I installed Bitwarden 2026.11.0, the standard install, on a Debian 12 server, with a private certificate authority and a test mail server, and wrote a health check for it. Then I reproduced four questions on it, two of them open issues on Bitwarden's GitHub. Here's what each run settled, and the reply I'd send.
The test server
It listens only on 127.0.0.1, uses the reserved .test domain and a private CA, and changed nothing public on its host. The installation ID and key stay in the server's own settings, and no script prints them. The has every step, from the installer's prompts to teardown.
Start with a health check
bwcheck checks a self-hosted server from the outside and, with --bwdata, from the server itself. It uses Python's standard library only, so there's nothing to install. On the finished test server:
bwcheck report
==============
Server https://vault.casebook.test:18443
[OK] config.yml's url matches
[OK] The installation ID and key are set
[OK] SMTP is set to mailpit:1025
[INFO] 21 settings in global.override.env (9 secret ones, not shown)
[OK] All 11 bitwarden- containers are up
[INFO] nginx 1.31.9 is running in bitwarden-nginx
After a security fix, check this rather than the image tag: pulling an update too
early can still give the old nginx.
[INFO] Connecting to 127.0.0.1 as vault.casebook.test (--resolve)
[OK] The certificate verifies against the CA in pki/ca.crt (TLSv1.3)
Issued by Casebook Test Root CA.
[OK] The certificate is valid for another 29 days
[INFO] The server sends 2 certificates in its chain
[OK] The web vault answers
[OK] The security headers are present
[OK] All 5 services answer: API, Identity, Notifications, Icons, Events
[INFO] Server version 2026.11.0
[OK] The URLs the server advertises match the address you used
No blocking problems found.It checks the certificate, and why it fails if it does, the web vault and the five services, the URLs the server advertises, the security headers, and whether the content security policy allows the storage you've configured. On the server, it reads config.yml and the settings file, showing settings by name only, never their values. From a machine that doesn't trust the test CA, the same check explains the failure, and names the fix for the CLI too:
[FAIL] The certificate doesn't verify: self-signed certificate in certificate chain.
It's issued by "Casebook Test Root CA", which this machine doesn't trust. Install
that CA on each device, or pass --cacert. Node-based tools (the Bitwarden CLI and
Directory Connector CLI) also need NODE_EXTRA_CA_CERTS.1. Emails that never arrive
The question: on a new server, nobody gets verification or invitation emails, and there are no errors anywhere. The admin portal even says it sent the login link.
What the run showed: a new install leaves the mail server set to REPLACE. With those settings, asking the admin portal for a login link got the same "sent" answer as when mail works, and the admin service logged nothing:
=== 1. As the installer left it
globalSettings__mail__smtp__host=REPLACE
globalSettings__mail__smtp__username=REPLACE
The admin portal answered 302, redirecting to /admin/login?success=3
Errors or warnings the admin service logged since the request: none
=== 2. With a test mail server in the stack
globalSettings__mail__smtp__host=mailpit
globalSettings__mail__smtp__port=1025
The admin portal answered 302, redirecting to /admin/login?success=3
Mailpit's inbox:
1 message(s)
To admin@casebook.test: "[Admin] Continue Logging In"explains why. It treats the placeholders SECRET and REPLACE as unset, then registers a service that drops mail when no provider is configured. bwcheck warns about it from the server: SMTP isn't configured, so verification and invitation emails can't be sent.
The reply, in short: set the five SMTP settings in ./bwdata/env/global.override.env, restart, and test with a login link from the admin portal. The note for the team: a warning at start-up, such as "Mail delivery isn't configured: emails will be dropped", would save these tickets.
2. A CLI that ignores the system's CA
The question: we added our CA to the server's trust store, and curl works now, but bw login still fails with "self-signed certificate in certificate chain".
What the run showed, with Bitwarden CLI 2026.11.1 on Node 22:
| Attempt | Result |
|---|---|
| No CA anywhere | self-signed certificate in certificate chain |
| CA added to the system store | curl gets HTTP 200, but the CLI fails the same way |
| NODE_EXTRA_CA_CERTS set | TLS works, and only the made-up login fails |
The Bitwarden CLI is built on Node.js, and Node keeps its own list of trusted CAs instead of using the system's. The same applies to the Directory Connector CLI.
The reply, in short: point the CLI at the CA file with NODE_EXTRA_CA_CERTS. describe it, but the CLI's error doesn't point there. One line in that error would make this a self-service fix.
3. Azure Blob storage blocked by the browser
The question (): after moving attachments and Send to Azure Blob storage, uploads and downloads fail in the web vault, with content security policy errors for connect-src.
What the run showed: the step that builds nginx's content security policy doesn't add the storage account's address, so the browser blocks requests to it. The account was made up, so nothing was uploaded. The case checks the policy the server sends, which is what the browser enforces:
=== 1. connect-src as generated
connect-src 'self' wss://vault.casebook.test https://api.pwnedpasswords.com https://api.2fa.directory
=== 2. Send and attachments pointed at Azure Blob storage
Rebuilt and restarted.
connect-src 'self' wss://vault.casebook.test https://api.pwnedpasswords.com https://api.2fa.directory
bwcheck: [FAIL] The content security policy blocks https://casebookexample.blob.core.windows.net.
=== 3. The workaround: a custom policy in config.yml
Rebuilt and restarted.
connect-src 'self' https://casebookexample.blob.core.windows.net wss://vault.casebook.test https://api.pwnedpasswords.com https://api.2fa.directory
bwcheck: [OK] The content security policy allows https://casebookexample.blob.core.windows.netbwcheck reads the storage settings and checks each address against the policy:
def csp_allows(policy: dict[str, list[str]], directive: str, origin: str) -> bool:
"""Whether a directive (falling back to default-src) lists an origin."""
sources = policy.get(directive, policy.get("default-src", []))
origin = origin.rstrip("/").lower()
for source in sources:
source = source.rstrip("/").lower()
if source in ("*", origin):
return True
if source.startswith("https://*.") and origin.startswith("https://") and origin.endswith(source[len("https://*"):]):
return True
return False
def azure_blob_origin(connection_string: str) -> str | None:
"""The blob storage origin an Azure connection string points at, if any."""
parts = dict(
item.split("=", 1) for item in connection_string.strip().strip('"').split(";") if "=" in item
)
if "BlobEndpoint" in parts:
endpoint = urlsplit(parts["BlobEndpoint"])
return f"{endpoint.scheme}://{endpoint.netloc}".lower()
if "AccountName" in parts:
suffix = parts.get("EndpointSuffix", "core.windows.net")
protocol = parts.get("DefaultEndpointsProtocol", "https")
return f"{protocol}://{parts['AccountName']}.blob.{suffix}".lower()
return NoneThe reply, in short: until it's fixed, put the whole policy in config.yml with the account's address added to connect-src, then rebuild and restart. One thing to remember: a custom policy also freezes it. Later releases won't change it until the setting is removed, so it needs checking after each update.
4. Lite logs that stopped
The question (): after updating Bitwarden Lite to 2026.11.0, no new log files appear. There's also an "Item has already been added" exception in the container output.
What the run showed: five Lite containers ran side by side for two minutes, all with SQLite and the same installation ID:
| Run | Daily logs on the data volume | Start-up crash |
|---|---|---|
| 2026.10.1, minimum settings | 5 files | none |
| 2026.11.0, minimum settings | none | none |
2026.11.0 + GLOBALSETTINGS__ | none | yes |
2026.11.0 + GLOBALSETTINGS__ | none | yes |
2026.11.0 + globalSettings__, Lite's own spelling | none | none |
So the report is two problems. Lite 2026.11.0 stopped writing its daily service logs to the data volume. It still writes them inside the container, in /var/log/bitwarden, but those are lost when the container is replaced. Separately, any setting Lite already sets, given in capitals, crashes its start-up step. On Linux those are different names, so the container ends up with both, and the step that merges them, ignoring case, stops with "Item has already been added".
The reply, in short: read the logs with docker exec for now, and use the spelling from Lite's settings.env template, which makes the exception go away. The log change goes to engineering: a container with only the required settings behaves the same way, so it isn't the customer's settings.
One more, for shared hosts
Bitwarden's Compose project is called docker, after its folder, and its stop and restart act on the whole project. On a host that runs other Compose projects, check first that docker compose ls shows no other project called docker.
How I used AI
I used Claude Code to read Bitwarden's source, set up the test server, write bwcheck and the cases, and draft the replies. Every claim on this page comes from a recorded run, and the runs also caught bwcheck's own mistakes. An early version warned about an advertised URL that's meant to point elsewhere, so it now compares only the URLs a self-hosted server serves itself, port included.
The transcripts were checked for the installation ID and key before publishing, and the tests build their fake keys at runtime, so secret scanners don't mistake them for real ones.
The sample
Everything above comes from : the runbook, bwcheck with 13 offline tests, the four cases with their replies and transcripts, and scripts that create the private CA and remove everything afterwards.
bwcheck.py (522 lines)
#!/usr/bin/env python3
"""
bwcheck: a health check for a self-hosted Bitwarden server.
It answers the first questions an implementation engineer asks about a
deployment, and prints a report that can go straight into a ticket:
- Does the name resolve, and does the certificate verify? If not, why not:
an unknown CA, a missing chain, the wrong name, or an expired certificate?
- Do the web vault and the API, identity and notifications services answer?
- Which version is running, and do the URLs it advertises match the address
people actually use?
- Are the security headers there, and does the content security policy
allow the storage you've configured?
- Run on the server with --bwdata, it also checks the containers, the nginx
version, and the settings in global.override.env (names only, never values).
It uses Python's standard library only, so it runs on any machine with
Python 3.9 or later and nothing to install.
Examples:
python3 bwcheck.py https://vault.example.com
python3 bwcheck.py https://vault.example.com --cacert ca.crt
python3 bwcheck.py https://vault.example.com:8443 --resolve 127.0.0.1 --bwdata /opt/bitwarden/bwdata
Exit codes: 0 if nothing blocking was found, 1 if a check failed, 2 for bad arguments.
"""
from __future__ import annotations
import argparse
import datetime as dt
import http.client
import json
import os
import re
import shutil
import socket
import ssl
import subprocess
import sys
import tempfile
import textwrap
from dataclasses import dataclass, field
from urllib.parse import urlsplit
OK, INFO, WARN, FAIL = "OK", "INFO", "WARN", "FAIL"
WIDTH = 92
# Services behind Bitwarden's nginx, and the health path each one answers.
SERVICES = [
("API", "/api/alive"),
("Identity", "/identity/alive"),
("Notifications", "/notifications/alive"),
("Icons", "/icons/alive"),
("Events", "/events/alive"),
]
# The URLs in /api/config's "environment" that should point at this server.
# Others, such as fillAssistRules and cloudRegion, legitimately point at Bitwarden's cloud.
SELF_HOSTED_URLS = ("vault", "api", "identity", "notifications", "sso")
SECURITY_HEADERS = [
"content-security-policy",
"strict-transport-security",
"x-frame-options",
"x-content-type-options",
"referrer-policy",
]
# Setting names whose values must never be printed.
SECRET_NAME = re.compile(r"(key|password|secret|token|connectionstring)", re.I)
@dataclass
class Finding:
level: str
title: str
detail: str = ""
@dataclass
class Report:
url: str
findings: list[Finding] = field(default_factory=list)
def add(self, level: str, title: str, detail: str = "") -> None:
self.findings.append(Finding(level, title, detail))
@property
def failed(self) -> bool:
return any(f.level == FAIL for f in self.findings)
def render(self) -> str:
lines = ["bwcheck report", "==============", f"Server {self.url}", ""]
for f in self.findings:
tag = f"[{f.level}]"
pad = " " * (len(tag) + 1)
lines += textwrap.wrap(f"{tag} {f.title}", WIDTH, subsequent_indent=pad)
if f.detail:
lines += textwrap.wrap(f.detail, WIDTH, initial_indent=pad, subsequent_indent=pad)
lines += ["", "Problems found: see FAIL lines." if self.failed else "No blocking problems found."]
return "\n".join(lines)
# ---------------------------------------------------------------- pure helpers
def parse_csp(header: str) -> dict[str, list[str]]:
"""Split a Content-Security-Policy header into {directive: [sources]}."""
policy: dict[str, list[str]] = {}
for part in header.split(";"):
words = part.strip().split()
if words:
policy[words[0].lower()] = words[1:]
return policy
def csp_allows(policy: dict[str, list[str]], directive: str, origin: str) -> bool:
"""Whether a directive (falling back to default-src) lists an origin."""
sources = policy.get(directive, policy.get("default-src", []))
origin = origin.rstrip("/").lower()
for source in sources:
source = source.rstrip("/").lower()
if source in ("*", origin):
return True
if source.startswith("https://*.") and origin.startswith("https://") and origin.endswith(source[len("https://*"):]):
return True
return False
def azure_blob_origin(connection_string: str) -> str | None:
"""The blob storage origin an Azure connection string points at, if any."""
parts = dict(
item.split("=", 1) for item in connection_string.strip().strip('"').split(";") if "=" in item
)
if "BlobEndpoint" in parts:
endpoint = urlsplit(parts["BlobEndpoint"])
return f"{endpoint.scheme}://{endpoint.netloc}".lower()
if "AccountName" in parts:
suffix = parts.get("EndpointSuffix", "core.windows.net")
protocol = parts.get("DefaultEndpointsProtocol", "https")
return f"{protocol}://{parts['AccountName']}.blob.{suffix}".lower()
return None
def read_env_file(path: str) -> dict[str, str]:
"""NAME=VALUE lines from a file such as global.override.env."""
values: dict[str, str] = {}
with open(path, encoding="utf-8-sig") as handle:
for line in handle:
line = line.strip()
if line and not line.startswith("#") and "=" in line:
name, _, value = line.partition("=")
values[name.strip()] = value.strip()
return values
def read_config_yml(path: str) -> dict[str, str]:
"""The top-level `key: value` lines of Bitwarden's config.yml (enough for these checks)."""
values: dict[str, str] = {}
with open(path, encoding="utf-8") as handle:
for line in handle:
if line.startswith((" ", "\t", "#", "-")) or ":" not in line:
continue
key, _, value = line.partition(":")
values[key.strip()] = value.strip().strip("'\"")
return values
def days_left(not_after: str, now: dt.datetime | None = None) -> int:
"""Days until a certificate's notAfter, as Python's ssl module formats it."""
expires = dt.datetime.strptime(not_after, "%b %d %H:%M:%S %Y %Z").replace(tzinfo=dt.timezone.utc)
now = now or dt.datetime.now(dt.timezone.utc)
return (expires - now).days
def version_tuple(text: str) -> tuple[int, ...]:
return tuple(int(p) for p in re.findall(r"\d+", text)[:3])
def host_and_port(url: str) -> tuple[str | None, int]:
"""A URL's host and port, filling in the scheme's default port."""
parts = urlsplit(url)
return parts.hostname, parts.port or (443 if parts.scheme in ("https", "wss") else 80)
def cert_names(cert: dict) -> list[str]:
"""The DNS names a certificate is valid for."""
return [value for kind, value in cert.get("subjectAltName", ()) if kind == "DNS"]
def name_matches(host: str, names: list[str]) -> bool:
host = host.lower()
for name in names:
name = name.lower()
if name == host or (name.startswith("*.") and host.count(".") == name.count(".") and host.endswith(name[1:])):
return True
return False
# -------------------------------------------------------------- network checks
class PinnedHTTPSConnection(http.client.HTTPSConnection):
"""HTTPS to a chosen IP address, while sending the real name for SNI and Host."""
def __init__(self, host: str, port: int, ip: str, context: ssl.SSLContext, timeout: float = 10):
super().__init__(host, port, context=context, timeout=timeout)
self._ip = ip
def connect(self) -> None:
sock = socket.create_connection((self._ip, self.port), self.timeout)
self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
class PinnedHTTPConnection(http.client.HTTPConnection):
def __init__(self, host: str, port: int, ip: str, timeout: float = 10):
super().__init__(host, port, timeout=timeout)
self._ip = ip
def connect(self) -> None:
self.sock = socket.create_connection((self._ip, self.port), self.timeout)
@dataclass
class Target:
scheme: str
host: str
port: int
ip: str
base_path: str
context: ssl.SSLContext | None
def get(self, path: str) -> tuple[int, dict[str, str], bytes]:
if self.scheme == "https":
conn = PinnedHTTPSConnection(self.host, self.port, self.ip, self.context)
else:
conn = PinnedHTTPConnection(self.host, self.port, self.ip)
try:
conn.request("GET", self.base_path + path, headers={"User-Agent": "bwcheck"})
response = conn.getresponse()
body = response.read(200_000)
headers = {name.lower(): value for name, value in response.getheaders()}
return response.status, headers, body
finally:
conn.close()
def describe_unverified_cert(host: str, ip: str, port: int) -> dict:
"""Fetch the certificate without verifying it, to say why verification failed."""
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
with socket.create_connection((ip, port), timeout=10) as sock:
with context.wrap_socket(sock, server_hostname=host) as tls:
der = tls.getpeercert(binary_form=True)
pem = ssl.DER_cert_to_PEM_cert(der)
with tempfile.NamedTemporaryFile("w", suffix=".pem", delete=False) as handle:
handle.write(pem)
try:
return ssl._ssl._test_decode_cert(handle.name) # CPython's own certificate decoder
except Exception:
return {}
finally:
os.unlink(handle.name)
def chain_length(host: str, ip: str, port: int) -> int | None:
"""How many certificates the server sends, using the openssl tool if it's installed."""
if not shutil.which("openssl"):
return None
result = subprocess.run(
["openssl", "s_client", "-showcerts", "-servername", host, "-connect", f"{ip}:{port}"],
input="",
capture_output=True,
text=True,
timeout=20,
)
return result.stdout.count("BEGIN CERTIFICATE") or None
def check_tls(report: Report, host: str, ip: str, port: int, cafile: str | None) -> ssl.SSLContext:
"""Verify the certificate the way a client would, and explain any failure."""
context = ssl.create_default_context(cafile=cafile)
try:
with socket.create_connection((ip, port), timeout=10) as sock:
with context.wrap_socket(sock, server_hostname=host) as tls:
cert = tls.getpeercert()
protocol = tls.version()
left = days_left(cert["notAfter"])
issuer = dict(item[0] for item in cert.get("issuer", ())).get("commonName", "?")
trust = f"the CA in {cafile}" if cafile else "this machine's trusted CAs"
report.add(OK, f"The certificate verifies against {trust} ({protocol})", f"Issued by {issuer}.")
if left < 0:
report.add(FAIL, f"The certificate expired {-left} days ago.")
elif left < 14:
report.add(WARN, f"The certificate expires in {left} days.")
else:
report.add(OK, f"The certificate is valid for another {left} days")
except ssl.SSLCertVerificationError as exc:
reason = exc.verify_message or str(exc)
details = describe_unverified_cert(host, ip, port)
names = cert_names(details)
issuer = dict(item[0] for item in details.get("issuer", ())).get("commonName", "unknown")
hints = []
if names and not name_matches(host, names):
hints.append(f"It's for {', '.join(names)}, not {host}.")
if "self-signed" in reason or "unable to get local issuer" in reason:
hints.append(
f'It\'s issued by "{issuer}", which this machine doesn\'t trust. Install that CA on each '
"device, or pass --cacert. Node-based tools (the Bitwarden CLI and Directory Connector "
"CLI) also need NODE_EXTRA_CA_CERTS."
)
sent = chain_length(host, ip, port)
if sent == 1 and issuer != "unknown":
hints.append("The server sends only its own certificate, so clients can't build the chain.")
report.add(FAIL, f"The certificate doesn't verify: {reason}.", " ".join(hints))
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE # carry on with the other checks, unverified
else:
sent = chain_length(host, ip, port)
if sent is not None:
report.add(INFO, f"The server sends {sent} certificate{'s' if sent != 1 else ''} in its chain")
return context
def check_http(report: Report, target: Target, storage_origins: list[str]) -> None:
status, headers, _ = target.get("/")
if status != 200:
report.add(FAIL, f"The web vault answered {status}, not 200.")
else:
report.add(OK, "The web vault answers")
missing = [name for name in SECURITY_HEADERS if name not in headers]
if target.scheme != "https" and "strict-transport-security" in missing:
missing.remove("strict-transport-security")
if missing:
report.add(WARN, "Missing security headers: " + ", ".join(missing) + ".",
"If a reverse proxy sits in front of Bitwarden's nginx, it may be dropping them.")
else:
report.add(OK, "The security headers are present")
csp = parse_csp(headers.get("content-security-policy", ""))
for origin in storage_origins:
if csp_allows(csp, "connect-src", origin):
report.add(OK, f"The content security policy allows {origin}")
else:
report.add(
FAIL,
f"The content security policy blocks {origin}.",
"Send and attachment uploads and downloads to that storage will fail in the browser. "
"Add the origin to connect-src with nginx_header_content_security_policy in config.yml, "
"then run ./bitwarden.sh rebuild and ./bitwarden.sh restart.",
)
down = []
for name, path in SERVICES:
try:
code, _, _ = target.get(path)
except OSError as exc:
code = f"error ({exc.__class__.__name__})"
if code != 200:
down.append(f"{name} ({path}: {code})")
if down:
report.add(FAIL, "Some services don't answer: " + ", ".join(down) + ".")
else:
report.add(OK, f"All {len(SERVICES)} services answer: " + ", ".join(n for n, _ in SERVICES))
try:
code, _, body = target.get("/api/config")
config = json.loads(body) if code == 200 else {}
except (OSError, ValueError):
config = {}
if not config:
report.add(WARN, "Couldn't read /api/config.")
return
report.add(INFO, f"Server version {config.get('version', '?')}")
environment = config.get("environment") or {}
expected = (target.host, target.port)
wrong = {
name: url for name, url in environment.items()
if name in SELF_HOSTED_URLS and isinstance(url, str) and url and host_and_port(url) != expected
}
if wrong:
listed = ", ".join(f"{k}={v}" for k, v in sorted(wrong.items()))
report.add(
WARN,
"The server advertises URLs on a different host than the one you used.",
f"{listed}. Clients follow these, so a wrong url: in config.yml or a wrong "
"globalSettings__baseServiceUri setting breaks logins.",
)
else:
report.add(OK, "The URLs the server advertises match the address you used")
# ----------------------------------------------------------- on-server checks
def check_server(report: Report, bwdata: str, host: str) -> list[str]:
"""Checks that need the server's files. Returns any storage origins found in the settings."""
origins: list[str] = []
config_path = os.path.join(bwdata, "config.yml")
env_path = os.path.join(bwdata, "env", "global.override.env")
if os.path.exists(config_path):
config = read_config_yml(config_path)
configured = urlsplit(config.get("url", "")).hostname
if configured and configured != host:
report.add(FAIL, f"config.yml says url is {config.get('url')}, but you're checking {host}.")
else:
report.add(OK, "config.yml's url matches")
if config.get("nginx_header_content_security_policy"):
report.add(INFO, "config.yml sets a custom content security policy")
else:
report.add(WARN, f"No config.yml at {config_path}.")
if os.path.exists(env_path):
env = read_env_file(env_path)
lowered = {k.lower(): v for k, v in env.items()}
def is_set(name: str) -> bool:
value = lowered.get(name.lower(), "")
return bool(value) and "<placeholder>" not in value.lower() and value.upper() != "REPLACE"
missing = [n for n in ("globalSettings__installation__id", "globalSettings__installation__key") if not is_set(n)]
report.add(FAIL if missing else OK,
"The installation ID and key are set" if not missing else "Missing: " + ", ".join(missing) + ".")
smtp = [n for n in ("globalSettings__mail__smtp__host", "globalSettings__mail__smtp__port") if not is_set(n)]
if smtp:
report.add(WARN, "SMTP isn't configured, so verification and invitation emails can't be sent.",
"Set the globalSettings__mail__smtp__ settings in global.override.env, then restart.")
else:
report.add(OK, f"SMTP is set to {lowered.get('globalsettings__mail__smtp__host')}:"
f"{lowered.get('globalsettings__mail__smtp__port')}")
if not is_set("adminSettings__admins"):
report.add(INFO, "No adminSettings__admins, so the System Administrator Portal has no users.")
for label, name in (("Attachments", "globalSettings__attachment__connectionString"),
("Send files", "globalSettings__send__connectionString")):
value = lowered.get(name.lower(), "")
origin = azure_blob_origin(value) if value else None
if origin:
if origin not in origins:
origins.append(origin)
report.add(INFO, f"{label}: Azure Blob storage at {origin}")
secret_names = sorted(n for n in env if SECRET_NAME.search(n))
report.add(INFO, f"{len(env)} settings in global.override.env ({len(secret_names)} secret ones, not shown)")
else:
report.add(WARN, f"No global.override.env at {env_path}.")
if shutil.which("docker"):
result = subprocess.run(
["docker", "ps", "-a", "--filter", "name=bitwarden-", "--format", "{{.Names}}\t{{.Status}}"],
capture_output=True, text=True, timeout=30,
)
rows = [line.split("\t", 1) for line in result.stdout.splitlines() if "\t" in line]
unhealthy = [f"{n} ({s})" for n, s in rows if not s.startswith("Up") or "unhealthy" in s]
if not rows:
report.add(WARN, "No bitwarden- containers found.")
elif unhealthy:
report.add(FAIL, "Some containers aren't running or healthy: " + ", ".join(unhealthy) + ".")
else:
report.add(OK, f"All {len(rows)} bitwarden- containers are up")
nginx = subprocess.run(["docker", "exec", "bitwarden-nginx", "nginx", "-v"],
capture_output=True, text=True, timeout=30)
found = re.search(r"nginx/([\d.]+)", nginx.stderr + nginx.stdout)
if found:
report.add(INFO, f"nginx {found.group(1)} is running in bitwarden-nginx",
"After a security fix, check this rather than the image tag: pulling an update "
"too early can still give the old nginx.")
return origins
# ------------------------------------------------------------------------ main
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Check a self-hosted Bitwarden server.")
parser.add_argument("url", help="the address people use, for example https://vault.example.com")
parser.add_argument("--cacert", help="a CA certificate file to trust, for a private CA")
parser.add_argument("--resolve", metavar="IP", help="connect to this IP instead of looking the name up")
parser.add_argument("--bwdata", help="the server's bwdata folder, to add on-server checks")
parser.add_argument("--storage-origin", action="append", default=[],
help="a storage origin the content security policy must allow (repeatable)")
args = parser.parse_args(argv)
parts = urlsplit(args.url)
if parts.scheme not in ("http", "https") or not parts.hostname:
parser.error("the URL must look like https://vault.example.com")
host = parts.hostname
port = parts.port or (443 if parts.scheme == "https" else 80)
report = Report(args.url)
origins = list(dict.fromkeys(args.storage_origin)) # keeps order, drops repeats
if args.bwdata:
for origin in check_server(report, args.bwdata, host):
if origin not in origins:
origins.append(origin)
try:
ip = args.resolve or socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)[0][4][0]
report.add(OK if not args.resolve else INFO,
f"{host} resolves to {ip}" if not args.resolve else f"Connecting to {ip} as {host} (--resolve)")
except socket.gaierror as exc:
report.add(FAIL, f"{host} doesn't resolve: {exc}.", "Check the DNS record, or use --resolve.")
print(report.render())
return 1
context = None
try:
if parts.scheme == "https":
context = check_tls(report, host, ip, port, args.cacert)
check_http(report, Target(parts.scheme, host, port, ip, parts.path.rstrip("/"), context), origins)
except OSError as exc:
report.add(FAIL, f"Couldn't connect to {ip}:{port}: {exc}.")
print(report.render())
return 1 if report.failed else 0
if __name__ == "__main__":
sys.exit(main())To run bwcheck, you need Python 3: python3 bwcheck.py https://vault.example.com, with --cacert for a private CA.