diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsFixture.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/LinuxConfigurationFilePermissionsTests.cs similarity index 86% rename from source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsFixture.cs rename to source/Octopus.Tentacle.Tests.Integration/Configuration/LinuxConfigurationFilePermissionsTests.cs index 131e18043..072aac762 100644 --- a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsFixture.cs +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/LinuxConfigurationFilePermissionsTests.cs @@ -14,11 +14,10 @@ namespace Octopus.Tentacle.Tests.Integration.Configuration { - [TestFixture] [LinuxTest] [NonParallelizable] [UnsupportedOSPlatform("windows")] - public class ConfigurationFilePermissionsFixture + public class LinuxConfigurationFilePermissionsTests { [Test] [RequiresSudoOnLinux] @@ -29,10 +28,10 @@ public async Task WhenRestrictedToTheServiceUserThenOnlyThatUserOwnsAndCanReadTh File.SetUnixFileMode(configurationFile, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead); var log = new InMemoryLog(); - ConfigurationFilePermissions.RestrictToServiceUser(configurationFile, user.UserName, log); + new LinuxConfigurationFilePermissions(log).RestrictToServiceUser(configurationFile, user.UserName); log.GetLog().Should().NotContain("Unable to restrict"); - File.GetUnixFileMode(configurationFile).Should().Be(ConfigurationFilePermissions.OwnerOnly); + File.GetUnixFileMode(configurationFile).Should().Be(LinuxConfigurationFilePermissions.OwnerOnly); var owner = await new CommandLineInvocation("/bin/bash", $"-c \"stat -c '%U' {configurationFile}\"").ExecuteCommandAsync(); owner.Infos.Single().Should().Be(user.UserName); } diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/WindowsConfigurationFilePermissionsTests.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/WindowsConfigurationFilePermissionsTests.cs new file mode 100644 index 000000000..a37f740a0 --- /dev/null +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/WindowsConfigurationFilePermissionsTests.cs @@ -0,0 +1,65 @@ +using System; +using System.IO; +using System.Linq; +using System.Security.AccessControl; +using System.Security.Principal; +using System.Threading.Tasks; +using FluentAssertions; +using NUnit.Framework; +using Octopus.Tentacle.CommonTestUtils; +using Octopus.Tentacle.Tests.Integration.Support; +using Octopus.Tentacle.Tests.Integration.Support.TestAttributes; +#if NET +using System.Runtime.Versioning; +#endif + +namespace Octopus.Tentacle.Tests.Integration.Configuration +{ + [IntegrationTestTimeout] + [WindowsTest] +#if NET + [SupportedOSPlatform("windows")] +#endif + public class WindowsConfigurationFilePermissionsTests : IntegrationTest + { + [Test] + public async Task WhenAnInstanceIsCreatedThenOnlySystemAdministratorsAndTheCurrentUserCanAccessItsConfig() + { + using var instance = await new TentacleInstanceBuilder() + .WithName($"ConfigPermissions-{Guid.NewGuid():N}") + .WithHomeDirectory(HomeDirectoryAnyAuthenticatedUserCanModify()) + .Build(Logger, CancellationToken); + + var security = new FileInfo(instance.ConfigurationFile).GetAccessControl(); + security.AreAccessRulesProtected.Should().BeTrue(); + security.GetAccessRules(true, true, typeof(SecurityIdentifier)) + .Cast() + .Select(r => r.IdentityReference.Value) + .Distinct() + .Should() + .BeEquivalentTo(new[] + { + new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null).Value, + new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Value, + WindowsIdentity.GetCurrent().User!.Value + } + .Distinct()); + } + + // Like the default home, C:\Octopus, which inherits Authenticated Users: Modify from C:\. A config that + // inherited its folder's permissions would let every user read it. + static TemporaryDirectory HomeDirectoryAnyAuthenticatedUserCanModify() + { + var home = new TemporaryDirectory(); + var directory = new DirectoryInfo(home.DirectoryPath); + var security = directory.GetAccessControl(); + security.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), + FileSystemRights.Modify, + InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, + PropagationFlags.None, + AccessControlType.Allow)); + directory.SetAccessControl(security); + return home; + } + } +} diff --git a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs index 29c667efa..5dc535221 100644 --- a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs +++ b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs @@ -60,7 +60,8 @@ public override void SetUp() Substitute.For(), new AppVersion(GetType().Assembly), Substitute.For(), - backgroundTasks.Select(bt => new Lazy(() => bt)).ToList()); + backgroundTasks.Select(bt => new Lazy(() => bt)).ToList(), + Substitute.For()); selector.Current.Returns(new ApplicationInstanceConfiguration("MyTentacle", null, null, null)); } diff --git a/source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/LinuxConfigurationFilePermissionsTests.cs similarity index 65% rename from source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsFixture.cs rename to source/Octopus.Tentacle.Tests/Configuration/LinuxConfigurationFilePermissionsTests.cs index 42ffaf598..c06379d8e 100644 --- a/source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsFixture.cs +++ b/source/Octopus.Tentacle.Tests/Configuration/LinuxConfigurationFilePermissionsTests.cs @@ -6,32 +6,22 @@ using NUnit.Framework; using Octopus.Tentacle.Configuration; using Octopus.Tentacle.Tests.Support; -using Octopus.Tentacle.Util; namespace Octopus.Tentacle.Tests.Configuration { - [TestFixture] + [Platform(Exclude = "Win", Reason = "Unix file modes only")] [UnsupportedOSPlatform("windows")] - public class ConfigurationFilePermissionsFixture + public class LinuxConfigurationFilePermissionsTests { - [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()); + new LinuxConfigurationFilePermissions(new InMemoryLog()).RestrictToCurrentUser(configurationFile); - File.GetUnixFileMode(configurationFile).Should().Be(ConfigurationFilePermissions.OwnerOnly); + File.GetUnixFileMode(configurationFile).Should().Be(LinuxConfigurationFilePermissions.OwnerOnly); } [Test] @@ -39,9 +29,9 @@ public void WhenAnEmptyConfigIsCreatedThenOnlyItsOwnerCanReadIt() { var configurationFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); - ConfigurationFilePermissions.CreateEmpty(new OctopusPhysicalFileSystem(new InMemoryLog()), configurationFile, ""); + new LinuxConfigurationFilePermissions(new InMemoryLog()).CreateRestrictedToCurrentUser(configurationFile, ""); - File.GetUnixFileMode(configurationFile).Should().Be(ConfigurationFilePermissions.OwnerOnly); + File.GetUnixFileMode(configurationFile).Should().Be(LinuxConfigurationFilePermissions.OwnerOnly); } [Test] @@ -52,7 +42,7 @@ public void WhenTheConfigIsASymlinkThenItIsNotGivenToTheServiceUser() File.CreateSymbolicLink(configurationFile, target); var log = new InMemoryLog(); - ConfigurationFilePermissions.RestrictToServiceUser(configurationFile, "nobody", log); + new LinuxConfigurationFilePermissions(log).RestrictToServiceUser(configurationFile, "nobody"); log.GetLog().Should().Contain("symbolic link"); } diff --git a/source/Octopus.Tentacle.Tests/Configuration/WindowsConfigurationFilePermissionsTests.cs b/source/Octopus.Tentacle.Tests/Configuration/WindowsConfigurationFilePermissionsTests.cs new file mode 100644 index 000000000..c25cc2049 --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Configuration/WindowsConfigurationFilePermissionsTests.cs @@ -0,0 +1,109 @@ +using System; +using System.IO; +using System.Linq; +using System.Security.AccessControl; +using System.Security.Principal; +using FluentAssertions; +using NUnit.Framework; +using Octopus.Tentacle.Configuration; +using Octopus.Tentacle.Tests.Support; +using Octopus.Tentacle.Tests.Support.TestAttributes; +#if NET +using System.Runtime.Versioning; +#endif + +namespace Octopus.Tentacle.Tests.Configuration +{ + [WindowsTest] +#if NET + [SupportedOSPlatform("windows")] +#endif + public class WindowsConfigurationFilePermissionsTests + { + static readonly SecurityIdentifier LocalSystem = new(WellKnownSidType.LocalSystemSid, null); + static readonly SecurityIdentifier Administrators = new(WellKnownSidType.BuiltinAdministratorsSid, null); + static readonly SecurityIdentifier NetworkService = new(WellKnownSidType.NetworkServiceSid, null); + static readonly SecurityIdentifier LocalService = new(WellKnownSidType.LocalServiceSid, null); + static readonly SecurityIdentifier AuthenticatedUsers = WindowsConfigurationFileBuilder.AuthenticatedUsers; + + [Test] + public void WhenAConfigInheritsItsFolderPermissionsThenTheyAreReplacedButItsOwnEntriesAreKept() + { + using var configurationFile = new WindowsConfigurationFileBuilder().WithModifyGrantedTo(NetworkService).Build(); + + new WindowsConfigurationFilePermissions(new InMemoryLog()).RestrictToCurrentUser(configurationFile.Path); + + var security = new FileInfo(configurationFile.Path).GetAccessControl(); + security.AreAccessRulesProtected.Should().BeTrue(); + Identities(security).Should().BeEquivalentTo(RestrictedIdentities().Append(NetworkService.Value)); + } + + [Test] + public void WhenAConfigNoLongerInheritsItsFolderPermissionsThenItIsLeftAlone() + { + using var configurationFile = new WindowsConfigurationFileBuilder().NoLongerInheritingFolderPermissions().Build(); + + new WindowsConfigurationFilePermissions(new InMemoryLog()).RestrictToCurrentUser(configurationFile.Path); + + Identities(new FileInfo(configurationFile.Path).GetAccessControl()).Should().Contain(AuthenticatedUsers.Value); + } + + [Test] + public void WhenRestrictedToTheServiceUserThenOnlyThatUserSystemAndAdministratorsCanAccessIt() + { + using var configurationFile = new WindowsConfigurationFileBuilder().Build(); + var log = new InMemoryLog(); + + new WindowsConfigurationFilePermissions(log).RestrictToServiceUser(configurationFile.Path, AccountName(LocalService)); + + log.GetLog().Should().NotContain("Unable to restrict"); + var security = new FileInfo(configurationFile.Path).GetAccessControl(); + security.AreAccessRulesProtected.Should().BeTrue(); + Identities(security).Should().BeEquivalentTo(RestrictedIdentities().Append(LocalService.Value)); + Rights(security, LocalService).Should().HaveFlag(FileSystemRights.Modify).And.NotHaveFlag(FileSystemRights.ChangePermissions); + } + + [Test] + public void WhenTheServiceUserIsLocalSystemThenNoOtherUserIsGrantedAccess() + { + using var configurationFile = new WindowsConfigurationFileBuilder().Build(); + + new WindowsConfigurationFilePermissions(new InMemoryLog()).RestrictToServiceUser(configurationFile.Path, "LocalSystem"); + + Identities(new FileInfo(configurationFile.Path).GetAccessControl()).Should().BeEquivalentTo(RestrictedIdentities()); + } + + [Test] + public void WhenTheServiceUserCannotBeFoundThenThePermissionsAreLeftAlone() + { + using var configurationFile = new WindowsConfigurationFileBuilder().Build(); + var log = new InMemoryLog(); + + new WindowsConfigurationFilePermissions(log).RestrictToServiceUser(configurationFile.Path, @".\tentacle-no-such-user"); + + log.GetLog().Should().Contain("Unable to restrict"); + var security = new FileInfo(configurationFile.Path).GetAccessControl(); + security.AreAccessRulesProtected.Should().BeFalse(); + Identities(security).Should().Contain(AuthenticatedUsers.Value); + } + + static string[] RestrictedIdentities() + => new[] { LocalSystem.Value, Administrators.Value, WindowsIdentity.GetCurrent().User!.Value }.Distinct().ToArray(); + + static string[] Identities(FileSecurity security) + => security.GetAccessRules(true, true, typeof(SecurityIdentifier)) + .Cast() + .Select(r => r.IdentityReference.Value) + .Distinct() + .ToArray(); + + static FileSystemRights Rights(FileSecurity security, SecurityIdentifier identity) + => security.GetAccessRules(true, true, typeof(SecurityIdentifier)) + .Cast() + .Where(r => r.IdentityReference.Value == identity.Value) + .Aggregate((FileSystemRights)0, (rights, r) => rights | r.FileSystemRights); + + static string AccountName(SecurityIdentifier identity) + => identity.Translate(typeof(NTAccount)).Value; + } +} diff --git a/source/Octopus.Tentacle.Tests/Support/WindowsConfigurationFileBuilder.cs b/source/Octopus.Tentacle.Tests/Support/WindowsConfigurationFileBuilder.cs new file mode 100644 index 000000000..470cfdc2e --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Support/WindowsConfigurationFileBuilder.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.AccessControl; +using System.Security.Principal; +using Octopus.Tentacle.Util; +#if NET +using System.Runtime.Versioning; +#endif + +namespace Octopus.Tentacle.Tests.Support +{ + // Builds a Tentacle config in a folder that, like the default home C:\Octopus, lets every authenticated user modify + // the files in it. By default the config inherits the folder's permissions. +#if NET + [SupportedOSPlatform("windows")] +#endif + class WindowsConfigurationFileBuilder + { + public static readonly SecurityIdentifier AuthenticatedUsers = new(WellKnownSidType.AuthenticatedUserSid, null); + + bool inheritFolderPermissions = true; + readonly List grantedModify = new(); + + public WindowsConfigurationFileBuilder WithModifyGrantedTo(SecurityIdentifier identity) + { + grantedModify.Add(identity); + return this; + } + + // As if Tentacle or an administrator had already restricted it, keeping the folder's entries as its own. + public WindowsConfigurationFileBuilder NoLongerInheritingFolderPermissions() + { + inheritFolderPermissions = false; + return this; + } + + public TemporaryWindowsConfigurationFile Build() + { + var directory = new TemporaryDirectory(new OctopusPhysicalFileSystem(new InMemoryLog())); + var directoryInfo = new DirectoryInfo(directory.DirectoryPath); + var directorySecurity = directoryInfo.GetAccessControl(); + directorySecurity.AddAccessRule(new FileSystemAccessRule(AuthenticatedUsers, + FileSystemRights.Modify, + InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, + PropagationFlags.None, + AccessControlType.Allow)); + directoryInfo.SetAccessControl(directorySecurity); + + var configurationFile = new TemporaryWindowsConfigurationFile(directory, Path.Combine(directory.DirectoryPath, "Tentacle.config")); + File.WriteAllText(configurationFile.Path, ""); + var file = new FileInfo(configurationFile.Path); + var security = file.GetAccessControl(); + foreach (var identity in grantedModify) + { + security.AddAccessRule(new FileSystemAccessRule(identity, FileSystemRights.Modify, AccessControlType.Allow)); + } + + if (!inheritFolderPermissions) + { + security.SetAccessRuleProtection(isProtected: true, preserveInheritance: true); + } + + file.SetAccessControl(security); + return configurationFile; + } + } + + class TemporaryWindowsConfigurationFile : IDisposable + { + readonly TemporaryDirectory directory; + + public TemporaryWindowsConfigurationFile(TemporaryDirectory directory, string path) + { + this.directory = directory; + Path = path; + } + + public string Path { get; } + + public void Dispose() => directory.Dispose(); + } +} diff --git a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs index 4947e3c37..87e6f895d 100644 --- a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs +++ b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs @@ -34,6 +34,7 @@ public class RunAgentCommand : AbstractStandardCommand readonly IWindowsLocalAdminRightsChecker windowsLocalAdminRightsChecker; readonly AppVersion appVersion; readonly IEnumerable> backgroundTasks; + readonly IConfigurationFilePermissions configurationFilePermissions; int wait; bool halibutHasStarted; @@ -51,7 +52,8 @@ public RunAgentCommand( IWindowsLocalAdminRightsChecker windowsLocalAdminRightsChecker, AppVersion appVersion, ILogFileOnlyLogger logFileOnlyLogger, - IEnumerable> backgroundTasks) : base(selector, log, logFileOnlyLogger) + IEnumerable> backgroundTasks, + IConfigurationFilePermissions configurationFilePermissions) : base(selector, log, logFileOnlyLogger) { this.halibut = halibut; this.configuration = configuration; @@ -64,6 +66,7 @@ public RunAgentCommand( this.windowsLocalAdminRightsChecker = windowsLocalAdminRightsChecker; this.appVersion = appVersion; this.backgroundTasks = backgroundTasks; + this.configurationFilePermissions = configurationFilePermissions; Options.Add("wait=", "Delay (ms) before starting", arg => wait = int.Parse(arg)); Options.Add("console", "Don't attempt to run as a service, even if the user is non-interactive", v => @@ -125,7 +128,11 @@ protected override void Start() Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, proxyConfiguration.Value.CustomProxyPort.ToString()); LogWarningIfNotRunningAsAdministrator(); - ConfigurationFilePermissions.RestrictToOwner(selector.Current.ConfigurationPath, log); + var configurationPath = selector.Current.ConfigurationPath; + if (!string.IsNullOrWhiteSpace(configurationPath)) + { + configurationFilePermissions.RestrictToCurrentUser(configurationPath!); + } proxyInitializer.Value.InitializeProxy(); diff --git a/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs b/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs index b32d21c6e..9f36dd55f 100644 --- a/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs +++ b/source/Octopus.Tentacle/Configuration/ConfigurationModule.cs @@ -43,6 +43,8 @@ protected override void Load(ContainerBuilder builder) builder.RegisterType().As(); } + RegisterConfigurationFilePermissions(builder); + builder.RegisterType().As(); builder.RegisterType() @@ -106,6 +108,19 @@ protected override void Load(ContainerBuilder builder) RegisterWatchdog(builder); } + // Checks the OS with OperatingSystem, which the platform compatibility analyzer understands. + internal static void RegisterConfigurationFilePermissions(ContainerBuilder builder) + { +#if NET + if (!OperatingSystem.IsWindows()) + { + builder.RegisterType().As(); + return; + } +#endif + builder.RegisterType().As(); + } + void RegisterWatchdog(ContainerBuilder builder) { if (PlatformDetection.IsRunningOnWindows) @@ -140,6 +155,7 @@ protected override void Load(ContainerBuilder builder) builder.RegisterType() .As(); builder.RegisterType().As(); + ConfigurationModule.RegisterConfigurationFilePermissions(builder); builder.RegisterType() .As(); diff --git a/source/Octopus.Tentacle/Configuration/IConfigurationFilePermissions.cs b/source/Octopus.Tentacle/Configuration/IConfigurationFilePermissions.cs new file mode 100644 index 000000000..3b1da8982 --- /dev/null +++ b/source/Octopus.Tentacle/Configuration/IConfigurationFilePermissions.cs @@ -0,0 +1,11 @@ +using System; + +namespace Octopus.Tentacle.Configuration +{ + public interface IConfigurationFilePermissions + { + void CreateRestrictedToCurrentUser(string configurationPath, string contents); + void RestrictToCurrentUser(string configurationPath); + void RestrictToServiceUser(string configurationPath, string userName); + } +} diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs index 16b8a5026..3b6d00948 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs @@ -14,6 +14,7 @@ class ApplicationInstanceManager : IApplicationInstanceManager readonly Lazy homeConfiguration; readonly ApplicationName applicationName; readonly StartUpInstanceRequest startUpInstanceRequest; + readonly IConfigurationFilePermissions configurationFilePermissions; public ApplicationInstanceManager( ApplicationName applicationName, @@ -21,7 +22,8 @@ public ApplicationInstanceManager( IOctopusFileSystem fileSystem, ISystemLog log, IApplicationInstanceStore instanceStore, - Lazy homeConfiguration) + Lazy homeConfiguration, + IConfigurationFilePermissions configurationFilePermissions) { this.applicationName = applicationName; this.startUpInstanceRequest = startUpInstanceRequest; @@ -29,6 +31,7 @@ public ApplicationInstanceManager( this.log = log; this.instanceStore = instanceStore; this.homeConfiguration = homeConfiguration; + this.configurationFilePermissions = configurationFilePermissions; } public void CreateDefaultInstance(string configurationFile, string? homeDirectory = null) @@ -76,7 +79,7 @@ void EnsureConfigurationFileExists(string configurationFile, string homeDirector if (!fileSystem.FileExists(configurationFile)) { log.Info("Creating empty configuration file: " + configurationFile); - ConfigurationFilePermissions.CreateEmpty(fileSystem, configurationFile, @""); + configurationFilePermissions.CreateRestrictedToCurrentUser(configurationFile, @""); } else { diff --git a/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs b/source/Octopus.Tentacle/Configuration/LinuxConfigurationFilePermissions.cs similarity index 70% rename from source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs rename to source/Octopus.Tentacle/Configuration/LinuxConfigurationFilePermissions.cs index 1db32e708..77f1efd60 100644 --- a/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs +++ b/source/Octopus.Tentacle/Configuration/LinuxConfigurationFilePermissions.cs @@ -1,47 +1,45 @@ -using System; -using System.IO; -using Octopus.Tentacle.Core.Diagnostics; -using Octopus.Tentacle.Util; #if NET +using System; using System.Diagnostics; +using System.IO; using System.Runtime.InteropServices; using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; -#endif +using Octopus.Tentacle.Core.Diagnostics; 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 + // Only the file's owner may read it, so the service user must own it. + [UnsupportedOSPlatform("windows")] + class LinuxConfigurationFilePermissions : IConfigurationFilePermissions { -#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) + readonly ISystemLog log; + + public LinuxConfigurationFilePermissions(ISystemLog log) { -#if NET - if (!OperatingSystem.IsWindows()) + this.log = log; + } + + public void CreateRestrictedToCurrentUser(string configurationPath, string contents) + { + // The mode is applied as the file is created, so it is never readable by other users. + using var stream = new FileStream(configurationPath, new FileStreamOptions { - 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); + Mode = FileMode.CreateNew, + Access = FileAccess.Write, + UnixCreateMode = OwnerOnly + }); + using var writer = new StreamWriter(stream); + writer.Write(contents); } - public static void RestrictToOwner(string? configurationPath, ISystemLog log) + // The agent runs as the service user, which owns the file. + public void RestrictToCurrentUser(string configurationPath) { -#if NET - if (OperatingSystem.IsWindows() || string.IsNullOrWhiteSpace(configurationPath) || !File.Exists(configurationPath)) + if (!File.Exists(configurationPath)) { return; } @@ -59,16 +57,11 @@ public static void RestrictToOwner(string? configurationPath, ISystemLog log) { 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) + public void RestrictToServiceUser(string configurationPath, string userName) { -#if NET - if (OperatingSystem.IsWindows() - || string.IsNullOrWhiteSpace(configurationPath) - || string.IsNullOrWhiteSpace(userName) - || userName == "root") + if (userName == "root") { return; } @@ -78,11 +71,8 @@ public static void RestrictToServiceUser(string? configurationPath, string? user { 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 @@ -135,6 +125,6 @@ public static void RestrictToServiceUser(string? configurationPath, string? user [DllImport("libc", SetLastError = true)] static extern int fchown(SafeFileHandle fd, uint owner, uint group); -#endif } } +#endif diff --git a/source/Octopus.Tentacle/Configuration/WindowsConfigurationFilePermissions.cs b/source/Octopus.Tentacle/Configuration/WindowsConfigurationFilePermissions.cs new file mode 100644 index 000000000..a8e26b026 --- /dev/null +++ b/source/Octopus.Tentacle/Configuration/WindowsConfigurationFilePermissions.cs @@ -0,0 +1,129 @@ +using System; +using System.IO; +using System.Security.AccessControl; +using System.Security.Principal; +using Octopus.Tentacle.Core.Diagnostics; +#if NET +using System.Runtime.Versioning; +#endif + +namespace Octopus.Tentacle.Configuration +{ + // A new file inherits its folder's ACL. Under the default home, C:\Octopus, that comes from C:\, which lets every + // authenticated user modify the file. The config's protected settings are encrypted with DPAPI's LocalMachine scope, + // so anyone who can read the file can decrypt them. Only SYSTEM, Administrators and the account Tentacle runs as + // should be able to access it. +#if NET + [SupportedOSPlatform("windows")] +#endif + class WindowsConfigurationFilePermissions : IConfigurationFilePermissions + { + static readonly SecurityIdentifier LocalSystem = new(WellKnownSidType.LocalSystemSid, null); + static readonly SecurityIdentifier Administrators = new(WellKnownSidType.BuiltinAdministratorsSid, null); + + readonly ISystemLog log; + + public WindowsConfigurationFilePermissions(ISystemLog log) + { + this.log = log; + } + + public void CreateRestrictedToCurrentUser(string configurationPath, string contents) + { + var security = new FileSecurity(); + Restrict(security); + + // The ACL is applied as the file is created, so it never has the folder's ACL. +#if NET + using var stream = new FileInfo(configurationPath).Create(FileMode.CreateNew, FileSystemRights.Write, FileShare.None, 4096, FileOptions.None, security); +#else + using var stream = new FileStream(configurationPath, FileMode.CreateNew, FileSystemRights.Write, FileShare.None, 4096, FileOptions.None, security); +#endif + using var writer = new StreamWriter(stream); + writer.Write(contents); + } + + // The agent runs as the service account, so granting the current user access keeps the service account's + // access. Entries set on the file itself, such as the service account granted access by `service --install`, + // are kept too. An ACL that no longer inherits from its folder has already been restricted, by Tentacle or by + // an administrator, so it is left alone. + public void RestrictToCurrentUser(string configurationPath) + { + if (!File.Exists(configurationPath)) + { + return; + } + + try + { + var file = new FileInfo(configurationPath); + var security = file.GetAccessControl(); + if (security.AreAccessRulesProtected) + { + return; + } + + Restrict(security); + file.SetAccessControl(security); + log.Info($"Restricted `{configurationPath}` to SYSTEM, Administrators and {WindowsIdentity.GetCurrent().Name}"); + } + catch (Exception ex) when (ex is UnauthorizedAccessException or IOException or PrivilegeNotHeldException) + { + log.Warn($"Unable to restrict `{configurationPath}`, so other users may be able to read it: {ex.Message}. Run `service --reconfigure --username ` as an administrator to restrict it."); + } + } + + public void RestrictToServiceUser(string configurationPath, string userName) + { + try + { + var serviceAccount = ResolveAccount(userName); + var file = new FileInfo(configurationPath); + var security = file.GetAccessControl(); + Restrict(security); + if (serviceAccount != LocalSystem) + { + security.AddAccessRule(new FileSystemAccessRule(serviceAccount, FileSystemRights.Modify, AccessControlType.Allow)); + } + + file.SetAccessControl(security); + log.Info($"Restricted `{configurationPath}` to SYSTEM, Administrators, {WindowsIdentity.GetCurrent().Name} and `{userName}`"); + } + catch (Exception ex) + { + log.Warn($"Unable to restrict `{configurationPath}` to `{userName}`: {ex.Message.TrimEnd('.')}. Only SYSTEM, Administrators and the service account should be able to read and write the configuration file, so check its permissions."); + } + } + + // Stops inheriting from the folder, which drops entries such as Authenticated Users, and keeps any entries set on + // the file itself, such as a service account granted access by an earlier install. + static void Restrict(FileSecurity security) + { + security.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + security.AddAccessRule(new FileSystemAccessRule(LocalSystem, FileSystemRights.FullControl, AccessControlType.Allow)); + security.AddAccessRule(new FileSystemAccessRule(Administrators, FileSystemRights.FullControl, AccessControlType.Allow)); + + var currentUser = WindowsIdentity.GetCurrent().User; + if (currentUser != null) + { + security.AddAccessRule(new FileSystemAccessRule(currentUser, FileSystemRights.FullControl, AccessControlType.Allow)); + } + } + + static SecurityIdentifier ResolveAccount(string userName) + { + // sc.exe accepts these, NTAccount doesn't. + if (string.Equals(userName, "LocalSystem", StringComparison.OrdinalIgnoreCase)) + { + return LocalSystem; + } + + if (userName.StartsWith(@".\", StringComparison.Ordinal)) + { + userName = Environment.MachineName + userName.Substring(1); + } + + return (SecurityIdentifier)new NTAccount(userName).Translate(typeof(SecurityIdentifier)); + } + } +} diff --git a/source/Octopus.Tentacle/Startup/ServiceCommand.cs b/source/Octopus.Tentacle/Startup/ServiceCommand.cs index 44d5033fa..2ee89e673 100644 --- a/source/Octopus.Tentacle/Startup/ServiceCommand.cs +++ b/source/Octopus.Tentacle/Startup/ServiceCommand.cs @@ -17,6 +17,7 @@ public class ServiceCommand : AbstractCommand readonly IApplicationInstanceSelector instanceSelector; readonly ServiceConfigurationState serviceConfigurationState; readonly IServiceConfigurator serviceConfigurator; + readonly IConfigurationFilePermissions configurationFilePermissions; private readonly ISystemLog log; readonly string ServicePasswordEnvVar = "OCTOPUS_SERVICE_PASSWORD"; readonly string ServiceUsernameEnvVar = "OCTOPUS_SERVICE_USERNAME"; @@ -30,7 +31,8 @@ public ServiceCommand(ApplicationName applicationName, Assembly assemblyContainingService, IServiceConfigurator serviceConfigurator, ISystemLog log, - ILogFileOnlyLogger logFileOnlyLogger) + ILogFileOnlyLogger logFileOnlyLogger, + IConfigurationFilePermissions configurationFilePermissions) : base(logFileOnlyLogger) { this.applicationName = applicationName; @@ -39,6 +41,7 @@ public ServiceCommand(ApplicationName applicationName, this.serviceDescription = serviceDescription; this.assemblyContainingService = assemblyContainingService; this.serviceConfigurator = serviceConfigurator; + this.configurationFilePermissions = configurationFilePermissions; this.log = log; serviceConfigurationState = new ServiceConfigurationState @@ -100,6 +103,19 @@ protected override void Start() { var currentName = instanceSelector.Current.InstanceName; var thisServiceName = ServiceName.GetWindowsServiceName(applicationName, currentName); + + // Before configuring the service, which may also start it, so the service user can already read the config. + // Without a user name the service keeps its current account, which may rely on the inherited + // permissions, so the file is left alone. + var configurationPath = instanceSelector.Current.ConfigurationPath; + var userName = serviceConfigurationState.Username; + if ((serviceConfigurationState.Install || serviceConfigurationState.Reconfigure) + && !string.IsNullOrWhiteSpace(configurationPath) + && !string.IsNullOrWhiteSpace(userName)) + { + configurationFilePermissions.RestrictToServiceUser(configurationPath!, userName!); + } + if (currentName == null) { if (serviceConfigurationState.Install || serviceConfigurationState.Reconfigure) @@ -120,11 +136,6 @@ protected override void Start() serviceDescription, serviceConfigurationState); } - - if (serviceConfigurationState.Install || serviceConfigurationState.Reconfigure) - { - ConfigurationFilePermissions.RestrictToServiceUser(instanceSelector.Current.ConfigurationPath, serviceConfigurationState.Username, log); - } } } }