Skip to content

Stop deriving Linux Tentacle's config encryption key from /etc/machine-id - #1348

Merged
LukeButters merged 129 commits into
mainfrom
luke/lev-1171-config-encryption-key
Nov 26, 2026
Merged

LukeButters merged 129 commits into
mainfrom
luke/lev-1171-config-encryption-key

Conversation

@LukeButters

@LukeButters LukeButters commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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.config with 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's tentacle.config could 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/octopus on 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

Path What it is Used for
/var/lib/octopus/tentacle/<instance>/keys/config-encryption.key The instance's new key config that is encrypted
/etc/machine-id The machine id Only to read settings written by earlier versions
/etc/octopus/machinekey A key earlier versions generated when there was no machine id Only to read settings written by earlier versions

Tentacle 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-encryption to remove the settings it protected and create a new key, re-enter any proxy password with proxy or polling-proxy, then run replace-certificate to give the Tentacle a new certificate and update Octopus Server to trust it.

When the configuration is upgraded

  • Tentacle runs. When Tentacle is run (ie to start accepting work from Octopus), it will create the key if missing and then attempt to re-encrypt settings. If it is unable to create the key or re-encrypt, tentacle will still start.
  • When you run 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.config from before the upgrade, or downgrade and run replace-certificate.

This ships as a major version.

Key creation

When a service is installed or reconfigured as root, (service --install or service --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-encryption

Runs 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:

sudo tentacle upgrade-configuration-encryption --instance <name>

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.

grep 'Tentacle.Certificate' /etc/octopus/<instance>/tentacle.config
  • Upgraded: <set key="Tentacle.Certificate">AESGCM-V1$...$...$...</set>
  • Not upgraded yet: <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/octopus on 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:

Path Contains
/etc/octopus The configuration, including the certificate
/var/lib/octopus/tentacle The key that encrypts it
  • Mount both or neither. If only the configuration is persisted, the container refuses to start rather than create a key it would lose on the next re-create.
  • The image no longer ships a shared /etc/machine-id.
  • A configuration persisted by an earlier image can't be moved to this one, because its key came from that image's machine id. Start the new container on new volumes.

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.

@LukeButters
LukeButters force-pushed the luke/lev-1171-config-encryption-key branch from bace2af to af7dfbf Compare November 16, 2026 01:25
@LukeButters
LukeButters changed the base branch from main to luke/lev-2213-restrict-config-permissions November 16, 2026 01:25
@LukeButters
LukeButters changed the base branch from luke/lev-2213-restrict-config-permissions to main November 16, 2026 05:16
@LukeButters
LukeButters force-pushed the luke/lev-1171-config-encryption-key branch 4 times, most recently from 2c8c535 to 5edd108 Compare November 16, 2026 23:55
* 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
@LukeButters
LukeButters force-pushed the luke/lev-1171-config-encryption-key branch from e9ab6b3 to 3e06c12 Compare November 23, 2026 00:38
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 16d2564. Key failures now throw ConfigurationEncryptionKeyException, which neither the x509stores catch in RunAgentCommand nor the in-memory certificate fallback in GenerateNewCertificate catches.

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);

@gb-8 gb-8 Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method name says TryAtomic..... It should be renamed if it is not doing it atomically.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we be deleting the encryption key (and its folder) in DeleteInstance below?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-instance as 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 suggests chown/chmod on keys, 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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 -d creates 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 755 also 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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call, added in 458d333 using your vector.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🫠 we don't have this test in tentacle already.

@gb-8 gb-8 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

…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

@sburmanoctopus sburmanoctopus left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Luke and I pair reviewed this.

@LukeButters
LukeButters enabled auto-merge (squash) November 26, 2026 05:19
@LukeButters
LukeButters merged commit 2f9aed4 into main Nov 26, 2026
46 checks passed
@LukeButters
LukeButters deleted the luke/lev-1171-config-encryption-key branch November 26, 2026 06:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Linux Tentacle derives its config encryption key from /etc/machine-id

3 participants