Repository navigation
Restrict Tentacle config file permissions and ownership on Linux - #1349
Conversation
These now live in #1349. Only the new key file keeps its owner-only mode, since it holds the configuration encryption key.
These now live in #1349. Only the new key file keeps its owner-only mode, since it holds the configuration encryption key.
rhysparry
left a comment
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
🤖 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.
| public static void RestrictToOwner(string configurationPath) | ||
| => File.SetUnixFileMode(configurationPath, OwnerOnly); | ||
|
|
||
| public static string? TryRestrictToServiceUser(string configurationPath, string userName) |
There was a problem hiding this comment.
🤖 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.
| 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; | ||
| } |
There was a problem hiding this comment.
🤖 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.
There was a problem hiding this comment.
Yeah calling getpwname seems um pretty complex.
I think though wrapping this in a try catch would make sense.
Agreed on the name
| [DllImport("libc", SetLastError = true)] | ||
| static extern int fchown(int fd, uint owner, uint group); |
There was a problem hiding this comment.
🤖 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.
| [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.
There was a problem hiding this comment.
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."); |
There was a problem hiding this comment.
🤖 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.configtotentacle: 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.
There was a problem hiding this comment.
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 }); |
There was a problem hiding this comment.
🤖 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.
| 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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
🤖 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.
| 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.
There was a problem hiding this comment.
Yeah lets do that
| if (OperatingSystem.IsWindows() || string.IsNullOrWhiteSpace(configurationPath) || !File.Exists(configurationPath)) | ||
| return; |
There was a problem hiding this comment.
🤖 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.
| 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.
There was a problem hiding this comment.
sure, it doesn't bother me
| if (!(serviceConfigurationState.Install || serviceConfigurationState.Reconfigure) | ||
| || OperatingSystem.IsWindows() | ||
| || string.IsNullOrWhiteSpace(configurationPath) | ||
| || string.IsNullOrWhiteSpace(userName) | ||
| || userName == "root") | ||
| return; |
There was a problem hiding this comment.
🤖 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.
| 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.
| 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}`."; |
There was a problem hiding this comment.
🤖 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.
| 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.
|
🤖 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:
On the "install path has no automated test" gap: The rest are nits: naming, comment wording, line widths, braces on single-line Related follow-up (outside this diff): Rhys: I think there are some opportunities to move some of the logic into the shared |
rhysparry
left a comment
There was a problem hiding this comment.
✅ 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.
75e1164 to
e0a2d44
Compare
These now live in #1349. Only the new key file keeps its owner-only mode, since it holds the configuration encryption key.
e0a2d44 to
602c5e6
Compare
These now live in #1349. Only the new key file keeps its owner-only mode, since it holds the configuration encryption key.
… test the service user chown
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
create-instancecreatestentacle.configas 0600 on non-Windows hosts. The mode is set when the file is opened, so it is never readable by other users.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
sudo tentacle create-instanceis root-owned 0600 untilservice --install --username Xhands 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/machinekeyis not changed here.