Search and contents

The Node's MQTT broker

Every Kindred appliance runs its own Mosquitto. The Node publishes its Activity Log events, a retained message saying who it is and a retained count of what is waiting for a person to it over a Unix socket, and remote subscribers read them over a TLS port. deployment/configure_mosquitto.sh sets all of this up; provision_node.sh runs it for you. This page says what it does, how to run it yourself, and how the pieces stay safe.

What the certificates must be

The broker's network listener is only as good as the certificates behind it:

  • A CA, not a lab pin. The trust bundle must hold CA certificates. A lab certificate (create_lab_certificate.sh) pins a self-signed leaf, which is not a CA, so configure_mosquitto.sh refuses it ("not a usable CA"). The lab flow is for a Node on its own; a broker with a network listener needs the site CA or an external CA.
  • A name clients can verify. BrokerConnection verifies the broker's certificate and hostname. Issue the broker Node's certificate with --dns and/or --ip for every name or address a subscriber will connect to (issue_node_certificate.sh <site> <node> --dns broker.plant.lan --ip 10.0.0.5); one issued with no SAN carries only the identity URI, and a client connecting by host or IP will refuse it, with the verification error in last_error.
  • Through an intermediate. A node.crt holding the leaf then its intermediates, with only the root in the bundle, is supported (install_node_certificate.sh --chain).

What you get

ListenerWho may connectWhat they may do
Unix socket /run/kindred-mqtt/mqtt.sock Local accounts in the kindred group (the Kindred service user is added to it). No password. Publish to the Activity Log topic (kindred/activity_log), the identity topic (kindred/node_identity) and the pending-count topic (kindred/pending_summary). It can read nothing, and every other topic is refused
TLS port (default 8883) A client presenting a certificate signed by the site CA. No anonymous client, no password. Read the Activity Log topic (kindred/activity_log), the identity topic (kindred/node_identity) and the pending-count topic (kindred/pending_summary); every other topic is refused. A network client can never publish, so it cannot forge an event, an announcement or a count

Who may open the socket is decided by file permissions, not by a password: Mosquitto has no socket-mode option, so the script makes /run/kindred-mqtt owned by mosquitto:kindred with mode 2750 (setgid), and the socket inherits the group. A tmpfiles rule recreates the directory at boot.

The username a network client gets is the CN of its certificate. Access is not per identity: any certificate that chains to the site CA may read the three topics.

The Node finds the socket through MQTT_SOCKET_PATH, which provision_node.sh writes. With it unset, the Node publishes over TCP to the broker named by MQTT_HOST and MQTT_PORT, as before.

Running it

Run it after install_mosquitto.sh, on the appliance, as root or as a sudo-capable user:

deployment/configure_mosquitto.sh --service-user kindred-svc

Without a node certificate it configures only the socket listener and says so. Once the certificate exists (see site-pki.md), run it again and it adds the network listener. Re-running when nothing has changed changes nothing and does not restart the broker. The script generates no secret.

An appliance configured before the identity topic or the pending-count topic existed must run the script again after an upgrade. Until it does, its socket access list does not let the Node publish the topic that is missing, and Mosquitto drops a publish it does not allow without telling the client. The Node starts and runs normally and logs no error. Without the identity rule it announces nothing, so a roster reader finds that broker reachable and holding no announcement. With the identity rule and without the pending-count rule it announces itself and its counts never arrive, so a reader finds the Node with no counts. The re-run adds the missing topics to the socket access list (and to the network access list when the appliance has a network listener), restarts the broker once, and the Node's next connection publishes them. A second run changes nothing.

Refused on a development host: the repo's tests use that host's anonymous broker on port 1883, which the script removes. A host whose PRODUCTION_MODE is false, or whose Mosquitto already has a listener or anonymous access configured, is refused unless KINDRED_FORCE=1.

Telling the broker which CA to trust

The Kindred service user is not trusted with the trust anchor. The CA the broker trusts for client certificates is set only when an administrator runs the script, and is stored root-owned. The first time, and whenever the node's trust bundle differs from the installed one, look at what you are accepting and then accept exactly that:

deployment/configure_mosquitto.sh --service-user kindred-svc --print-trust-bundle-sha256
deployment/configure_mosquitto.sh --service-user kindred-svc --trust-bundle-sha256 <hash shown>

After a CA replacement, run it again with the new hash; nothing the service user does can move the anchor.

Other options

--network-port and --bind set the TLS listener's port and address. --drop-network-listener removes the network listener, the broker's copy of the node key and the trust anchor stored with it; without it, missing certificate files are an error, never a silent downgrade.

--autosave-interval SECONDS sets how often the broker saves its retained messages to disk (default 60, at least 1; see What survives a restart). A run without the option keeps the interval the installed configuration already has (the first run on a broker sets 60), and says so, so re-running provisioning does not restart the broker to put 60 back. --network-port behaves the same way. Running again with the same value changes nothing; a different value rewrites the broker's configuration and restarts it, which drops every Node's connection until it reconnects.

--persistent-client-expiration DAYS (default 7, 1 to 3650) and --max-queued-messages COUNT (default 1000, 1 to 1000000) bound what persistence keeps beyond the two retained messages (see What persistence keeps besides the retained messages). They are kept between runs like the interval, and a changed value rewrites the configuration and restarts the broker.

What survives a restart

Two messages are retained on a Node's broker:

  • The identity announcement, on kindred/node_identity. It holds the Node's Node Type, instance id, version, start time, whether it is online, and its management API address if it has one that others can reach.

  • The pending-count message, on kindred/pending_summary. It holds:

    • how many sign-off records and identity matches are waiting for a person;
    • how many alerts are unacknowledged (a number, 0 included, on a Node whose config has an instruction_bindings section, and null on one without);
    • when the oldest of the three was created;
    • when the counts were taken (as_of), and the interval at which the Node refreshes them.

    It names the Node it belongs to and holds counts and timestamps only, never a record's content.

The Activity Log topic is not retained. A subscriber sees only the events published while it is connected, and a restart does not bring any back. (Persistence saves the whole of the broker's state, so a subscriber of your own that asks the broker to keep its session has the messages queued for it kept across a restart too. Kindred's own connections to this broker do not ask for that.)

Where it saves. The configuration turns on Mosquitto's persistence and names how often it saves.

  • The directory it saves into is the distribution's own (persistence_location in its main configuration, /var/lib/mosquitto/ on the Ubuntu package). Kindred's configuration names none, because Mosquitto refuses a second one.
  • The script warns when it finds no persistence_location in the broker's own configuration, since the messages would then not be kept across a restart.
  • The interval in force is 60 seconds unless the script was run with --autosave-interval.
