Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

TLS

ytls.h

The ytls.h header file defines the interface for the TLS (Transport Layer Security) function in the Yuneta framework. It provides function declarations and structures for handling secure communication using TLS. Key features include:

Architecture

The ytls module uses a backend-agnostic design. The public API (ytls.h / ytls.c) exposes a single api_tls_t dispatch table, while the actual crypto is provided by two interchangeable backends configured via Kconfig (one or both can be enabled):

Both backends can be enabled simultaneously. When both are present, OpenSSL is preferred as the default.

ytls.h is the single source of truth for the backend names:

At runtime, two matching yuno global variables are available — root-linux’s yunetas_register_c_core() publishes them into gobj’s global-variable pool via gobj_add_global_variable(), so gobj-c itself stays free of any CONFIG_HAVE_OPENSSL / CONFIG_HAVE_MBEDTLS checks:

Source files

FilePurpose
ytls.h / ytls.cPublic API and dispatch table
tls/openssl.c / openssl.hOpenSSL backend implementation
tls/mbedtls.c / mbedtls.hmbed-TLS backend implementation

Backend implementations

Both backends implement the same function:

A client of one backend talks to a server of the other. One case needs care: a TLS 1.3 server sends session tickets after the handshake (OpenSSL, nginx and Python send two by default), and an mbedTLS client reports the last one from its next write as MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET. ytls writes again: it is not an error. In 7.30.20 (since 7.28.0) it was taken for one, and an mbedTLS client that wrote after the tickets arrived lost the connection:

ERROR: {"function": "encrypt_data", "msgset": "MbedTLS", "msg": "mbedtls_ssl_write() FAILED", "error_code": -31488, ...}

Test: tests/c/ytls/test_session_tickets (an mbedTLS client against an OpenSSL server, when both backends are compiled in).

This module makes sure that Yuneta applications can securely transmit data over the network using industry-standard encryption protocols.

Hot-reloading certificates

ytls can swap the certificate material of a running TLS listener without dropping the sessions that are already established. This is how Yuneta keeps MQTT brokers, intake gates and control-plane channels online while Let’s Encrypt renews a certificate in the background.

API

ytls_reload_certificates() is the only entry point. It rebuilds the per-backend context from the cert paths already stored in the ytls handle, validates it, and atomically swaps it in. If any step fails, the previous context is kept intact and the caller sees a negative return — traffic is never interrupted by a bad reload.

ytls_get_cert_info() returns subject, issuer, not_before, not_after, serial and days_remaining for the currently-active context, so operators can observe the live cert (not just the file on disk).

How live sessions survive the swap

The ytls handle is repointed from old_ctx to new_ctx and frees its own reference to old_ctx; live SSL sessions still hold their own refs, so old_ctx survives until the last in-flight session closes, while new sessions attach to new_ctx.

The handle drops its ref on old_ctx; live sessions keep theirs, so the old context outlives the swap.

The invariant is: live sessions hold their own reference on the old context, so the swap only drops the handle’s reference. This is the easiest thing to break when touching the reload path.

Callers

Yuneta ships three layers of defense that all drive ytls_reload_certificates() through the same path — see the TLS certificate management guide for the full picture:

  1. Layer 1 — certbot deploy hook. Pushes the reload-certs command down the yuno tree the moment certbot succeeds.

  2. Layer 2 — c_agent auto-sync timer. Re-reads the cert files every cert_sync_interval_sec seconds (default 15 min) and broadcasts reload-certs when size+mtime changes.

  3. Layer 3 — c_yuno expiry monitor. Periodic view-cert walk with warning / critical thresholds (cert_warn_days, cert_critical_days). It only alerts, and it never reloads.

Each C_TCP_S / C_UDP_S listener also exposes reload-certs and view-cert directly, so a single listener can be targeted from ycommand without touching the rest of the yuno.

A server without its certificate: the yuno decides

A TLS context that cannot be built is never fatal in ytls. A server whose certificate, key or trusted certificate cannot be loaded gets NULL from ytls_init(), with ONE ERROR of the cause, and its C_TCP_S never listens without a context. What happens then is the yuno’s choice, with exitOnError of the C_TCP_S:

The agent sets 0: its listeners are secondary services, its primary role is managing its realms and yunos, and its 1993 must not take that down. The agent without its pair keeps answering ycommand on 1991, and opens 1993 as soon as yuneta-agent-cert ensure (or cert-sync) puts the pair in place, with no restart:

