Skip to content

Restrict Tentacle config file permissions and ownership on Linux - #1349

Merged
LukeButters merged 3 commits into
mainfrom
luke/lev-2213-restrict-config-permissions
Nov 16, 2026
Merged

LukeButters merged 3 commits into
mainfrom
luke/lev-2213-restrict-config-permissions

Conversation

@LukeButters

@LukeButters LukeButters commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Fixes: #1351
Fixes: LEV-2213

Tentacle config is no longer world-readable and is now owned by the service user.

This is a major version bump (+semver: major), because installs that rely on other users reading the config will no longer be able to.

Changes

  • On creation: create-instance creates tentacle.config as 0600 on non-Windows hosts. The mode is set when the file is opened, so it is never readable by other users.
  • On agent start: the config is set to 0600. This runs as the service user, the one that must read the file, so it can't lock the service out. If it fails, for example because the agent doesn't own the file, Tentacle logs a warning and carries on.
  • On install: service --install/--reconfigure --username X, run as root, sets the config to 0600 and makes X its owner, both on the same open handle. Group ownership is unchanged. It refuses if the config is a symlink. If any of this fails, install logs a warning and carries on.

Known gaps

  • Between the symlink check and the open there is a small race. Exploiting it needs write access to the config directory, and anyone with that can already edit the config.
  • A config created by sudo tentacle create-instance is root-owned 0600 until service --install --username X hands it over. A non-root service set up some other way, such as a hand-written systemd unit, can't read it until it is chowned.
  • /etc/octopus/machinekey is not changed here.
  • The install path has no automated test, because it needs root and a second user. Only the symlink refusal and the chmod are tested.

@LukeButters
LukeButters requested a review from a team as a code owner November 13, 2026 01:40
@LukeButters LukeButters changed the title Restrict Tentacle config file to owner-only on Linux Restrict Tentacle config file permissions and ownership on Linux Nov 13, 2026
LukeButters added a commit that referenced this pull request Nov 15, 2026
These now live in #1349. Only the new key file keeps its owner-only mode, since
it holds the configuration encryption key.
LukeButters added a commit that referenced this pull request Nov 16, 2026
These now live in #1349. Only the new key file keeps its owner-only mode, since
it holds the configuration encryption key.

@rhysparry rhysparry 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.

Inline notes from Rhys. Each comment shows which parts were drafted by an AI agent.

public const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
const uint UnchangedGroup = uint.MaxValue;

// Only the agent calls this, as the service user, so it can never lock that user out of the config.

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.

🤖 Agent's comment, endorsed by Rhys

Nit: the conclusion is right, but the reason given isn't quite why. RestrictToOwner also runs from an interactive tentacle run, which any user can run, so "as the service user" doesn't always hold. It's safe anyway because chmod never changes the owner, and the owner is meant to be the service user. Could the comment state that invariant? For example:

// The service user owns the config, so restricting it to its owner never locks the service out, whoever runs the agent.

Rhys: The AI was particularly caught up on this point. It ended up getting confused about possibly having the file owned by another user and using the group level permission to access it.

I'd be inclined to delete the comment. "Restrict To Owner" is exactly what the method does, and callers need to be responsible for not misusing it, which a comment most assuredly cannot enforce.

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.

agreed

public static void RestrictToOwner(string configurationPath)
=> File.SetUnixFileMode(configurationPath, OwnerOnly);

public static string? TryRestrictToServiceUser(string configurationPath, string userName)

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.

🤖 Agent's comment, endorsed by Rhys

Naming nit: in .NET, a Try prefix usually means "returns bool, result in an out parameter". Returning a nullable error string with null meaning success reads backwards at the call site (if (error != null)).

Something like bool TryRestrictToServiceUser(string configurationPath, string userName, [NotNullWhen(false)] out string? error) would match the convention. Or drop the Try and name it for what it returns.

Rhys: Maybe we should just throw exceptions and catch it at the call site. Or add a GetErrorMessage suffix or something.

Not a blocker.

