diff --git a/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsFixture.cs b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsFixture.cs new file mode 100644 index 000000000..131e18043 --- /dev/null +++ b/source/Octopus.Tentacle.Tests.Integration/Configuration/ConfigurationFilePermissionsFixture.cs @@ -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 diff --git a/source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsFixture.cs new file mode 100644 index 000000000..42ffaf598 --- /dev/null +++ b/source/Octopus.Tentacle.Tests/Configuration/ConfigurationFilePermissionsFixture.cs @@ -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, ""); + + 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 diff --git a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs index 0ca205b43..4947e3c37 100644 --- a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs +++ b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs @@ -125,6 +125,7 @@ protected override void Start() Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, proxyConfiguration.Value.CustomProxyPort.ToString()); LogWarningIfNotRunningAsAdministrator(); + ConfigurationFilePermissions.RestrictToOwner(selector.Current.ConfigurationPath, log); proxyInitializer.Value.InitializeProxy(); diff --git a/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs b/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs new file mode 100644 index 000000000..1db32e708 --- /dev/null +++ b/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs @@ -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 + } +} diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs index fb777649f..16b8a5026 100644 --- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs +++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceManager.cs @@ -76,7 +76,7 @@ void EnsureConfigurationFileExists(string configurationFile, string homeDirector if (!fileSystem.FileExists(configurationFile)) { log.Info("Creating empty configuration file: " + configurationFile); - fileSystem.OverwriteFile(configurationFile, @""); + ConfigurationFilePermissions.CreateEmpty(fileSystem, configurationFile, @""); } else { diff --git a/source/Octopus.Tentacle/Startup/ServiceCommand.cs b/source/Octopus.Tentacle/Startup/ServiceCommand.cs index b2535f3df..44d5033fa 100644 --- a/source/Octopus.Tentacle/Startup/ServiceCommand.cs +++ b/source/Octopus.Tentacle/Startup/ServiceCommand.cs @@ -120,6 +120,11 @@ protected override void Start() serviceDescription, serviceConfigurationState); } + + if (serviceConfigurationState.Install || serviceConfigurationState.Reconfigure) + { + ConfigurationFilePermissions.RestrictToServiceUser(instanceSelector.Current.ConfigurationPath, serviceConfigurationState.Username, log); + } } } }