Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| edb2a6df1d | |||
| bea370dca2 | |||
| 7772e489e0 | |||
| 2e50696bb4 | |||
| 25f3a40402 | |||
| 2bfe130d3b | |||
| 3cd04e3263 | |||
| 00cc2beec7 | |||
| 9472cfff8d | |||
| e23eb7498b |
@@ -0,0 +1,24 @@
|
||||
# Changelog
|
||||
|
||||
## 0.4.2
|
||||
|
||||
- Certificate Common Name (CN) is now taken from each device's own
|
||||
CSR instead of being forced to equal its `device_id`. Enables
|
||||
deployments where many devices intentionally share one CN per
|
||||
category (e.g. for broker ACL grouping) while each still uses its
|
||||
own unique MQTT topic.
|
||||
- `GET /api/pending` and `GET /api/issued` now include the resolved
|
||||
CN alongside `device_id` for each entry.
|
||||
|
||||
## 0.4.1
|
||||
|
||||
- Changed SAN default for generating server certificate
|
||||
- Added two new options for organizations
|
||||
|
||||
## 0.4.0
|
||||
|
||||
- Replaced RSA algorithm with EC for encryption.
|
||||
|
||||
## 0.3.0
|
||||
|
||||
- Initial release.
|
||||
@@ -7,17 +7,29 @@ MQTT broker (unauthenticated, or with a shared bootstrap username/password
|
||||
|
||||
Default topic prefix is `cert/enroll`, configurable in the add-on options.
|
||||
Replace `<device_id>` with a stable, unique identifier for the node (e.g.
|
||||
its MAC address with colons stripped, or a serial number). This value is
|
||||
used as both the MQTT topic segment and the certificate's Common Name /
|
||||
SAN, so keep it short, DNS-safe, and unique on your network.
|
||||
its MAC address with colons stripped, or a serial number) — this MUST be
|
||||
unique per physical device, even if many devices share the same MQTT
|
||||
login for connecting to the broker. It's what topic routing and this
|
||||
add-on's own record-keeping are both keyed on; two devices sharing a
|
||||
`device_id` will collide with each other.
|
||||
|
||||
The cert's Common Name (CN) is a separate, independent concept — see
|
||||
step 2.
|
||||
|
||||
## 1. Generate a key pair and CSR (on-device, once)
|
||||
|
||||
The private key never leaves the device. Generate an RSA-2048 (or EC
|
||||
P-256) key pair and a PKCS#10 CSR with:
|
||||
- Common Name = `<device_id>`
|
||||
- No need for extensions in the CSR itself; the add-on sets the ones that
|
||||
matter (basic constraints, key usage, SAN) when it signs.
|
||||
|
||||
- Common Name = whatever identity you want written into the issued
|
||||
certificate. This does NOT have to be `device_id` and does NOT have to
|
||||
be unique per device — a common pattern is to share one CN across a
|
||||
whole category of devices (e.g. every TH sensor uses CN `TH-Sensors`,
|
||||
every light sensor uses CN `Light-Sensors`), which is useful if you're
|
||||
writing broker ACL rules grouped by category rather than by individual
|
||||
device.
|
||||
- No need for other extensions in the CSR itself; the add-on sets the
|
||||
ones that matter (basic constraints, key usage, SAN) when it signs.
|
||||
|
||||
Persist the key pair to flash. If a cert is later lost or expires, reuse
|
||||
the same key and just repeat step 2 — no need to regenerate the key.
|
||||
@@ -28,6 +40,7 @@ Topic: `cert/enroll/<device_id>/request`
|
||||
QoS: 1, retain: false
|
||||
|
||||
Payload (JSON):
|
||||
|
||||
```json
|
||||
{
|
||||
"csr": "-----BEGIN CERTIFICATE REQUEST-----\n...\n-----END CERTIFICATE REQUEST-----\n",
|
||||
@@ -37,34 +50,53 @@ Payload (JSON):
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`meta` is optional and only shown to the human approving the request — put
|
||||
anything there that helps you recognize the device in the UI.
|
||||
|
||||
The issued certificate's CN is taken directly from your CSR's own CN
|
||||
(step 1) — there's no separate field for it here. If your CSR has no CN
|
||||
at all, the add-on falls back to using `device_id` as the CN, but that's
|
||||
a safety net for malformed requests, not something to rely on.
|
||||
|
||||
This does NOT apply to renewal (§5) — a renewed cert always keeps the CN
|
||||
of the device's current, still-valid cert, regardless of what a renewal
|
||||
request's CSR claims. Changing identity requires a fresh, human-approved
|
||||
enrollment, not a renewal.
|
||||
|
||||
## 3. Subscribe for the result, before or immediately after publishing
|
||||
|
||||
Subscribe to both of these (QoS 1) so you catch whichever response comes:
|
||||
Subscribe to both of these (QoS 1) so you catch whichever response comes.
|
||||
Since `device_id` is unique per device (per the requirement above), each
|
||||
device has its own dedicated topics here — no filtering needed, unlike
|
||||
setups where many devices might share one topic.
|
||||
|
||||
- `cert/enroll/<device_id>/issued` — retained. Payload:
|
||||
|
||||
```json
|
||||
{
|
||||
"cert": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n",
|
||||
"ca": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n"
|
||||
}
|
||||
```
|
||||
|
||||
Because this is retained, if the device subscribes *after* a cert was
|
||||
already issued (e.g. after a reboot), it will receive it immediately
|
||||
without needing to re-request.
|
||||
|
||||
- `cert/enroll/<device_id>/rejected` — not retained. Payload:
|
||||
|
||||
```json
|
||||
{ "reason": "human-readable reason" }
|
||||
```
|
||||
|
||||
- `cert/enroll/<device_id>/revoked` — not retained, best-effort only.
|
||||
Payload:
|
||||
|
||||
```json
|
||||
{ "reason": "human-readable reason" }
|
||||
```
|
||||
|
||||
Sent if you revoke a device's cert after it was issued. This is
|
||||
informational — actual enforcement happens at the TLS layer via
|
||||
Mosquitto's CRL check, which a revoked device will hit on its *next*
|
||||
@@ -93,6 +125,7 @@ Topic: `cert/enroll/<device_id>/renew`
|
||||
QoS: 1, retain: false
|
||||
|
||||
Payload (JSON):
|
||||
|
||||
```json
|
||||
{
|
||||
"csr": "-----BEGIN CERTIFICATE REQUEST-----\n...\n-----END CERTIFICATE REQUEST-----\n",
|
||||
|
||||
@@ -23,20 +23,60 @@ CA_COMMON_NAME = "Home Assistant Local MQTT CA"
|
||||
CA_VALIDITY_YEARS = 20
|
||||
|
||||
|
||||
def extract_csr_common_name(csr_pem: str):
|
||||
"""Return the CN the CSR itself requests, or None if it has none /
|
||||
doesn't parse. Lets a device declare its own identity independent of
|
||||
whatever MQTT topic segment the request arrived on."""
|
||||
try:
|
||||
csr = x509.load_pem_x509_csr(csr_pem.encode())
|
||||
attrs = csr.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
|
||||
return attrs[0].value if attrs else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def extract_cert_common_name(cert_pem: str):
|
||||
"""Return the CN of an already-issued cert, or None if it has none /
|
||||
doesn't parse. Used so renewal can keep a device's identity stable
|
||||
across reissuance regardless of what the new request claims."""
|
||||
try:
|
||||
cert = x509.load_pem_x509_certificate(cert_pem.encode())
|
||||
attrs = cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)
|
||||
return attrs[0].value if attrs else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
class CertificateAuthority:
|
||||
def __init__(self):
|
||||
def __init__(self, organization: str = "", organizational_unit: str = ""):
|
||||
# Not hardcoded: these come from add-on options (default empty,
|
||||
# meaning "omit entirely" — the subject stays CN-only, same as
|
||||
# before this existed). If set, they're applied consistently to
|
||||
# every cert this CA issues: the root CA itself, the broker cert,
|
||||
# and every device client cert.
|
||||
self.organization = organization
|
||||
self.organizational_unit = organizational_unit
|
||||
os.makedirs(CA_DIR, exist_ok=True)
|
||||
if not (os.path.exists(CA_KEY_PATH) and os.path.exists(CA_CERT_PATH)):
|
||||
self._generate_root_ca()
|
||||
self._load_root_ca()
|
||||
|
||||
def _build_name(self, common_name: str) -> x509.Name:
|
||||
attrs = []
|
||||
if self.organization:
|
||||
attrs.append(x509.NameAttribute(NameOID.ORGANIZATION_NAME, self.organization))
|
||||
if self.organizational_unit:
|
||||
attrs.append(
|
||||
x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, self.organizational_unit)
|
||||
)
|
||||
attrs.append(x509.NameAttribute(NameOID.COMMON_NAME, common_name))
|
||||
return x509.Name(attrs)
|
||||
|
||||
# -- setup ---------------------------------------------------------
|
||||
|
||||
def _generate_root_ca(self):
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
subject = issuer = x509.Name(
|
||||
[x509.NameAttribute(NameOID.COMMON_NAME, CA_COMMON_NAME)]
|
||||
)
|
||||
subject = issuer = self._build_name(CA_COMMON_NAME)
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
cert = (
|
||||
x509.CertificateBuilder()
|
||||
@@ -95,9 +135,14 @@ class CertificateAuthority:
|
||||
def ca_cert_pem(self) -> str:
|
||||
return self.cert_pem.decode()
|
||||
|
||||
def sign_csr(self, csr_pem: str, device_id: str, validity_days: int) -> str:
|
||||
def sign_csr(self, csr_pem: str, common_name: str, validity_days: int) -> str:
|
||||
"""Validate and sign a device CSR. Returns the signed cert as PEM.
|
||||
|
||||
`common_name` is deliberately NOT tied to any MQTT topic/device_id
|
||||
here -- callers decide where it comes from (see
|
||||
extract_csr_common_name / extract_cert_common_name below, and
|
||||
main.py's resolution order).
|
||||
|
||||
Raises ValueError on a malformed or untrustworthy CSR.
|
||||
"""
|
||||
try:
|
||||
@@ -109,7 +154,7 @@ class CertificateAuthority:
|
||||
raise ValueError("CSR signature is invalid")
|
||||
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, device_id)])
|
||||
subject = self._build_name(common_name)
|
||||
|
||||
builder = (
|
||||
x509.CertificateBuilder()
|
||||
@@ -139,7 +184,7 @@ class CertificateAuthority:
|
||||
critical=False,
|
||||
)
|
||||
.add_extension(
|
||||
x509.SubjectAlternativeName([x509.DNSName(device_id)]),
|
||||
x509.SubjectAlternativeName([x509.DNSName(common_name)]),
|
||||
critical=False,
|
||||
)
|
||||
)
|
||||
@@ -159,7 +204,7 @@ class CertificateAuthority:
|
||||
|
||||
key = ec.generate_private_key(ec.SECP256R1())
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, hostnames[0])])
|
||||
subject = self._build_name(hostnames[0])
|
||||
|
||||
san_entries = []
|
||||
for name in hostnames:
|
||||
|
||||
@@ -8,7 +8,7 @@ import time
|
||||
from flask import Flask, jsonify, render_template, request
|
||||
|
||||
import store
|
||||
from ca import CertificateAuthority
|
||||
from ca import CertificateAuthority, extract_cert_common_name, extract_csr_common_name
|
||||
from mqtt_worker import MqttWorker
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(message)s")
|
||||
@@ -31,8 +31,10 @@ def load_options():
|
||||
"mqtt_password": "",
|
||||
"request_topic_prefix": "cert/enroll",
|
||||
"cert_validity_days": 825,
|
||||
"broker_hostnames": "core-mosquitto,localhost",
|
||||
"broker_hostnames": "homeassistant.local,192.168.1.80, core-mosquitto,localhost",
|
||||
"renewal_window_days": 30,
|
||||
"cert_organization": "",
|
||||
"cert_organizational_unit": "",
|
||||
}
|
||||
if os.path.exists(OPTIONS_PATH):
|
||||
with open(OPTIONS_PATH) as f:
|
||||
@@ -41,7 +43,10 @@ def load_options():
|
||||
|
||||
|
||||
options = load_options()
|
||||
ca = CertificateAuthority()
|
||||
ca = CertificateAuthority(
|
||||
organization=options["cert_organization"],
|
||||
organizational_unit=options["cert_organizational_unit"],
|
||||
)
|
||||
app = Flask(__name__)
|
||||
|
||||
# Guard: this server has no login of its own. It relies entirely on only
|
||||
@@ -138,16 +143,31 @@ def write_crl():
|
||||
log.info("wrote CRL with %d revoked cert(s) to %s", len(entries), crl_path)
|
||||
|
||||
|
||||
def resolve_common_name(device_id: str, csr_pem: str) -> str:
|
||||
"""CN comes from the CSR itself -- devices set it there deliberately,
|
||||
often shared across a whole device category (e.g. all TH sensors use
|
||||
one CN, all light sensors another) for ACL grouping purposes. This
|
||||
is intentionally NOT unique per device, unlike device_id.
|
||||
|
||||
Falls back to device_id only if the CSR has no CN at all (malformed
|
||||
or lazy firmware) -- a safety net, not the intended path."""
|
||||
from_csr = extract_csr_common_name(csr_pem)
|
||||
return from_csr or device_id
|
||||
|
||||
|
||||
def handle_request(device_id, csr_pem, meta):
|
||||
store.add_pending(device_id, csr_pem, meta)
|
||||
|
||||
|
||||
def finalize_issuance(device_id: str, csr_pem: str, state=None):
|
||||
def finalize_issuance(device_id: str, csr_pem: str, common_name: str, state=None):
|
||||
"""Sign a CSR, record it, and deliver it. Shared by manual approval
|
||||
and the auto-renewal fast path so both stay in sync."""
|
||||
and the auto-renewal fast path so both stay in sync. `common_name`
|
||||
is resolved by the caller -- see resolve_common_name for fresh
|
||||
issuance, and handle_renew's own logic for renewals (which must NOT
|
||||
use CSR-based resolution -- it always keeps the existing CN)."""
|
||||
from cryptography import x509
|
||||
|
||||
cert_pem = ca.sign_csr(csr_pem, device_id, int(options["cert_validity_days"]))
|
||||
cert_pem = ca.sign_csr(csr_pem, common_name, int(options["cert_validity_days"]))
|
||||
leaf = x509.load_pem_x509_certificate(cert_pem.encode())
|
||||
not_after = leaf.not_valid_after_utc.isoformat()
|
||||
store.mark_issued(device_id, cert_pem, not_after, leaf.serial_number, state=state)
|
||||
@@ -162,7 +182,15 @@ def handle_renew(device_id, csr_pem, timestamp, signature_b64, meta):
|
||||
Any failure falls back to the ordinary manual-approval queue —
|
||||
exactly as if this were a first-time request — rather than being
|
||||
silently dropped, so a legitimate device with e.g. clock skew still
|
||||
gets a cert eventually, just with human review."""
|
||||
gets a cert eventually, just with human review.
|
||||
|
||||
CN handling for renewal is intentionally NOT the same as fresh
|
||||
issuance: the renewed cert always keeps whatever CN the device's
|
||||
CURRENT on-record cert already has. A renewal CSR's own CN (or any
|
||||
other claimed identity) is never consulted -- renewal is about
|
||||
extending validity / rotating keys, not about redefining who a
|
||||
device is. Changing identity requires a fresh, humanly-approved
|
||||
enrollment, not a renewal."""
|
||||
|
||||
def fall_back_to_manual(why):
|
||||
log.info("renewal from %s falling back to manual approval: %s", device_id, why)
|
||||
@@ -172,8 +200,8 @@ def handle_renew(device_id, csr_pem, timestamp, signature_b64, meta):
|
||||
fall_back_to_manual("device is revoked")
|
||||
return
|
||||
|
||||
issued = store.list_issued().get(device_id)
|
||||
if not issued:
|
||||
existing_issued = store.list_issued().get(device_id)
|
||||
if not existing_issued:
|
||||
fall_back_to_manual("no prior issued cert on record")
|
||||
return
|
||||
|
||||
@@ -187,12 +215,10 @@ def handle_renew(device_id, csr_pem, timestamp, signature_b64, meta):
|
||||
fall_back_to_manual("timestamp outside allowed skew window")
|
||||
return
|
||||
|
||||
not_after = datetime.datetime.fromisoformat(issued["not_after"])
|
||||
not_after = datetime.datetime.fromisoformat(existing_issued["not_after"])
|
||||
renewal_opens_at = not_after - datetime.timedelta(days=int(options["renewal_window_days"]))
|
||||
if datetime.datetime.now(datetime.timezone.utc) < renewal_opens_at:
|
||||
fall_back_to_manual(
|
||||
f"too early to renew (opens {renewal_opens_at.isoformat()})"
|
||||
)
|
||||
fall_back_to_manual(f"too early to renew (opens {renewal_opens_at.isoformat()})")
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -202,17 +228,24 @@ def handle_renew(device_id, csr_pem, timestamp, signature_b64, meta):
|
||||
return
|
||||
|
||||
message = f"{device_id}|{int(ts)}|renew".encode()
|
||||
if not ca.verify_renewal_proof(issued["cert"], message, signature):
|
||||
if not ca.verify_renewal_proof(existing_issued["cert"], message, signature):
|
||||
fall_back_to_manual("proof-of-possession signature did not verify")
|
||||
return
|
||||
|
||||
# Past every check: keep the EXISTING cert's CN, full stop. Never
|
||||
# derived from the new CSR for a renewal.
|
||||
preserved_common_name = extract_cert_common_name(existing_issued["cert"]) or device_id
|
||||
|
||||
try:
|
||||
_, new_not_after = finalize_issuance(device_id, csr_pem)
|
||||
_, new_not_after = finalize_issuance(device_id, csr_pem, preserved_common_name)
|
||||
except ValueError as exc:
|
||||
fall_back_to_manual(f"CSR rejected: {exc}")
|
||||
return
|
||||
|
||||
log.info("auto-renewed cert for %s (proof verified), now valid until %s", device_id, new_not_after)
|
||||
log.info(
|
||||
"auto-renewed cert for %s (proof verified), CN kept as %r, now valid until %s",
|
||||
device_id, preserved_common_name, new_not_after,
|
||||
)
|
||||
|
||||
|
||||
mqtt_worker = MqttWorker(
|
||||
@@ -237,12 +270,25 @@ def index():
|
||||
|
||||
@app.route("/api/pending")
|
||||
def api_pending():
|
||||
return jsonify(store.list_pending())
|
||||
pending = store.list_pending()
|
||||
enriched = {}
|
||||
for device_id, entry in pending.items():
|
||||
enriched[device_id] = dict(entry)
|
||||
# What CN WOULD be used if approved right now (from the CSR) --
|
||||
# purely for display, not stored, since it's cheap to recompute
|
||||
# and this way it's never stale.
|
||||
enriched[device_id]["resolved_common_name"] = resolve_common_name(device_id, entry["csr"])
|
||||
return jsonify(enriched)
|
||||
|
||||
|
||||
@app.route("/api/issued")
|
||||
def api_issued():
|
||||
return jsonify(store.list_issued())
|
||||
issued = store.list_issued()
|
||||
enriched = {}
|
||||
for device_id, entry in issued.items():
|
||||
enriched[device_id] = dict(entry)
|
||||
enriched[device_id]["common_name"] = extract_cert_common_name(entry["cert"])
|
||||
return jsonify(enriched)
|
||||
|
||||
|
||||
@app.route("/api/approve/<device_id>", methods=["POST"])
|
||||
@@ -251,12 +297,17 @@ def api_approve(device_id):
|
||||
if not pending:
|
||||
return jsonify({"error": "no pending request for that device"}), 404
|
||||
|
||||
common_name = resolve_common_name(device_id, pending["csr"])
|
||||
|
||||
try:
|
||||
_, not_after = finalize_issuance(device_id, pending["csr"], state=state)
|
||||
_, not_after = finalize_issuance(device_id, pending["csr"], common_name, state=state)
|
||||
except ValueError as exc:
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
return jsonify({"status": "issued", "device_id": device_id, "not_after": not_after})
|
||||
return jsonify({
|
||||
"status": "issued", "device_id": device_id,
|
||||
"common_name": common_name, "not_after": not_after,
|
||||
})
|
||||
|
||||
|
||||
@app.route("/api/reject/<device_id>", methods=["POST"])
|
||||
|
||||
@@ -8,6 +8,13 @@ Topics (prefix is configurable, default "cert/enroll"):
|
||||
<prefix>/<device_id>/rejected here -> node {"reason": "..."}
|
||||
<prefix>/<device_id>/revoked here -> node {"reason": "..."} (best-effort notice; see DEVICE_PROTOCOL.md)
|
||||
|
||||
device_id is expected to be unique per physical device (not a shared
|
||||
bootstrap identity) -- that's what makes per-device topics work without
|
||||
any extra filtering in the payload. The cert's CN is a separate concern,
|
||||
set from the CSR by main.py/ca.py, and may deliberately be shared across
|
||||
many devices (e.g. one CN per device category) -- that has no bearing on
|
||||
topic routing here.
|
||||
|
||||
See DEVICE_PROTOCOL.md for the full spec devices should implement.
|
||||
"""
|
||||
import json
|
||||
|
||||
@@ -14,6 +14,7 @@ async function refreshPending() {
|
||||
const meta = Object.entries(entry.meta || {}).map(([k, v]) => `${k}: ${v}`).join(", ");
|
||||
row.innerHTML = `
|
||||
<td>${deviceId}</td>
|
||||
<td>${entry.resolved_common_name}</td>
|
||||
<td>${requested}</td>
|
||||
<td>${meta || "-"}</td>
|
||||
<td>
|
||||
@@ -50,7 +51,7 @@ async function refreshIssued() {
|
||||
const action = isRevoked
|
||||
? `<span class="empty">revoked</span>`
|
||||
: `<button class="revoke" data-id="${deviceId}">Revoke</button>`;
|
||||
row.innerHTML = `<td>${deviceId}</td><td>${issued}</td><td>${expires}</td><td>${action}</td>`;
|
||||
row.innerHTML = `<td>${deviceId}</td><td>${entry.common_name}</td><td>${issued}</td><td>${expires}</td><td>${action}</td>`;
|
||||
tbody.appendChild(row);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
"""Simple JSON-file store for pending requests and issued cert records.
|
||||
|
||||
Keyed by device_id -- the unique per-device identifier from the MQTT
|
||||
topic path (cert/enroll/<device_id>/...). CN is deliberately NOT unique
|
||||
in this deployment (many devices share one CN per category, for ACL
|
||||
grouping), so it can't be used as a storage key -- device_id is the
|
||||
only thing guaranteed unique per physical device.
|
||||
|
||||
A real deployment could swap this for sqlite, but request volume here is
|
||||
tiny (one entry per physical device) so a flat file is fine and easy to
|
||||
inspect/back up.
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
<section>
|
||||
<h2>Pending requests</h2>
|
||||
<table id="pending-table">
|
||||
<thead><tr><th>Device</th><th>Requested</th><th>Info</th><th></th></tr></thead>
|
||||
<thead><tr><th>Device</th><th>CN</th><th>Requested</th><th>Info</th><th></th></tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
<p id="pending-empty" class="empty" style="display:none">No pending requests. Nodes that ask for a certificate will show up here.</p>
|
||||
@@ -20,7 +20,7 @@
|
||||
<section>
|
||||
<h2>Issued certificates</h2>
|
||||
<table id="issued-table">
|
||||
<thead><tr><th>Device</th><th>Issued</th><th>Expires</th><th></th></tr></thead>
|
||||
<thead><tr><th>Device</th><th>CN</th><th>Issued</th><th>Expires</th><th></th></tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
<p id="issued-empty" class="empty" style="display:none">No certificates issued yet.</p>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
name: "MQTT Certificate Manager"
|
||||
version: "0.4.0"
|
||||
version: "0.4.2"
|
||||
slug: "mqtt_cert_manager"
|
||||
description: "Local CA that issues and manages TLS client certificates for MQTT nodes"
|
||||
url: "https://gitea.viratak.com/bitopa/mqtt-cert-manager"
|
||||
@@ -42,8 +42,10 @@ options:
|
||||
mqtt_password: ""
|
||||
request_topic_prefix: "cert/enroll"
|
||||
cert_validity_days: 825
|
||||
broker_hostnames: "core-mosquitto,localhost"
|
||||
broker_hostnames: "homeassistant.local,192.168.1.80,core-mosquitto,localhost"
|
||||
renewal_window_days: 30
|
||||
cert_organization: "Viratak Telecommunications"
|
||||
cert_organizational_unit: "Cloudihome"
|
||||
|
||||
schema:
|
||||
mqtt_host: str
|
||||
@@ -54,3 +56,5 @@ schema:
|
||||
cert_validity_days: int(30,3650)
|
||||
broker_hostnames: str
|
||||
renewal_window_days: int(1,365)
|
||||
cert_organization: str?
|
||||
cert_organizational_unit: str?
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# Changelog
|
||||
|
||||
## 0.1.0
|
||||
|
||||
- Initializing the Application
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- Added app icon
|
||||
- Improved app configuration
|
||||
|
||||
## 0.2.1
|
||||
|
||||
- Fixed app icon
|
||||
|
||||
## 0.2.2
|
||||
|
||||
- Minor bug fix
|
||||
|
||||
## 0.2.3
|
||||
|
||||
- Minor bug fix
|
||||
|
||||
## 0.2.4
|
||||
|
||||
- Minor bug fix
|
||||
|
||||
## 0.2.5
|
||||
|
||||
- Minor bug fix
|
||||
|
||||
## 0.3.0
|
||||
|
||||
- Added separated ACL's
|
||||
- Improved logging capabilities
|
||||
@@ -0,0 +1,5 @@
|
||||
FROM eclipse-mosquitto:2
|
||||
RUN apk add --no-cache jq
|
||||
COPY run.sh /run.sh
|
||||
RUN chmod a+x /run.sh
|
||||
CMD ["/run.sh"]
|
||||
@@ -0,0 +1,61 @@
|
||||
# Visquitto
|
||||
|
||||
Visquitto is a simple Mosquitto broker setup intended to run on a separate port and be used alongside [mqtt-cert-manager](../mqtt-cert-manager) and custom MQTT nodes.
|
||||
|
||||
This is not a full certificate-management platform or a Home Assistant-only app. It is a lightweight broker instance for local MQTT traffic, designed to coexist with [mqtt-cert-manager](../mqtt-cert-manager) and custom client code.
|
||||
|
||||
## What it is
|
||||
|
||||
- A standard Mosquitto broker
|
||||
- Configured for a dedicated port, separate from the default broker
|
||||
- Meant to be used alongside [mqtt-cert-manager](../mqtt-cert-manager) and custom MQTT nodes
|
||||
- Intended for local/private network use
|
||||
|
||||
## Why use it
|
||||
|
||||
If you want a second MQTT broker for a specific project, workflow, or device group, Visquitto gives you:
|
||||
|
||||
- a clean, separate broker port
|
||||
- a simple local MQTT endpoint for custom nodes and devices
|
||||
- isolation from your main broker traffic
|
||||
- an easy way to pair it with your own app logic
|
||||
|
||||
## Typical setup
|
||||
|
||||
Visquitto is designed to be used like this:
|
||||
|
||||
- Your main app runs normally
|
||||
- Custom nodes or devices connect to the Visquitto broker
|
||||
- The broker listens on its own port instead of the default Mosquitto port
|
||||
- Traffic is kept separate from the primary broker environment
|
||||
|
||||
## Requirements
|
||||
|
||||
- A machine/container/environment capable of running Mosquitto
|
||||
- A separate port for the broker
|
||||
- Your own app and custom MQTT clients/nodes
|
||||
- Local or private network access as needed
|
||||
|
||||
## Configuration
|
||||
|
||||
Common settings include:
|
||||
|
||||
- broker port
|
||||
- listener configuration
|
||||
- allow/deny rules if needed
|
||||
- persistence settings
|
||||
- logging options
|
||||
- TLS settings if you choose to enable them
|
||||
|
||||
This project is intentionally minimal: it provides a broker for your other app and custom nodes rather than trying to manage a larger certificate or onboarding system.
|
||||
|
||||
## Notes
|
||||
|
||||
- This is a plain Mosquitto-based broker setup
|
||||
- It is meant to complement another app, not replace it
|
||||
- It is best suited for local experiments, custom node integrations, and paired app workflows
|
||||
- If you are using TLS or custom auth, configure it explicitly for your environment
|
||||
|
||||
## License
|
||||
|
||||
Please check the repository license file for usage terms if one is included in the project.
|
||||
@@ -0,0 +1,39 @@
|
||||
name: Visquitto
|
||||
version: "0.3.0"
|
||||
slug: visquitto
|
||||
description: Second private Mosquitto broker for bitopa nodes
|
||||
arch:
|
||||
- amd64
|
||||
init: false
|
||||
startup: services
|
||||
boot: auto
|
||||
ports:
|
||||
1883/tcp: 1993
|
||||
8883/tcp: 9993
|
||||
ports_description:
|
||||
1883/tcp: MQTT (plain)
|
||||
8883/tcp: MQTT over TLS
|
||||
map:
|
||||
- addon_config:rw
|
||||
- share:rw
|
||||
- ssl:ro
|
||||
options:
|
||||
users: []
|
||||
log_dest: []
|
||||
log_type: []
|
||||
nodes: []
|
||||
require_certificate: false
|
||||
cafile: mqtt-cert-manager-ca.crt
|
||||
certfile: mosquitto-server.crt
|
||||
keyfile: mosquitto-server.key
|
||||
schema:
|
||||
users:
|
||||
- username: str
|
||||
password: password
|
||||
nodes:
|
||||
log_dest: []
|
||||
log_type: []
|
||||
require_certificate: false
|
||||
cafile: str
|
||||
certfile: str
|
||||
keyfile: str
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,155 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
umask 077
|
||||
|
||||
CONFIG=/config
|
||||
SHARE=/share/visquitto
|
||||
DATA=/data/mosquitto
|
||||
PASSWD=/data/passwd
|
||||
CERTDIR=/data/certs
|
||||
|
||||
mkdir -p "$SHARE" "$DATA" "$CERTDIR"
|
||||
chown -R mosquitto:mosquitto "$DATA"
|
||||
|
||||
CAFILE=$(jq -r '.cafile' /data/options.json)
|
||||
CERTFILE=$(jq -r '.certfile' /data/options.json)
|
||||
KEYFILE=$(jq -r '.keyfile' /data/options.json)
|
||||
|
||||
# ---- Check plugins exist ----
|
||||
for p in /usr/lib/mosquitto_acl_file.so /usr/lib/mosquitto_password_file.so; do
|
||||
[ -f "$p" ] || { echo "Missing plugin $p" >&2; exit 1; }
|
||||
done
|
||||
|
||||
# ---- Certificates: copied at every start, readable by mosquitto ----
|
||||
for f in "$CAFILE" "$CERTFILE" "$KEYFILE"; do
|
||||
[ -f "/ssl/$f" ] || { echo "Missing /ssl/$f" >&2; exit 1; }
|
||||
done
|
||||
|
||||
cp "/ssl/$CAFILE" "$CERTDIR/ca.pem"
|
||||
cp "/ssl/$CERTFILE" "$CERTDIR/cert.pem"
|
||||
cp "/ssl/$KEYFILE" "$CERTDIR/key.pem"
|
||||
chown -R mosquitto:mosquitto "$CERTDIR"
|
||||
chmod 644 "$CERTDIR/ca.pem" "$CERTDIR/cert.pem"
|
||||
chmod 600 "$CERTDIR/key.pem"
|
||||
|
||||
# ---- Defaults in /config (regenerated at every start) ----
|
||||
cat > "$CONFIG/mosquitto.conf" <<EOF
|
||||
protocol mqtt
|
||||
allow_anonymous false
|
||||
|
||||
log_dest stdout
|
||||
log_type error
|
||||
log_type warning
|
||||
log_type notice
|
||||
log_timestamp_format %Y-%m-%d %H:%M:%S
|
||||
|
||||
persistence true
|
||||
persistence_location $DATA/
|
||||
max_queued_messages 8192
|
||||
|
||||
plugin_load acl_file /usr/lib/mosquitto_acl_file.so
|
||||
plugin_load password_file /usr/lib/mosquitto_password_file.so
|
||||
|
||||
include_dir $SHARE
|
||||
|
||||
# Plain listener (host port 1993): password users only
|
||||
listener 1883
|
||||
protocol mqtt
|
||||
plugin_use password_file
|
||||
plugin_opt_password_file $PASSWD
|
||||
plugin_use acl_file
|
||||
plugin_opt_acl_file $DATA/acl_plain
|
||||
|
||||
# TLS listener (host port 9993): client certificate required
|
||||
listener 8883
|
||||
protocol mqtt
|
||||
cafile $CERTDIR/ca.pem
|
||||
certfile $CERTDIR/cert.pem
|
||||
keyfile $CERTDIR/key.pem
|
||||
tls_version tlsv1.2
|
||||
require_certificate true
|
||||
use_identity_as_username true
|
||||
plugin_use password_file
|
||||
plugin_opt_password_file $PASSWD
|
||||
plugin_use acl_file
|
||||
plugin_opt_acl_file $DATA/acl_tls
|
||||
EOF
|
||||
|
||||
# plain ACL
|
||||
echo "# Default ACL for the plain listener: no rules, all access denied" > "$CONFIG/acl_plain"
|
||||
cat > "$CONFIG/acl_plain" <<EOF
|
||||
# ============================================================
|
||||
# Not certified devices
|
||||
# ============================================================
|
||||
user hamqtt
|
||||
|
||||
# Test topic
|
||||
topic readwrite test
|
||||
# Initial enrollment
|
||||
topic write cert/enroll/+/request
|
||||
topic read cert/enroll/+/issued
|
||||
|
||||
# ============================================================
|
||||
# Certificate manager
|
||||
# ============================================================
|
||||
user viracert
|
||||
|
||||
topic read cert/enroll/+/request
|
||||
topic write cert/enroll/+/issued
|
||||
topic read cert/enroll/+/renew
|
||||
EOF
|
||||
|
||||
# TLS ACL
|
||||
echo "# Default ACL for the TLS listener: no rules, all access denied" > "$CONFIG/acl_tls"
|
||||
cat > "$CONFIG/acl_tls" <<EOF
|
||||
# Default rule for every certificate client. %u is the certificate CN.
|
||||
pattern readwrite clients/%u/#
|
||||
EOF
|
||||
|
||||
# ---- User customization in /share (created once, never overwritten) ----
|
||||
if [ ! -f "$SHARE/mosquitto.conf" ]; then
|
||||
echo "# Extra global Mosquitto options (loaded with include_dir, before the listeners)" > "$SHARE/mosquitto.conf"
|
||||
fi
|
||||
|
||||
if [ ! -f "$SHARE/acl_plain" ]; then
|
||||
cat > "$SHARE/acl_plain" <<EOF
|
||||
# Extra ACL rules for the plain listener, appended to the default, for example:
|
||||
# user enroll
|
||||
# topic write certs/request/#
|
||||
# topic read certs/response/#
|
||||
EOF
|
||||
fi
|
||||
|
||||
if [ ! -f "$SHARE/acl_tls" ]; then
|
||||
cat > "$SHARE/acl_tls" <<EOF
|
||||
# Extra ACL rules for the TLS listener (user = certificate CN), appended to the default, for example:
|
||||
# user hamt
|
||||
# topic read broadcast/#
|
||||
EOF
|
||||
fi
|
||||
|
||||
chmod 644 "$SHARE/mosquitto.conf"
|
||||
chmod 600 "$SHARE/acl_plain" "$SHARE/acl_tls"
|
||||
|
||||
# ---- Merge defaults + user ACLs into the files Mosquitto reads ----
|
||||
{ cat "$CONFIG/acl_plain"; echo; cat "$SHARE/acl_plain"; echo; } > "$DATA/acl_plain"
|
||||
{ cat "$CONFIG/acl_tls"; echo; cat "$SHARE/acl_tls"; echo; } > "$DATA/acl_tls"
|
||||
|
||||
for f in "$DATA/acl_plain" "$DATA/acl_tls"; do
|
||||
chown mosquitto:mosquitto "$f"
|
||||
chmod 600 "$f"
|
||||
done
|
||||
|
||||
# ---- Users from the panel ----
|
||||
rm -f "$PASSWD"
|
||||
touch "$PASSWD"
|
||||
jq -r '.users[] | [.username, .password] | @tsv' /data/options.json |
|
||||
while IFS="$(printf '\t')" read -r user pass; do
|
||||
mosquitto_passwd -b "$PASSWD" "$user" "$pass"
|
||||
done
|
||||
chown mosquitto:mosquitto "$PASSWD"
|
||||
chmod 0700 "$PASSWD"
|
||||
|
||||
[ -s "$PASSWD" ] || echo "Warning: no users defined, nobody can log in on the plain listener" >&2
|
||||
|
||||
exec mosquitto -c "$CONFIG/mosquitto.conf"
|
||||
Reference in New Issue
Block a user