ycommand -c 'stats-agent service=agent_secure_port'
# {"listening": false, "tls_ready": false, ...}
sudo /usr/libexec/yuneta/yuneta-agent-cert ensure
ycommand -c 'command-agent service=agent_secure_port command=reload-certs'

Up to 7.30.17 ytls itself exited the yuno with code 0, whatever the yuno wanted, and 7.30.18 degraded every yuno. Details: C_TCP_S, A TLS server without its TLS context.

TLS security posture (hardening)

ytls is secure-by-default: a gate that sets no TLS knobs gets the hardened behavior, and every deliberate relaxation is an explicit, logged downgrade — the yuneta “no silent errors” axiom applied to crypto. The knobs below live in the gate’s crypto config. The same key means the same thing on both backends.

Protocol floor — ssl_min_version

Both backends floor at TLS 1.2 when ssl_min_version is unset.

Handshake deadline — timeout_tls_handshake

A TLS handshake that has not ended in timeout_tls_handshake ms (an attribute of C_TCP, default 10000, 0: none) drops the connection, on a server and on a client. A client then reconnects. The drop is said with ONE warning per 10 s for the whole yuno, whose suppressed counts the drops it did not write. Without it, a peer that opened a TCP connection and said nothing held a channel of a TLS server for ever (up to 7.30.16). See The deadline of the TLS handshake in the C_TCP section of the transport GClasses page.

'gclass': 'C_TCP',
'kw': {
    'timeout_tls_handshake': 5000
}

Renegotiation — ssl_disable_renegotiation

Defaults to true (renegotiation disabled), closing the renegotiation-based DoS/abuse surface. TLS 1.3 has no renegotiation at all. Set it to false only on a gate that genuinely needs it — that re-enable is logged as an auditable downgrade. OpenSSL backend only.

Peer verification — ssl_verify_mode

When unset, the mode is computed from the gate’s role and whether a CA is configured:

SituationComputed default
server, no CA configurednone — preserves historical IoT / PSK / self-signed behavior (anonymous clients accepted)
client, no CA configuredrefused — see verify-by-default below
server with a CAoptional — request + verify the client cert if presented
client with a CArequired — validate the server cert + hostname

ssl_verify_mode (required / optional / none / request) overrides the computed default. ssl_use_system_ca adds the OS trust store. ssl_verify_depth bounds the chain. A verify failure is never silent: under optional a non-verifying peer is accepted but logged post-handshake (OpenSSL SSL_get_verify_result(), mbed-TLS mbedtls_ssl_get_verify_result()). Under required the verify callback logs the chain error and aborts the handshake. The mbed-TLS verify default is deliberately left IoT-tolerant (optional, surfaced) — raise it per gate with ssl_verify_mode=required.

ModeAsks the client’s certificate (server)Chain verifiedA peer that does not verifyverified in peer_cert
nonenono—always false
optionalyes, can be absentyeslet in, WARNINGtrue only if it verified
requiredyes, must be present (server)yesrefused in the handshaketrue
requestyes, can be absentno (a CA given is not used)let in, nothing loggedalways false

request (since 7.30.10) is for a server only: a client with it is refused (ytls_init() fails). It takes the client’s certificate as it comes, so that the owner PINS the key of each client by the spki_sha256 of its peer_cert — a self-signed client certificate is the point. Trust an identity from a request server only through a key you pinned, never through verified. The controlcenter’s listeners of the agents use it to pin the key of each node:

"crypto": {
    "library": "openssl",
    "ssl_certificate": "/yuneta/store/certs/controlcenter.example.com.crt",
    "ssl_certificate_key": "/yuneta/store/certs/private/controlcenter.example.com.key",
    "ssl_verify_mode": "request"
}

The key of a certificate, as spki_sha256 gives it:

openssl x509 -in client.crt -pubkey -noout | openssl pkey -pubin -outform DER | sha256sum

Verify-by-default for clients (since 7.6.0)

A TLS client with no way to validate the server certificate (effective authmode none — no CA configured, or an explicit ssl_verify_mode=none) is a standing MITM hole, so it is now refused at ctx/state build time in both backends: ytls_init() fails and the connection is not made (fail-soft — the yuno stays up). This is a breaking change for clients that previously ran unverified. To keep running such a client (self-signed / PSK / IoT bring-up) set ssl_allow_insecure_client: true in its crypto block to accept the MITM risk explicitly. The choice is then logged, never silent (the mbed-TLS backend runs the opted-in client under optional so the tolerated verify failure is still surfaced — OpenSSL parity). Servers with no CA legitimately accept anonymous clients and are unaffected.

