Repository navigation
Stop deriving Linux Tentacle's config encryption key from /etc/machine-id - #1348
Conversation
bace2af to
af7dfbf
Compare
2c8c535 to
5edd108
Compare
* Split the per-instance configuration encryption key from the legacy machine key source * Do not fall back to legacy encryption when the configuration encryption key is unreadable * Remove duplicated legacy key and decryption error handling * Require callers to supply the encryptor when creating an XmlFileKeyValueStore * Reduce ITentacleConfigurationUpgrade to PrepareKey and Run, both throwing * Move Unix P/Invoke into UnixFile * Simplify AtomicCreateFileWithUserReadWriteAccessOnly to one implementation * Resolve the instance's key path in Tentacle Manager instead of passing null * Rename WriteUserReadWriteOnly to CreateOwnerOnlyFile * Read the link error before another call can overwrite it * Move the upgrade's warn-and-continue handling into TentacleConfigurationUpgrade * Rename the configuration upgrade's Run to Upgrade
e9ab6b3 to
3e06c12
Compare
Renames it to AtomicCreateFileWithOnlyUserReadWritePermissions, marks it and
its callers [UnsupportedOSPlatform("windows")] so an unguarded caller fails
to compile, and throws on Windows instead of writing a file with inherited
permissions.
| { | ||
| CreateFileWithUserReadWriteAccessOnly(temporaryPath, contents); | ||
| // Unlike File.Move, link(2) is atomic about not replacing: two racing processes cannot each keep their own file. | ||
| return UnixFile.TryLinkWithoutReplacing(temporaryPath, path); |
There was a problem hiding this comment.
Key creation needs hard links, which some volume types don't support.
link(2) fails on filesystems without hard links. As far as I know that includes SMB/CIFS shares such as Azure Files, and exFAT/vFAT. TryLinkWithoutReplacing treats anything other than EEXIST as fatal, so create-instance would fail with "Unable to create …" and no instance could be made.
This matters more now because we tell Docker users to mount /var/lib/octopus/tentacle on a volume, and an Azure Files share is a common choice for that on ACI and AKS. I haven't tried it on one of those volumes, so this is from reading the code.
Could we fall back when link fails with EPERM, ENOTSUP or EOPNOTSUPP? Creating the final path directly with FileMode.CreateNew is still exclusive, so two racers can't each keep their own key. The trade-off is that a racer that loses could read the file before the winner has finished writing it, so the loser might need a short retry on a corrupt or empty read. That seems acceptable for a fallback that only applies on these filesystems.
Generated by Claude Code
There was a problem hiding this comment.
Fixed in 290283e. If link fails with EPERM or EOPNOTSUPP, the key is created at its final path with FileMode.CreateNew, and a reader that finds it empty retries for about a second. Not tried on a real SMB or vFAT volume.
| } | ||
| catch (Exception e) | ||
| { | ||
| throw new CryptographicException($"Unable to encrypt a value with the Tentacle machine key: {e.Message}", e); |
There was a problem hiding this comment.
Minor: encryption failures at agent start get reported as an x509stores problem.
Encrypt now wraps every failure in CryptographicException (it threw AggregateException before). RunAgentCommand lines 98-100 already catch that type around first-certificate generation, log "The owner of the x509stores is not the current user, please change ownership of the x509stores directory or run with sudo", and return without starting.
So if the agent starts with no certificate yet and the key can't be used (unreadable by the service user, corrupt, or no key and no legacy key available), GenerateNewCertificate → SetTentacleCertificate → Encrypt throws here and the user is told it is an x509stores ownership problem. The real message is still appended after "Details:", but the lead sentence points them at the wrong thing.
Could Encrypt throw a distinct exception type, or could the catch in RunAgentCommand be narrowed so key failures aren't labelled as x509stores?
Generated by Claude Code
There was a problem hiding this comment.
Fixed in 16d2564. Key failures now throw ConfigurationEncryptionKeyException, which neither the x509stores catch in RunAgentCommand nor the in-memory certificate fallback in GenerateNewCertificate catches.
…tems that don't support them
…n as an x509stores problem
…op replace-certificate creating keys
…ad of linking it ourselves
…an changing the test process's umask
| CreateFileWithUserReadWriteAccessOnly(temporaryPath, contents); | ||
| // Unlike File.Move, link(2) is atomic about not replacing: two racing processes cannot each keep their own file. | ||
| return UnixFile.TryLinkWithoutReplacing(temporaryPath, path); | ||
| File.Move(temporaryPath, path); |
There was a problem hiding this comment.
Why this change?
This looks like a regression. Were the test failures this was causing not a scenario we care about?
File.Move is not guaranteed to be atomic.
Maybe it is in the cases where we use it in this PR, but this is a more general class, so it could cause confusion.
There was a problem hiding this comment.
I don't think the added code complexity is worth it for the edge case of race conditions specific to Linux-only tentacles that are running on a non-hard-linking FS.
There was a problem hiding this comment.
The method name says TryAtomic..... It should be renamed if it is not doing it atomically.
There was a problem hiding this comment.
I am going to leave it as atomic since its what we want and practically speaking its atomic.
It's not atomic when we have fat/exfat (who is running that?), or samba e.g. for azure shares. Azure shares provide no guarantee for atomic operations of complete files, even if we went back to the complex code we had before.
- I don't want to remove atomic from the name because it wants to be atomic.
- it is as atomic as it can be for the file system it runs on.
| public void CreateInstance(string instanceName, string configurationFile, string? homeDirectory = null) | ||
| { | ||
| (configurationFile, homeDirectory) = ValidateConfigDirectory(configurationFile, homeDirectory); | ||
| EnsureConfigurationEncryptionKeyExists(instanceName); |
There was a problem hiding this comment.
Should we be deleting the encryption key (and its folder) in DeleteInstance below?
There was a problem hiding this comment.
wow ok so delete instance is a disaster all it does it remove the instance registration (basically it removes the tentacles name bob from some shared file).
I guess given the config is left, leaving the key makes sense.
| } | ||
|
|
||
| [Test] | ||
| public async Task WhenTentacleKeyFileIsDeleted_AndANewCertificateIsCreated_ThenItFailsRatherThanFallBackToEtcMachineId() |
There was a problem hiding this comment.
This test covers overwriting certificates encrypted via the new method, but not writing certificates when there is currently none. We should probably guard against the old encryption being used in that case.
There was a problem hiding this comment.
This doesn't seem like a real case to concern ourselves with. I wont bother with the guard.
| var user = Environment.UserName; | ||
| var directory = key.KeyDirectory; | ||
| throw new ControlledFailureException($"Unable to create the configuration encryption key `{keyFilePath}` for the instance `{instanceName}`, so the instance was not created: {e.Message} " | ||
| + $"Run this command as root, or give the user ({user}) access to the directory, for example: `sudo mkdir -p {directory} && sudo chown -R {user} {directory} && sudo chmod 700 {directory}`.", e); |
There was a problem hiding this comment.
The suggested fix here can leave the key directory unreachable on a host with a hardened umask.
mkdir -p creates the missing parents with the caller's umask, and Tentacle only sets 0755 on directories it creates itself. Simulating the command under umask 027 gives:
750 root /var/lib/octopus
750 root /var/lib/octopus/tentacle
750 root /var/lib/octopus/tentacle/<instance>
700 <user> /var/lib/octopus/tentacle/<instance>/keys
The user owns keys but can't traverse the three parents to get to it. I checked the file-system part; the rest is from reading the code:
- Retrying
create-instanceas that user fails with this same error and this same command, so they're stuck in a loop. - If root then runs
upgrade-configuration-encryption, the key is created and handed to the service user, but the service can't start. The "exists but the user cannot read it" message suggestschown/chmodonkeys, which are already correct. - If root only runs
service --install, the service keeps working on the legacy key and warns "Unable to move the configuration to its own encryption key" on every start.
The same thing happens if anything else pre-creates /var/lib/octopus with a tight mode.
NonRootCreateInstanceTests doesn't catch it because it runs the printed fix under the test's normal umask, and the new hardened-umask test lets Tentacle create every directory itself.
Could the suggested command set the parent modes explicitly? For example install -d -m 755 for the parents and install -d -m 700 -o <user> for keys. It would also help if the "cannot read it" message said every parent directory needs to be traversable.
Generated by Claude Code
There was a problem hiding this comment.
Thanks for digging into this. I'm going to leave the command as is. A host with a hardened umask is already managed by an admin who handles permissions, and a command that covers every umask gets hard to read. If the key isn't readable, the error still points at the key directory, so they have somewhere to start.
There was a problem hiding this comment.
For reference, the install -d version would look like this:
sudo install -d -m 755 /var/lib/octopus /var/lib/octopus/tentacle /var/lib/octopus/tentacle/<instance> \
&& sudo install -d -m 700 -o <user> /var/lib/octopus/tentacle/<instance>/keys
It's also a bit more involved than it first looks:
- Every parent has to be listed explicitly, otherwise
install -dcreates the missing ones with root's umask and the bug comes back. So the code would have to build that list and decide where to stop, including for a custom data directory set by environment variable. install -d -m 755also changes the mode of parents that already exist, so it would loosen a directory an admin had locked down on purpose.
That's more than I want in an error message, which is part of why I'm leaving it.
| public class LinuxMachineKeyEncryptorTests | ||
| { | ||
| [Test] | ||
| public void WhenAValueIsEncryptedThenItIsVersionedAndDecrypts() |
There was a problem hiding this comment.
Could we add a known-answer test for the new format, the way LegacyCiphertextCompatibilityTests does for the old one?
All three tests in this class encrypt and decrypt with the same code, so they still pass if the stored format drifts. I checked by mutating a copy of LinuxMachineKeyEncryptor and running these three tests plus a known-answer test against it:
| Change to the encryptor | These three tests | Known-answer test |
|---|---|---|
| None | pass | passes |
| Stop passing the associated data, on both encrypt and decrypt | pass | fails |
| Encode the plaintext as UTF-16 instead of UTF-8 | pass | fails |
Once this ships, a change like either of those means upgraded Tentacles can't read their certificates, so it seems worth pinning now.
Here is a vector generated with Node's crypto from the format in the RFC, not with this code. It decrypts with the current LinuxMachineKeyEncryptor:
key file contents: AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=
stored value: AESGCM-V1$AAECAwQFBgcICQoL$I7lSH4DKt1wvmL7GctHp4w==$N8FyaLaSAa3/Jbd7LnnhTfS/81zQCC8dWwKWpTtJc8tscsGQ3OA=
plaintext: pässwörd 🐙 with spaces & symbols!
The key is bytes 0 to 31, the nonce is bytes 0 to 11, and the associated data is ASCII AESGCM-V1.
Generated by Claude Code
There was a problem hiding this comment.
It's interesting that you should ask for such a test; this is similar to what I would like to do for JSON stored in the aggregate. At least here its a super tiny test :D
There was a problem hiding this comment.
Good call, added in 458d333 using your vector.
There was a problem hiding this comment.
Added, I can't believe I missed this case given my position on JSON deserialisation tests.
| ConfigurationFilePermissions.RestrictToServiceUser(instanceSelector.Current.ConfigurationPath, serviceConfigurationState.Username, log); | ||
|
|
||
| // A non-root service cannot create its key under /var/lib/octopus, so it is created here while running as root. | ||
| configurationEncryptionUpgrade.Value.TryPrepareKey(); |
There was a problem hiding this comment.
Nothing tests that service --install --username <user> leaves the key readable by that user.
It works today because of ordering: RestrictToServiceUser gives the config to the service user, then TryPrepareKey gives the key to the config's owner. No test passes --username to service, and ServiceCommand has no unit tests, so swapping these two calls or dropping this one would pass CI. Because this is the Try variant, the install itself wouldn't fail either. From reading the code, the first symptom would be the service failing to start because it can't read its key, on the standard non-root install path.
WhenRootUpgradesUnderAHardenedUmask_ThenTheServiceUserCanStillReadItsKey covers the shared chown logic through upgrade-configuration-encryption, but not this wiring. Could we add a sibling that runs service --install --username <user> as root and then show-thumbprint as that user? LinuxConfigureServiceHelperFixture already uses systemd under RequiresSudoOnLinux, so it should run on the same agents.
Generated by Claude Code
There was a problem hiding this comment.
🫠 we don't have this test in tentacle already.
There was a problem hiding this comment.
I had a look at this from the perspective of the plan in the RFC.
-
Now replace-certificate does not create the key, the behaviour in the PR has drifted a bit from the PR. I guess this doesn't matter, since it is deliberate, and the RFC is a point-in-time request for comment and not documentation that needs updating.
-
Apart from that, the only thing I spotted that doesn't match the RFC is the atomicity of key creation, and that's covered by a separate comment.
…ask" This reverts commit 8cfd0a9.
…encryption-key # Conflicts: # source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsFixture.cs # source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsTests.cs # source/Octopus.Tentacle.Tests.Integration/Configuration/LinuxConfigurationFilePermissionsTests.cs # source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs # source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsFixture.cs # source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsTests.cs # source/Octopus.Tentacle.Tests/Configuration/LinuxConfigurationFilePermissionsTests.cs # source/Octopus.Tentacle/Commands/RunAgentCommand.cs # source/Octopus.Tentacle/Configuration/LinuxConfigurationFilePermissions.cs # source/Octopus.Tentacle/Startup/ServiceCommand.cs
…able by that user
sburmanoctopus
left a comment
There was a problem hiding this comment.
Luke and I pair reviewed this.
Fixes: #1370
Fixes LEV-1171. RFC: Stop deriving Linux Tentacle's configuration encryption key from /etc/machine-id. Supersedes #1307 and #1317.
Why
On Linux, Tentacle encrypts its certificate and proxy passwords in
tentacle.configwith a key derived from/etc/machine-id. Anyone on the machine can read that file, and every container from our Docker image had the same one. So anyone who got hold of a container'stentacle.configcould decrypt its certificate (FD-601).What Tentacle does now
Each Linux Tentacle instance gets its own randomly generated encryption key. Only the user Tentacle runs as can read it. The key is kept outside
/etc/octopuson purpose, so a copy of the configuration doesn't come with the key that unlocks it.Windows and the Kubernetes agent are unchanged.
Where the keys are
/var/lib/octopus/tentacle/<instance>/keys/config-encryption.key/etc/machine-id/etc/octopus/machinekeyTentacle never creates or changes the last two any more. Once an instance has been upgraded, it no longer needs them.
What to back up
/etc/octopus, the configuration./var/lib/octopus/tentacle, the keys.Back them up together. The configuration can't be decrypted without its key. If the key is lost and there is no backup, run
reset-configuration-encryptionto remove the settings it protected and create a new key, re-enter any proxy password withproxyorpolling-proxy, then runreplace-certificateto give the Tentacle a new certificate and update Octopus Server to trust it.When the configuration is upgraded
upgrade-configuration-encryption. See below.No going back after the upgrade
Older Tentacles can't read settings encrypted with the new key. To downgrade, restore a
tentacle.configfrom before the upgrade, or downgrade and runreplace-certificate.This ships as a major version.
Key creation
When a service is installed or reconfigured as root, (
service --installorservice --reconfigure), Tentacle will attempt to create the key. That key can be used next time tentacle runs to upgrade the config. This ensures that the service user can decrypt Tentacle.config, when tentacle runs.New command:
upgrade-configuration-encryptionRuns the upgrade now instead of waiting for the next start. It creates the instance's key, gives it to the owner of the configuration file, and re-encrypts the certificate and proxy passwords. Unlike the upgrade on start, it fails loudly if anything goes wrong. Use it to move a non-root Tentacle over without reinstalling the service:
How to check whether an instance has been upgraded
Settings encrypted with the new key start with
AESGCM-V1$. Settings still on the old key are a plain base64 string with no$in it.<set key="Tentacle.Certificate">AESGCM-V1$...$...$...</set><set key="Tentacle.Certificate">kX9f...</set>The Tentacle log also says
Re-encrypted the protected setting '...'for each setting it upgraded.Docker
Until now, upgrading the Tentacle image lost the Tentacle's identity even with
/etc/octopuson a volume. Each image build created its own/etc/machine-id, so a new image couldn't decrypt the certificate the old one had saved. Now the key lives on a volume with the configuration, so the image can be upgraded freely.To keep a Tentacle across image upgrades, mount both of these:
/etc/octopus/var/lib/octopus/tentacle/etc/machine-id.Unnamed instances do not support the new encryption.
A configuration that isn't registered as an instance can't get its own key, so it stays on the old one and Tentacle warns about it. Register it with
create-instance --instance <name> --config <file>to fix that.