Comment on lines +44 to +56
static uint? UserId(string userName)
{
if (userName.StartsWith("-", StringComparison.Ordinal))
return null;

var startInfo = new ProcessStartInfo("id") { UseShellExecute = false, RedirectStandardOutput = true };
startInfo.ArgumentList.Add("-u");
startInfo.ArgumentList.Add(userName);
using var process = Process.Start(startInfo)!;
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return process.ExitCode == 0 && uint.TryParse(output.Trim(), out var userId) ? userId : null;
}

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.

🤖 Agent's comment, endorsed by Rhys

We already P/Invoke libc for fchown, so it might be worth looking up the UID with getpwnam (or getpwnam_r) too, instead of shelling out to id. That would avoid spawning a process and the PATH lookup for id while running as root during install, and the StartsWith("-") guard and Process.Start(...)! could go. The trade-off is marshalling struct passwd, which is more code than what's here, so I can see the argument for keeping id.

If we keep it, id -u -- <name> should stop the name being parsed as an option, which might let the guard go.

Naming nit: UserId(string) reads a bit like a property. Maybe GetUserId or LookupUserId?

Rhys: I had a brief look at the man page for getpwnam, so if we'd rather avoid it, that's understandable (although I was wondering the same thing as I manually perused the code while I had claude running in the background). I agree with the naming suggestion, but I'm not too concerned for a private method.

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.

Yeah calling getpwname seems um pretty complex.

I think though wrapping this in a try catch would make sense.

Agreed on the name

Comment on lines +58 to +59
[DllImport("libc", SetLastError = true)]
static extern int fchown(int fd, uint owner, uint group);

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.

🤖 Agent's comment, endorsed by Rhys

Something to consider: if this takes a SafeFileHandle, the marshaller AddRefs and Releases the handle around the call, and line 34 wouldn't need DangerousGetHandle() or the cast. It would just be fchown(stream.SafeFileHandle, userId.Value, UnchangedGroup). It would also need using Microsoft.Win32.SafeHandles;.

Caveat: fd is an int in C, and a SafeHandle marshals as a pointer-sized value. I'd expect that to work on x64 and arm64, where the argument goes in a register, but strictly it's a signature mismatch. Keeping int and wrapping the call in DangerousAddRef/DangerousRelease would avoid that, if you'd rather.

Suggested change
[DllImport("libc", SetLastError = true)]
static extern int fchown(int fd, uint owner, uint group);
[DllImport("libc", SetLastError = true)]
static extern int fchown(SafeFileHandle fd, uint owner, uint group);

Rhys: I suspect this isn't actually a problem because we're just passing this to fchown rather than something that will hold onto the value. That said, if the suggestion properly works to eliminate the need to call a method labelled Dangerous and whose documentation has a big red warning banner, maybe that's for the best.

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.

Ok lets do it lets use SafeFileHandle


var error = ConfigurationFilePermissions.TryRestrictToServiceUser(configurationPath, userName);
if (error != null)
log.Warn($"Unable to restrict `{configurationPath}` to `{userName}`: {error} Only the service user should be able to read and write the configuration file, so check its owner and permissions.");

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.

🤖 Agent's comment, endorsed by Rhys

When fchown fails, error comes from Marshal.GetLastPInvokeErrorMessage(). As far as I know, that's strerror text with no trailing full stop, so the warning would read something like:

Unable to restrict …/tentacle.config to tentacle: Operation not permitted Only the service user should…

The custom messages above end in a full stop, so this probably only shows up on the P/Invoke failure path. Normalising it (e.g. error.TrimEnd('.') + "."), or putting the guidance in a separate sentence, would avoid it.

Nit: the line is about 210 characters. There are already long lines in this file, so take it or leave it.

Rhys: I think it would definitely read better if the message was properly distinct from its placement in the final error shown.

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.

Lets go with two sentences.

#if NET
if (!OperatingSystem.IsWindows())
{
using var stream = new FileStream(configurationFile, new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, UnixCreateMode = ConfigurationFilePermissions.OwnerOnly });

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.