Knob summary

KnobDefaultEffect
ssl_min_versionTLS 1.2 floorminimum negotiated protocol version
ssl_disable_renegotiationtrueOpenSSL renegotiation off
ssl_verify_modecomputed (table above)required / optional / none / request (a server that pins its clients’ keys)
ssl_trusted_certificateunsetpath to a CA bundle (PEM) used to verify the peer
ssl_use_system_cafalsealso trust the OS CA store (both backends: mbed-TLS parses the system bundle)
ssl_verify_depth2max certificate chain depth (leaf → intermediate → root)
ssl_allow_insecure_clientfalsetrue → run an unverified client anyway (accept the MITM risk)
ssl_ciphersbackend defaultcipher list (@SECLEVEL=0 to reach legacy suites)

Regression coverage: test_tls_floor_openssl.c asserts that an explicit sub-TLS1.2 floor is logged and that a real TLS1.0 ClientHello is rejected by the default floor. test_tls_verify_openssl.c drives a real client/server handshake and asserts that a trusted cert with a matching host connects, while a hostname mismatch or an unknown CA is rejected.

Deployment — gate profiles & rollout

Secure-by-default means the upgrade itself breaks nothing: modern peers keep negotiating on the new TLS 1.2 floor, renegotiation-off is transparent, and peer verification stays off on any gate until you give it a CA. Hardening a gate is then just a few keys in its crypto config. Two profiles cover almost every gate.

Profile A — high-security gate

For SPA / BFF front ends, host-to-host links and the control plane — gates that talk to modern peers. Turn verification on. The floor, reneg-off and the computed required/optional mode are already the defaults, so the CA is the only thing you add.

A client that dials out (validates the server it connects to):

"crypto": {
    "library": "openssl",
    "ssl_trusted_certificate": "/yuneta/store/.../trusted_ca.pem",
    "ssl_server_name": "api.example.com"
}

The bundled CLI tools (ycommand, ystats, ybatch, ytests, ycli, mqtt_tui, emu_device) already pass "ssl_use_system_ca": true on their outbound TLS, so a wss:// / https:// endpoint with a public CA (for example Let’s Encrypt) works by default — including ycommand’s OIDC task-authenticate to the issuer. ycommand, ybatch and ystats expose --ssl-use-system-ca (default on), --ssl-trusted-certificate (private CA), --ssl-server-name and --ssl-allow-insecure-client (bypass) to override per call. ycli takes the same four as parameters of its connect command.

Verification checks the hostname too, so dial the name the certificate is issued for, not any DNS alias that resolves to the same host. When you cannot — a pinned certificate that carries a name of its own — give that name in --ssl-server-name. The agent is the case in point: it serves a long-life certificate named CN=yuneta_agent.yuneta.io on every node, so the name never matches the host dialed. Since 7.30.6 that certificate is the NODE’s own (made on it, see installation, “The agent’s own certificate”), so the client trusts that node’s copy, not its own:

scp yuneta@node.example.com:/yuneta/agent/certs/yuneta_agent.crt /tmp/node.crt
ycommand -u wss://node.example.com:1993 \
    --ssl-trusted-certificate=/tmp/node.crt \
    --ssl-server-name=yuneta_agent.yuneta.io \
    -c 'list-yunos'

Nothing is weakened: the chain is still validated against the PEM given, and --ssl-server-name only says which name to check it against. Without it the handshake is rejected for a hostname mismatch, and the tool retries in silence instead of failing — the flag is the difference between a working call and a command that seems to hang.

A server doing mutual-TLS (validates the client certificate):

"crypto": {
    "library": "openssl",
    "ssl_certificate": "/path/server.pem",
    "ssl_certificate_key": "/path/server.key",
    "ssl_trusted_certificate": "/path/client_ca.pem",
    "ssl_verify_mode": "required"
}

A CA-configured server defaults to optional (request + verify the client cert if presented, tolerate absent). Set required to reject clients without a valid certificate.

Profile B — IoT / legacy-compat gate

For old devices that cannot do TLS 1.2, or that use PSK / self-signed certs. Relax explicitly — each relaxation is logged and stays greppable.

