Repository navigation
Restrict Tentacle config file permissions and ownership on Linux #1349
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
602c5e6
Restrict Tentacle config file permissions and ownership on Linux
LukeButters 3c50599
Move config permission handling into ConfigurationFilePermissions and…
LukeButters abac45e
Use a non-root service user in the symlink test so it runs when the a…
LukeButters File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
41 changes: 41 additions & 0 deletions
41
...e/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsFixture.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| #if NET | ||
| using System; | ||
| using System.IO; | ||
| using System.Linq; | ||
| using System.Runtime.Versioning; | ||
| using System.Threading.Tasks; | ||
| using FluentAssertions; | ||
| using NUnit.Framework; | ||
| using Octopus.Tentacle.CommonTestUtils.Diagnostics; | ||
| using Octopus.Tentacle.Configuration; | ||
| using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; | ||
| using Octopus.Tentacle.Tests.Integration.Util; | ||
| using Octopus.Tentacle.Util; | ||
|
|
||
| namespace Octopus.Tentacle.Tests.Integration.Configuration | ||
| { | ||
| [TestFixture] | ||
| [LinuxTest] | ||
| [NonParallelizable] | ||
| [UnsupportedOSPlatform("windows")] | ||
| public class ConfigurationFilePermissionsFixture | ||
| { | ||
| [Test] | ||
| [RequiresSudoOnLinux] | ||
| public async Task WhenRestrictedToTheServiceUserThenOnlyThatUserOwnsAndCanReadTheConfig() | ||
| { | ||
| var user = new LinuxTestUserPrincipal("octo-config-perm-test"); | ||
| var configurationFile = Path.GetTempFileName(); | ||
| File.SetUnixFileMode(configurationFile, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead); | ||
| var log = new InMemoryLog(); | ||
|
|
||
| ConfigurationFilePermissions.RestrictToServiceUser(configurationFile, user.UserName, log); | ||
|
|
||
| log.GetLog().Should().NotContain("Unable to restrict"); | ||
| File.GetUnixFileMode(configurationFile).Should().Be(ConfigurationFilePermissions.OwnerOnly); | ||
| var owner = await new CommandLineInvocation("/bin/bash", $"-c \"stat -c '%U' {configurationFile}\"").ExecuteCommandAsync(); | ||
| owner.Infos.Single().Should().Be(user.UserName); | ||
| } | ||
| } | ||
| } | ||
| #endif |
61 changes: 61 additions & 0 deletions
61
source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsFixture.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| #if NET | ||
| using System; | ||
| using System.IO; | ||
| using System.Runtime.Versioning; | ||
| using FluentAssertions; | ||
| using NUnit.Framework; | ||
| using Octopus.Tentacle.Configuration; | ||
| using Octopus.Tentacle.Tests.Support; | ||
| using Octopus.Tentacle.Util; | ||
|
|
||
| namespace Octopus.Tentacle.Tests.Configuration | ||
| { | ||
| [TestFixture] | ||
| [UnsupportedOSPlatform("windows")] | ||
| public class ConfigurationFilePermissionsFixture | ||
| { | ||
| [SetUp] | ||
| public void SkipOnWindows() | ||
| { | ||
| if (OperatingSystem.IsWindows()) | ||
| { | ||
| Assert.Ignore("Unix file modes only"); | ||
| } | ||
| } | ||
|
|
||
| [Test] | ||
| public void WhenAWorldReadableConfigIsRestrictedThenOnlyItsOwnerCanReadIt() | ||
| { | ||
| var configurationFile = Path.GetTempFileName(); | ||
| File.SetUnixFileMode(configurationFile, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead); | ||
|
|
||
| ConfigurationFilePermissions.RestrictToOwner(configurationFile, new InMemoryLog()); | ||
|
|
||
| File.GetUnixFileMode(configurationFile).Should().Be(ConfigurationFilePermissions.OwnerOnly); | ||
| } | ||
|
|
||
| [Test] | ||
| public void WhenAnEmptyConfigIsCreatedThenOnlyItsOwnerCanReadIt() | ||
| { | ||
| var configurationFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); | ||
|
|
||
| ConfigurationFilePermissions.CreateEmpty(new OctopusPhysicalFileSystem(new InMemoryLog()), configurationFile, "<octopus-settings />"); | ||
|
|
||
| File.GetUnixFileMode(configurationFile).Should().Be(ConfigurationFilePermissions.OwnerOnly); | ||
| } | ||
|
|
||
| [Test] | ||
| public void WhenTheConfigIsASymlinkThenItIsNotGivenToTheServiceUser() | ||
| { | ||
| var target = Path.GetTempFileName(); | ||
| var configurationFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); | ||
| File.CreateSymbolicLink(configurationFile, target); | ||
| var log = new InMemoryLog(); | ||
|
|
||
| ConfigurationFilePermissions.RestrictToServiceUser(configurationFile, "nobody", log); | ||
|
|
||
| log.GetLog().Should().Contain("symbolic link"); | ||
| } | ||
| } | ||
| } | ||
| #endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
140 changes: 140 additions & 0 deletions
140
source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| using System; | ||
| using System.IO; | ||
| using Octopus.Tentacle.Core.Diagnostics; | ||
| using Octopus.Tentacle.Util; | ||
| #if NET | ||
| using System.Diagnostics; | ||
| using System.Runtime.InteropServices; | ||
| using System.Runtime.Versioning; | ||
| using Microsoft.Win32.SafeHandles; | ||
| #endif | ||
|
|
||
| namespace Octopus.Tentacle.Configuration | ||
| { | ||
| // The config holds protected settings, so only its owner may read it. The service user must therefore own it. | ||
| static class ConfigurationFilePermissions | ||
| { | ||
| #if NET | ||
| public const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite; | ||
| const uint UnchangedGroup = uint.MaxValue; | ||
| #endif | ||
|
|
||
| public static void CreateEmpty(IOctopusFileSystem fileSystem, string configurationPath, string contents) | ||
| { | ||
| #if NET | ||
| if (!OperatingSystem.IsWindows()) | ||
| { | ||
| using var stream = new FileStream(configurationPath, new FileStreamOptions | ||
| { | ||
| Mode = FileMode.CreateNew, | ||
| Access = FileAccess.Write, | ||
| UnixCreateMode = OwnerOnly | ||
| }); | ||
| using var writer = new StreamWriter(stream); | ||
| writer.Write(contents); | ||
| return; | ||
| } | ||
| #endif | ||
| fileSystem.OverwriteFile(configurationPath, contents); | ||
| } | ||
|
|
||
| public static void RestrictToOwner(string? configurationPath, ISystemLog log) | ||
| { | ||
| #if NET | ||
| if (OperatingSystem.IsWindows() || string.IsNullOrWhiteSpace(configurationPath) || !File.Exists(configurationPath)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| var previousMode = File.GetUnixFileMode(configurationPath); | ||
| if (previousMode != OwnerOnly) | ||
| { | ||
| File.SetUnixFileMode(configurationPath, OwnerOnly); | ||
| log.Info($"Restricted `{configurationPath}` from {Convert.ToString((int)previousMode, 8).PadLeft(4, '0')} to 0600"); | ||
| } | ||
| } | ||
| catch (Exception ex) when (ex is UnauthorizedAccessException or IOException) | ||
| { | ||
| log.Warn($"Unable to restrict `{configurationPath}` to its owner, so other users may be able to read it: {ex.Message}"); | ||
| } | ||
| #endif | ||
| } | ||
|
|
||
| public static void RestrictToServiceUser(string? configurationPath, string? userName, ISystemLog log) | ||
| { | ||
| #if NET | ||
| if (OperatingSystem.IsWindows() | ||
| || string.IsNullOrWhiteSpace(configurationPath) | ||
| || string.IsNullOrWhiteSpace(userName) | ||
| || userName == "root") | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var error = TryRestrictToServiceUser(configurationPath, userName); | ||
| if (error != null) | ||
| { | ||
| log.Warn($"Unable to restrict `{configurationPath}` to `{userName}`: {error.TrimEnd('.')}. Only the service user should be able to read and write the configuration file, so check its owner and permissions."); | ||
| } | ||
| #endif | ||
| } | ||
|
|
||
| #if NET | ||
| [UnsupportedOSPlatform("windows")] | ||
| static string? TryRestrictToServiceUser(string configurationPath, string userName) | ||
| { | ||
| try | ||
| { | ||
| if (new FileInfo(configurationPath).LinkTarget != null) | ||
| { | ||
| return $"`{configurationPath}` is a symbolic link."; | ||
| } | ||
|
|
||
| var userId = GetUserId(userName); | ||
| if (userId == null) | ||
| { | ||
| return $"Unable to find the user `{userName}`."; | ||
| } | ||
|
|
||
| using var stream = new FileStream(configurationPath, FileMode.Open, FileAccess.Read); | ||
| File.SetUnixFileMode(stream.SafeFileHandle, OwnerOnly); | ||
| return fchown(stream.SafeFileHandle, userId.Value, UnchangedGroup) == 0 | ||
| ? null | ||
| : Marshal.GetLastPInvokeErrorMessage(); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| return ex.Message; | ||
| } | ||
| } | ||
|
|
||
| static uint? GetUserId(string userName) | ||
| { | ||
| if (userName.StartsWith("-", StringComparison.Ordinal)) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| 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; | ||
| } | ||
| catch (Exception) | ||
| { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| [DllImport("libc", SetLastError = true)] | ||
| static extern int fchown(SafeFileHandle fd, uint owner, uint group); | ||
| #endif | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 thegetpwnamchange.Rhys: I've always held this stance, but feel free to disagree.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lets do it.