🤖 Agent's comment, endorsed by Rhys

Nit: this line is about 205 characters. Splitting the initialiser might help.

Also, on non-Windows this bypasses IOctopusFileSystem. I couldn't find any tests that use ApplicationInstanceManager today, so it doesn't matter yet, but a test with a substitute filesystem would end up writing to the real disk. An overload on the abstraction that takes a UnixFileMode is one option, though that may be more than this PR needs.

Suggested change
using var stream = new FileStream(configurationFile, new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, UnixCreateMode = ConfigurationFilePermissions.OwnerOnly });
using var stream = new FileStream(configurationFile, new FileStreamOptions
{
Mode = FileMode.CreateNew,
Access = FileAccess.Write,
UnixCreateMode = ConfigurationFilePermissions.OwnerOnly
});

Rhys: I'd improve the wrapping as it makes it easier.

This is our local copy of IOctopusFileSystem I think, so maybe there is something to that suggestion. Not a huge deal, especially if there really are no tests leaving behind random files.

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.

Improve the formatting to make it easier to read as suggested:

                using var stream = new FileStream(configurationFile, new FileStreamOptions
                {
                    Mode = FileMode.CreateNew,
                    Access = FileAccess.Write,
                    UnixCreateMode = ConfigurationFilePermissions.OwnerOnly
                });

Lets not worry about left over files on ephemeral test servers for code that isn't tested.


// Arrange
var configurationFile = Path.GetTempFileName();
File.SetUnixFileMode(configurationFile, (UnixFileMode)0b110_100_100);

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.

🤖 Agent's comment, endorsed by Rhys

Nit: named flags might read more easily than a binary literal, and would match how the assertion is written.

Also, neither test deletes what it creates: the temp file here, plus the target and symlink in the second test, stay in the temp directory. A try/finally or a TearDown would clean them up.

Suggested change
File.SetUnixFileMode(configurationFile, (UnixFileMode)0b110_100_100);
File.SetUnixFileMode(configurationFile, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead);

Rhys: I think I get what you (or Claude) was trying to achieve with this, but it's not super readable. Explicit flags would be a bit clearer.

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.

Yeah lets do that

Comment on lines +147 to +148
if (OperatingSystem.IsWindows() || string.IsNullOrWhiteSpace(configurationPath) || !File.Exists(configurationPath))
return;

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.

🤖 Agent's comment, endorsed by Rhys

Nit: please put braces around single-statement if bodies, even early returns. The same applies in ServiceCommand.RestrictConfigurationToServiceUser and the three guards in ConfigurationFilePermissions.

Suggested change
if (OperatingSystem.IsWindows() || string.IsNullOrWhiteSpace(configurationPath) || !File.Exists(configurationPath))
return;
if (OperatingSystem.IsWindows() || string.IsNullOrWhiteSpace(configurationPath) || !File.Exists(configurationPath))
{
return;
}

Rhys: I've always held this stance, but feel free to disagree.

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.

sure, it doesn't bother me

Comment on lines +132 to +137
if (!(serviceConfigurationState.Install || serviceConfigurationState.Reconfigure)
|| OperatingSystem.IsWindows()
|| string.IsNullOrWhiteSpace(configurationPath)
|| string.IsNullOrWhiteSpace(userName)
|| userName == "root")
return;

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.

🤖 Agent's comment, endorsed by Rhys

Nit: braces here too. With a multi-line condition, I find an unbraced return; a bit easier to misread.

Suggested change
if (!(serviceConfigurationState.Install || serviceConfigurationState.Reconfigure)
|| OperatingSystem.IsWindows()
|| string.IsNullOrWhiteSpace(configurationPath)
|| string.IsNullOrWhiteSpace(userName)
|| userName == "root")
return;
if (!(serviceConfigurationState.Install || serviceConfigurationState.Reconfigure)
|| OperatingSystem.IsWindows()
|| string.IsNullOrWhiteSpace(configurationPath)
|| string.IsNullOrWhiteSpace(userName)
|| userName == "root")
{
return;
}