What happens to the brokerWhat the retained message is afterwards
A controlled restart (systemctl restart mosquitto, a package upgrade, the script's own restart) Both messages are kept, whatever the interval: the broker saves as it stops. The identity message is offline for every Node that was connected, because the broker sends each Node's Last Will as it stops, and it stays so until the Node reconnects and announces online again, a few seconds later (its first retry is after 1 second and the wait grows to at most 10). The pending-count message has no Last Will: it keeps the last counts, which are stale by then, and the Node replaces it when it reconnects
A crash, or a power loss that takes the broker down The broker's last autosave, so at most one interval of changes is lost and no Last Will is sent. A Node that published inside that interval has no message until it reconnects; a Node that is still running does so by itself
The appliance is off, or the broker cannot be reached Nothing can be read; the messages on the broker's disk are what the next start loads

What persistence keeps besides the retained messages

Persistence saves every client's persistent session and the messages queued for it, not only the two retained messages. Kindred's own connections ask for no persistent session, so this concerns a subscriber of your own that does, and then never returns. The configuration bounds it two ways:

SettingDefaultWhat it bounds
persistent_client_expiration 7 days How long the broker keeps the saved session of a persistent client that has not come back; after that it forgets the client
max_queued_messages 1000 The most QoS 1 and 2 messages queued for one client that is not connected

Nothing that Kindred itself connects with is affected. One limit of the broker itself, seen on Mosquitto 2.0.18 with the configuration Kindred renders (per_listener_settings true): the broker queued no message for a client that was away, with or without max_queued_messages, so a subscriber of your own that leaves does not receive what was published meanwhile and costs the broker its session and not a queue. The expiration is what bounds that. If you need a subscriber to be given what it missed, read the Activity Log from its database and do not rely on the broker to hold it.

Retiring a Node: clearing its message

A Node's identity announcement and its pending counts stay on the broker after the Node is gone, so it stays on every roster with its last word (offline, or online after a crash) until something removes the message. A Node re-provisioned under a new instance id stays listed under the old one in the same way. With the Node stopped, on its own appliance and as the service user:

python3 -m engine.clear_node_announcement

publishes an empty retained message to kindred/node_identity and kindred/pending_summary, which is how Mosquitto removes one, and a reader that connects afterwards no longer lists the Node. It cannot read the topics, so it does not check whose message it removes: a broker holds one identity message, the last one announced, and on a broker that several Nodes share it removes whichever that was. If the broker cannot be reached it exits 1, says that nothing was cleared, and prints the by-hand command for your broker, for example:

mosquitto_pub --unix /run/kindred-mqtt/mqtt.sock -t kindred/node_identity -r -n
mosquitto_pub --unix /run/kindred-mqtt/mqtt.sock -t kindred/pending_summary -r -n

A caller that is tearing a Node down can carry on after a 1: nothing else waits on it. A Node that was removed by hand, with nothing run, lingers on the roster until its message is cleared this way or the same instance id announces again. A running Node announces itself again at its next connection, so stop it first.

How the Node refreshes its messages

The Node publishes its announcement on every connection to the broker, not only when it starts, so a broker that lost its message is repaired by the Node's next reconnect. It publishes the identity message on no timer: the message is not refreshed while the connection stays up, so its age says nothing about whether the Node is alive.

The pending-count message is different. The Node publishes it on every connection, right after the announcement, and again every interval, whether or not a count changed, and each time it carries a new as_of. Its age therefore does say whether the Node is alive: a message whose as_of is older than three of its own intervals comes from a Node that has stopped publishing, however online the identity message still says. That is what lets a reader tell a stale online left by a broker crash from a live one, and the roster reader below does. The interval is 60 seconds unless the Node's environment or its .env sets PENDING_SUMMARY_HEARTBEAT_SECONDS, a whole number of seconds from 1 to 86400; a Node refuses to start on any other value. The Node re-reads its counts from its database at each tick, so a record resolved through the management API shows in a later message, within one interval. A Node that cannot read its database publishes nothing for that tick, so as_of stops advancing, and it never publishes a zero for a count it could not read.

Reading the roster

What the roster reader (python3 -m engine.node_roster) shows for each case, in the order a reader meets them:

The reader findsIt shows
The broker answers and the Node's message says online online
The broker answers and the message says offline (a clean stop, a killed process, or a controlled broker restart not yet followed by the Node's reconnect) offline
The broker does not answer unknown for every Node behind it, whatever the message it last held said
The broker answers and holds no announcement (a new broker; a crash that lost the message; a Node not yet reconnected after a restart that saved nothing; an appliance that was not re-run, above) that broker is listed as announcing nothing, with no Node row
The broker answers after a crash, and its last autosave holds an online message for a Node that is no longer running online. The reader cannot tell from that message: the broker answers and the message says so, and no Last Will was sent. It stays until that Node is started again and replaces it. The Node's counts are what give it away, as the next table shows

Two limits of the roster reader are accepted, and this is what a reader sees for each:

  • A broker that reaches the Node over a half-open TCP connection (a cable pull, a hung process; not the Unix socket, where the broker sees a killed process's close at once) can send the old connection's Last Will after the new connection's online message, so the Node reads offline while it is running. Nothing repairs it until the Node's next reconnect. The roster reader's counts then read as unknown (node not online).
  • A broker crash sends no Last Will and its last autosave may hold online, so a dead Node reads online until it starts again. There is no heartbeat to age the message. Its counts give it away: the message's as_of stops moving and the row reads stale after three intervals.

A Node stopped while its broker is stopped cleanly does not look online afterwards, because the broker sent its Last Will as it went down; only a crash leaves a stale online behind.

Pending counts on the roster

The same command joins each Node's pending counts to its row, by instance id, on the broker that held both. It shows a Node's counts only while that Node is online and its count message is fresh, and otherwise shows them as unknown, with the reason (in --json, pending.state):

The reader findspending.stateIt prints
The Node is online and its count message is fresh shown The counts: sign-offs, identity matches and unacknowledged alerts, and how long ago the oldest of them was created, worked out from the reader's own clock and left out when nothing is waiting. Alerts read unknown while the Node has no alert source, never 0
The broker holds no count message for the Node, whether the Node is online or not (an appliance that was not re-run, above, or a Node that has not yet published) not announced pointer not announced. This is neither zero nor unknown
The broker holds a count message for the Node, but the Node is offline, whatever the message said node not online unknown (node not online). The last retained numbers are never shown
The broker that held the Node's count message does not answer broker not answering unknown (broker not answering). The Node may be running: nothing says it is down, and the last retained numbers are never shown
The Node is online, but the message's as_of is older than three of its own intervals (interval_seconds in the message), judged against the reader's clock stale unknown (stale). Each Node is judged by its own interval, so Nodes set to different intervals are each judged fairly. A Node whose own clock runs more than that far behind the reader's reads stale even while it is publishing, so keep the two clocks closer together than that
The Node is online, but the message's as_of is more than 60 seconds ahead of the reader's clock clock suspect unknown (clock suspect). A single retained message cannot say whether the Node's clock or the reader's is wrong; keep both within a minute of true time

Each count is bounded by a statement timeout of half the interval (at least half a second, at most 30), on top of the 10-second wait to reach the database. A count that waits behind a lock, a schema change say, is cancelled: that tick publishes nothing, as_of ages, the reader shows the Node stale, and the thread is free for the next tick. The failure is logged once per outage.

A count message that names no Node on its broker (no matching announcement) is not a Node: it is not listed, and the broker's line counts it apart from the messages dropped as malformed or over the per-broker limit (in --json, unmatched_counts beside dropped). On a broker shared by several Nodes the one retained count message can name another Node than the one announcement does, so that count is expected there and is not a sign of garbage. A stale, missing or suspect count does not change the command's exit code, which is about the roster: a site of healthy Nodes that were not re-run would otherwise fail every check.

Like the identity topic, the pending-count topic holds one retained message per broker. A reader that connects late to a broker shared by several Nodes is handed one count message, as it is handed one announcement, so the roster reads a site completely only when each broker has one Node.

Certificate renewal

Mosquitto runs as its own user and cannot read the service user's key, so it holds its own root-owned, mosquitto-group-readable copy in /etc/mosquitto/kindred-tls/. When the Node's certificate is renewed, a hook in its reload.d runs /usr/local/sbin/kindred-mosquitto-refresh-certs through sudo. That is the only command the service user may run as root, with no arguments. It checks the new certificate against the root-owned trust bundle (never the service user's copy), builds the new files whole, switches to them with one rename and tells Mosquitto to reload. The broker serves the new certificate without a restart. A bad certificate or key is refused and the broker keeps serving what it had.

Root runs the helper, the TLS probe, the renderer and pki_common.sh from the repository's deployment/ directory. If a non-root user owns or can write any of those files (a checkout the service user owns is the usual case), that user can change what root runs the next time an administrator runs the script. The script warns for each such file and prints the helper's sha256 so you can check it. If you must defend against a compromised service user, run the script from a root-owned copy of the repository.

The TLS version floor

Mosquitto's tls_version option pins one exact version, so it cannot say "1.2 or later". It is left unset: TLS 1.2 and 1.3 are accepted and the floor is the host's OpenSSL policy. After starting the broker, configure_mosquitto.sh runs probe_mqtt_tls.sh, which checks that 1.2 and 1.3 are accepted and 1.0 and 1.1 are refused on this host, and fails the script if they are not. The same probe runs in the tests.

Checking by hand

deployment/probe_mqtt_tls.sh --port 8883 --cafile trust-bundle.pem --cert node.crt --key node.key
mosquitto_sub -h <appliance> -p 8883 --cafile trust-bundle.pem --cert node.crt --key node.key -t kindred/activity_log

To read one Node's GET /v1/status through the roster, give the instance id, a file holding a bearer token and the site CA's trust bundle:

python3 -m engine.node_roster brokers.json --status mes-01 --token-file token.txt --trust-bundle trust-bundle.pem

The token is sent over TLS that must chain to the trust bundle, to the address the Node announced, with the hostname unchecked. Only the broker's writers can announce an address, so on a broker that every Node and person on the site can write to, a certificate from the same site CA at a wrong address is also accepted. --expect-site SITE closes that: the certificate the Node presents must also speak for that site (urn:kindred:<site>:<node>), and the token is not sent if it does not (the certificate is not of the expected site). Without the option nothing changes.

Connecting from code

engine/mqtt_connection.py's BrokerConnection is the one client for a Kindred broker. It takes a BrokerProfile (engine/mqtt_config.py): a host and port with the node's CA bundle, certificate and key for the network listener, or a socket_path for the Node's own socket. start() never raises; whether the broker is reachable is state (connecting, connected, reconnecting, disconnected) and the reason is last_error. It reconnects by itself and re-subscribes after each reconnect. A broker whose certificate does not chain to the bundle is refused and never used without verification. Delivery is QoS 0: messages sent while the connection is down are lost.

How the Node publishes its Activity Log

engine/activity_publisher.py keeps one long-lived publisher per broker (the Unix socket, or a host and port), built on BrokerConnection. A write to the Activity Log puts its event on a queue and returns at once; a worker sends it when the broker is reachable, in the order the events were written. A broker that is down, slow or refusing never slows or fails a write. The queue holds 1000 events; when it is full the oldest are dropped. Nothing is saved, so events queued or dropped while the broker is unreachable never reach it: the activity_log table is the record.

What to look for in the Node's log:

  • MQTT broker <target>: connected, reconnecting or disconnected (<reason>): one line per change of state, not one per event.
  • refused by the broker: <reason>: the broker does not accept this Node (a socket whose permissions or configuration reject it). It appears once; events queue and are dropped meanwhile.
  • events were dropped ... N since the last report, M in all: a rate-limited count, at most one line every 30 seconds, so a long outage stays quiet.
  • stopped with N events unsent: the process ended with events still queued. A normal stop flushes first, for up to two seconds, and does not wait for a broker that is unreachable.

Tests

tests/mqtt_secured_broker.py starts a throwaway Mosquitto on the configuration the renderer produces, with certificates from the Site CA scripts, and tests/test_mqtt_secured_broker.py runs the rules above against it: plaintext, certificate-less and foreign-CA clients are refused, the socket accepts only the Activity Log, identity and pending-count topics, network clients cannot publish, and a renewed certificate is served after a reload. tests/test_render_mosquitto_config.py also shows, for each of the retained topics, that a forged publish from the network is dropped and that a Last Will on the topic from the socket is delivered while one elsewhere is not. tests/test_broker_persistence.py restarts and crashes that broker to check what survives, including both retained messages across a controlled restart, and tests/test_mqtt_broker_doc.py keeps this page's topics, autosave interval, pending-count interval, the roster reader's states and its staleness factor and clock margin equal to the ones the renderer, the Node and the reader use. tests/test_mqtt_connection.py runs the client wrapper against the same broker, including a broker restart. tests/test_activity_publisher.py runs the Activity Log publisher against throwaway brokers. tests/test_configure_mosquitto.py covers the script itself, including a re-run on an appliance provisioned before each topic existed, and a Node on one not re-run that is announced while its counts are dropped. What needs real accounts (the group, the setgid directory, running the helper through sudo) is checked by the script's own checks after it starts the broker, and by running it on a fresh host.

Release: v0.11.0