
Recall first from Memory safety and secure coding
- ASan detects many invalid memory accesses during execution, while UBSan detects selected forms of undefined behavior.
- Bounds and resource limits must be checked before arithmetic, allocation, or copying.
- Fixed format strings, explicit child arguments, and constrained path resolution enforce different input rules.
Authenticate the caller and authorize the action
4 min readSafe code still needs to identify users and protect secrets; this lesson covers authentication, secrets management, and TLS configuration.
On Linux, a call to open() can fail because the process lacks permission to read a file. When a gateway opens its configuration on behalf of a remote caller, Linux checks the gateway process's credentials. Every caller whose request reaches that operation uses the same process permissions, so the gateway itself must decide whose request can reach it. The open(2) reference describes the local permission check that makes this distinction concrete.
verification of the identity associated with a presented credential answers “Who is calling?” the decision to permit a specific action on a specific resource answers “What may this caller do?” A technician might be allowed to change alarm thresholds on one gateway. A telemetry collector might be allowed to read measurements from the same gateway. Each request needs a verified identity and an appropriate permission.
Passwords. For a gateway with local user accounts, store a password verifier produced by a password hashing library. Choose Argon2id or use bcrypt where compatibility requires it. Have the library generate a fresh random salt for each password and save the algorithm, cost parameters, salt, and hash in the library's encoded format. The salt can be stored with the hash. It makes two identical passwords produce different records when the salts differ. On login, pass the submitted password and stored record to the library's verification function. A fast general-purpose hash such as SHA-256 alone makes guessing cheap after a database leak. Argon2id deliberately uses memory and computation, while bcrypt exposes a work factor. With bcrypt, check the library's input length behavior and reject passwords that would be silently truncated.
Measure verification on the target board under expected login concurrency. A cost that seems reasonable on a development PC can exhaust memory or delay other services on a gateway. Limit login attempts and the number of concurrent password verifications. For cost upgrades, verify against the existing record, then generate a fresh record using the new parameters after a successful login. This lets existing users keep their passwords through the transition.
Session tokens and JWTs. After login, a gateway can issue a random opaque session token and keep its identity and expiry in a server-side record. It can end that session by invalidating the record. A signed JSON Web Token (JWT) carries claims that a recipient can verify using a configured key. Use a library and configure the accepted signing algorithm and trusted issuer keys. Require a valid signature, the expected issuer and audience, and a valid expiration. Enforce the “not before” time when present. For example, a token issued for a cloud dashboard fails the audience check at a gateway that expects its own audience. A signed JWT's claims are readable, so keep secrets out of them. Short lifetimes limit how long a stolen bearer token can be reused. When logout or account disablement must take effect immediately, arrange a server-side check for revocation or current account state.
API keys. Issue a distinct key to each automated caller and give it a specific scope, such as reading telemetry from one device. Generate the secret with a cryptographic random source. On Linux, getrandom(2) documents an interface to the kernel random source. One design uses a public key identifier for lookup and a separate high-entropy secret. Store a digest of the random secret on the verifying server and compare the computed digest using a constant-time comparison from a crypto library. Send bearer credentials via an HTTP header over verified TLS and redact that header in logs. A key in a URL can appear in access logs and browser history.
Role-based access control. Assign identities to roles and define which actions each role permits. Check the role and resource scope in the server before applying a change. If a request targets another gateway, a valid operator role for the first gateway is insufficient. Deny actions unless the policy grants them explicitly. Hiding the settings button in a web UI helps guide the user, while the server must enforce the same rule on requests received directly.
Provision, store, and rotate device secrets
3 min readA release image is copied across units and may be available to anyone who can obtain an update. Keep passwords, private keys, and API secrets out of firmware binaries, image defaults, and build artifacts. Generate a device's own key on the unit when feasible, or provision a unique credential through an authenticated enrollment process. A certificate and a public CA trust anchor can be distributed openly. The corresponding private key must be protected. If one gateway's private credential is compromised, unique credentials let you revoke that gateway's identity independently.
TPM. A Trusted Platform Module can generate and use a suitably configured non-exportable private signing key. With a compatible TLS provider or middleware, the gateway can ask the TPM to sign during the handshake while the private key stays inside the TPM's protection boundary. A TPM can also seal a secret for release under a policy, which is a different use: the released secret is available to the software that consumes it. Check the hardware and software integration for your specific Raspberry Pi or BeagleBone design before choosing this approach. Restrict which service can use the key. A compromised process that has permission to request signatures can still request them.
Encrypted storage. A disk or data volume encrypted at rest can protect device credentials when storage is removed and the unlock key is unavailable. Decide how an unattended gateway will unlock after a reboot. If the unlock secret ships on the same readable media, someone who obtains that media may get both values. Once the volume is unlocked, file permissions and process privileges determine who can read the files. Check your backups and diagnostic bundles as well, since they can create additional copies outside the encrypted volume.
Files with tight permissions. When the TLS library loads a private key from a file, put it in a dedicated directory and restrict access to the service identity. For a directory and file owned by that identity, mode 0700 on the directory grants access to its owner, and mode 0600 on the key permits the owner to read and write it. Create the file with restricted permissions from the start. The open(2) reference explains how the requested creation mode and process umask affect the initial mode in the absence of a default ACL. Check the actual owner and permissions on the deployed device. A key copy in a provisioning log or a backup needs protection independently of the original file.
For planned rotation, issue a replacement credential and update the systems that must accept it. During a bounded overlap, the verifier can accept both credential versions. Switch the caller to the replacement and verify that a fresh session succeeds with it. Then retire the old credential and check that a fresh attempt with it fails. A certificate renewal can reuse a key, so generate a fresh key when the goal is key rotation. Allow enough time for offline units to check in before the planned cutoff and define how units that miss it will re-enroll. When compromise is suspected, revoke the affected credential promptly and use the recovery path for any units that lose access.
Configure TLS to verify the expected peer
4 min readFor a gateway upload, the client must establish that it reached the service configured for uploads before it sends credentials. Use TLS 1.3 where both ends support it. If interoperability requires TLS 1.2, use suites with ephemeral key exchange such as ECDHE and authenticated encryption such as AES-GCM or ChaCha20-Poly1305. Use the TLS library's modern defaults as a starting point and check the actual versions and suites the deployment permits. TLS 1.2 and TLS 1.3 suite settings can be separate in a library or server. Setting a TLS 1.2 cipher list alone leaves the TLS 1.3 suite policy to its own configuration.
Certificate validation. Configure the client to verify the certificate chain against the intended trust anchors, check certificate validity periods and allowed use, and verify the expected service name. A connection to gateway.test should validate against gateway.test in the certificate's DNS subject alternative names. When the configured endpoint is an IP address, use a certificate with a matching IP address subject alternative name. A server ordinarily sends its leaf and needed intermediates, and the client gets its trust anchor from a trusted source. A private CA is a practical option for a managed fleet. Provision its public trust material through an authenticated channel. Provide a credible system clock at boot, especially on boards that may start with an incorrect date after losing power. Have the application wait for usable time if needed, with certificate validity checks enabled.
Pinning. In a controlled fleet, a pin can add a requirement that the certificate's public key match a preconfigured value. Keep normal chain and hostname checks enabled. A public-key pin can survive certificate renewal with the same key. Key rotation requires a pin for the replacement key, so stage that pin before switching and keep an authenticated recovery path for clients that missed the update. A single pin that cannot be updated can prevent an otherwise valid connection after a key change.
Mutual TLS. With mutual TLS (mTLS), the server also requires a client certificate and proof that the client holds its private key. Configure the server to verify the client chain and certificate use against its intended client trust anchors, then map the authenticated certificate identity to an enrolled device or service account. That identity still needs permissions for the requested operation. For example, the cloud endpoint can allow a gateway to upload its own telemetry while rejecting uploads under another device's identity.
Common configuration failures include enabling encryption while skipping certificate verification, checking the CA while omitting hostname verification, and making client certificates optional on an endpoint that requires mTLS. A useful test plan includes a valid connection and separate failure cases for an untrusted issuer, a mismatched name, and, on an mTLS endpoint, a missing client certificate. Diagnose each failure while keeping verification enabled.
On Ubuntu 24.04, you can isolate trust and name checks without a running server. In a private temporary directory, generate a disposable self-signed certificate for a test endpoint, then explicitly trust that certificate for the check:
openssl req -x509 -newkey rsa:2048 -noenc -days 1 \
-subj '/CN=gateway.test' \
-addext 'subjectAltName=DNS:gateway.test' \
-keyout gateway.key -out gateway.crt
openssl verify -CAfile gateway.crt -purpose sslserver \
-verify_hostname gateway.test gateway.crt
The second command should succeed if certificate creation succeeded and the local clock is within the certificate's validity period. Keep the same trusted certificate and change -verify_hostname to other.test to isolate a name failure. Restore the expected name and replace -CAfile gateway.crt with -no-CAfile -no-CApath -no-CAstore to isolate a trust failure. In a test run with OpenSSL 3.0.13 the first check printed gateway.crt: OK, the other.test check printed error 62 at 0 depth lookup: hostname mismatch, and the no-trust check printed error 18 at 0 depth lookup: self-signed certificate. These checks exercise certificate verification offline. A deployment test must also connect through the actual client and server configuration to confirm they apply the intended rules.
A gateway can make the right credential and TLS decisions while its service process still has broad access to the device. Network, filesystem, and sandbox hardening asks how to limit that access so a compromised service can affect fewer resources.
Key takeaways
- Passwords need salted, deliberately expensive hashes, while API keys need high-entropy random values and narrow scopes.
- A verified identity still needs authorization for the requested action and resource.
- Provision private credentials per device and test replacement before retiring an old credential.
- TLS clients must verify certificate trust and the expected endpoint identity.
Reflect
- Explain to a colleague, in two sentences: distinguish authentication from authorization in a gateway request.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pagegetrandom(2): obtain random bytes
- Man pageopen(2): open and create files
- Kernel documentationTrusted and Encrypted Keys
Official documentation first. Links checked when the lesson was published.