Rhys: I've always held this stance, but feel free to disagree.

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.

lets do it.

Comment on lines +25 to +30
if (new FileInfo(configurationPath).LinkTarget != null)
return $"`{configurationPath}` is a symbolic link.";

var userId = UserId(userName);
if (userId == null)
return $"Unable to find the user `{userName}`.";

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.

🤖 Agent's comment, endorsed by Rhys

Nit: braces on these guards, and on the StartsWith("-") guard at line 46 if that survives the getpwnam change.

Suggested change
if (new FileInfo(configurationPath).LinkTarget != null)
return $"`{configurationPath}` is a symbolic link.";
var userId = UserId(userName);
if (userId == null)
return $"Unable to find the user `{userName}`.";
if (new FileInfo(configurationPath).LinkTarget != null)
{
return $"`{configurationPath}` is a symbolic link.";
}
var userId = UserId(userName);
if (userId == null)
{
return $"Unable to find the user `{userName}`.";
}

Rhys: I've always held this stance, but feel free to disagree.

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.

lets do it.

@rhysparry

Copy link
Copy Markdown
Contributor

🤖 Agent's comment, endorsed by Rhys

Thanks, the overall approach looks good to me. I like that the mode is set at creation and that the chmod/chown both happen on one open handle. I've left some inline comments, mostly small. The ones that might be worth a look:

  • UID lookup: since we already P/Invoke libc, getpwnam could replace shelling out to id, though there's a marshalling trade-off.
  • Visibility: logging when the start-up chmod actually changes the mode might help when diagnosing the breaking change.
  • Shared logic: there's an opportunity to move more of the logic into the shared ConfigurationFilePermissions class, for example creating the empty configuration file with the right permissions, which currently lives in ApplicationInstanceManager.

On the "install path has no automated test" gap: LinuxTestUserPrincipal in the test project already creates a throwaway user with sudo useradd. If the CI Linux agents allow that, it might be usable for a [LinuxTest] covering the chown path.

The rest are nits: naming, comment wording, line widths, braces on single-line ifs, a possibly run-together log message, and test cleanup.

Related follow-up (outside this diff): new-certificate --export-file (NewCertificateCommand.cs:53-56) writes the new certificate, including its private key, as an unprotected base64 PFX via File.WriteAllText. With a typical umask of 022, that file is 0644, so other users can read the private key, which arguably makes it more exposed than the config, where the certificate is machine-key protected. --export-pfx also writes 0644, though that file is password-protected. Creating both as 0600, as this PR does for the config, seems like a natural follow-up.

Rhys: I think there are some opportunities to move some of the logic into the shared ConfigurationFilePermission class. For example, populating the empty configuration file with the appropriate permissions.

@rhysparry rhysparry 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.

✅ LGTM - I think this right, but the various commands certainly confuses things. It would be good if everything went through one thing that just made sure it was configured properly.

@LukeButters
LukeButters force-pushed the luke/lev-2213-restrict-config-permissions branch from 75e1164 to e0a2d44 Compare November 16, 2026 22:41
LukeButters added a commit that referenced this pull request Nov 16, 2026
These now live in #1349. Only the new key file keeps its owner-only mode, since
it holds the configuration encryption key.
@LukeButters
LukeButters force-pushed the luke/lev-2213-restrict-config-permissions branch from e0a2d44 to 602c5e6 Compare November 16, 2026 22:42
LukeButters added a commit that referenced this pull request Nov 16, 2026
These now live in #1349. Only the new key file keeps its owner-only mode, since
it holds the configuration encryption key.
@LukeButters
LukeButters enabled auto-merge (squash) November 16, 2026 23:02
@LukeButters
LukeButters merged commit b2baf20 into main Nov 16, 2026
46 checks passed
@LukeButters
LukeButters deleted the luke/lev-2213-restrict-config-permissions branch November 16, 2026 23:37
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.

Tentacle config file is readable by other local users on Linux

2 participants