"crypto": {
    "library": "openssl",
    "ssl_min_version": "TLS1.0",
    "ssl_ciphers": "HIGH:@SECLEVEL=0",
    "ssl_verify_mode": "none"
}

Rollout procedure

  1. Upgrade. Nothing breaks. The reduced-security gates start announcing themselves in the log.

  2. Enumerate from the logs. Every gap is designed to be greppable:

    Log messageMeaningAction
    TLS client WITHOUT server-certificate validationa client is not validating the server it dialsadd a CA → Profile A
    TLS handshake rejecteda peer was refused (often a legacy device below the floor). One per 10 s for each listener, and one per 10 s for all the clients of the yuno together (for all the clients of one TLS backend: a yuno with clients on both backends has two clients’ windows, one per backend): suppressed counts the ones of the last window not written, so a peer that fails its handshake in a loop does not write the log at its own rate (up to 7.30.18 each one wrote it), a scanner on one listener does not hide the reject of a legitimate client on another (up to 7.30.19 the window was the whole yuno’s), and a client that connects again and again, with a context of its own for each connection, does not write a line per connection (in 7.30.20 it did)if legitimate, move that gate to Profile B
    TLS handshakes rejected, not said in their windowthe rejects that no line said. Nothing closes a window by time: its count is said at the next reject after the window (in that line, or in this one when the next reject comes more than 10 s after the window), or when a listener ends. The clients’ count is also said when a client context ends after the window, or in the shutdown of the yuno, by the first client context that ends in it (up to 7.30.21 the count of the clients’ last window was lost when the yuno ended). A window whose client contexts have all ended before the shutdown, with no reject after it (a client that stops after failing), keeps its count unsaid: its first reject was written, the ones after it in those 10 s are counted and never said. suppressed is the count, and the line names the gobj (gobj_full_name) and the ssl_server_name of the context that writes it. For the clients’ count that is the client whose reject or end writes the line, which can be another client than the ones that failed (see the second example below)as above
    TLS handshake not ended in time, connection droppeda peer opened a TCP connection and did not end its handshake in timeout_tls_handshake (a scanner, a slowloris, a broken client). One per 10 s, and suppressed counts the othersif a legitimate peer is slow, raise timeout_tls_handshake on that C_TCP. A high suppressed is a flood of mute connections
    legacy floor below TLS1.2a gate is on a relaxed floorconfirm it is an intended IoT gate
    renegotiation explicitly enableda gate re-enabled renegotiationconfirm it is needed
    peer certificate did NOT verifyan optional gate accepted an invalid certfix the chain, or raise to required

    For example, a client C_TCP that fails 40 handshakes in 10 s against a server whose certificate it does not accept (a new TLS context at each start), and one more 11 s later, writes two lines in all. The second says the 39 not written:

    WARNING: {"function": "do_handshake", "msg": "TLS handshake rejected", "error": "...certificate verify failed", "suppressed": 0, ...}
    WARNING: {"function": "do_handshake", "msg": "TLS handshake rejected", "error": "...certificate verify failed", "suppressed": 39, ...}

    The clients’ count is one for every client of the backend, so the line that says it names the client that writes it. Client X (ssl_server_name idp.x) fails 5 handshakes. Client Y (other.y) fails one 11 s later. X writes the first line. The line of Y carries the 4 that X did not write:

    WARNING: {"msg": "TLS handshake rejected", "ssl_server_name": "idp.x", "suppressed": 0, ...}
    WARNING: {"msg": "TLS handshake rejected", "ssl_server_name": "other.y", "suppressed": 4, ...}

    To tell which client failed, read the TLS handshake rejected lines and the disconnect_cause of each C_TCP, not the suppressed of a line.

  3. Harden the high-level gates one at a time: apply Profile A, restart, confirm the warning is gone and traffic still flows.

  4. Pin the legacy gates that showed TLS handshake rejected to Profile B.

  5. Validate in staging, then production. Roll the config to a staging environment first and watch the same logs. Only then promote to production.

Goal state: no WITHOUT server-certificate validation lines outside known IoT gates, and every legacy floor / renegotiation enabled line traceable to a deliberate Profile-B gate.

Philosophy of ytls

The ytls module is built with the core philosophy of Yuneta in mind:

By following these principles, ytls makes sure that Yuneta-based applications maintain strong security without unnecessary complexity.