├── Images └── ExampleDecrypt.gif ├── src ├── QnapBackupDecryptor.Core.Tests │ ├── TestFiles │ │ ├── plaintext.txt │ │ ├── encrypted.jpg │ │ └── encrypted.txt │ ├── FileHelpersTests.cs │ ├── QnapBackupDecryptor.Core.Tests.csproj │ ├── FileJobExtensionsTests.cs │ ├── DecryptorTests.cs │ ├── DecryptorServiceTests.cs │ ├── QnapTests.cs │ ├── JobMakerTests.cs │ └── OpenSslTests.cs ├── QnapBackupDecryptor.Core │ ├── Models │ │ ├── DeleteResult.cs │ │ ├── DecryptResult.cs │ │ ├── DecryptJob.cs │ │ └── Result.cs │ ├── QnapEncryptionCheckResult.cs │ ├── FileJobExtensions.cs │ ├── FileInfoExtensions.cs │ ├── QnapBackupDecryptor.Core.csproj │ ├── FileService.cs │ ├── FileHelpers.cs │ ├── DecryptorService.cs │ ├── Qnap.cs │ ├── JobMaker.cs │ └── OpenSsl.cs ├── nuget.config ├── QnapBackupDecryptor.Console │ ├── QnapBackupDecryptor.Console.csproj │ ├── Prompts.cs │ ├── Options.cs │ ├── Program.cs │ └── Output.cs └── QnapBackupDecryptor.sln ├── .github ├── dependabot.yml ├── workflows │ ├── CIBuildTest-Win.yml │ ├── CIBuildTest-Linux.yml │ └── ReleaseAll.yml └── copilot-instructions.md ├── .gitattributes ├── README.md ├── .gitignore └── LICENSE /Images/ExampleDecrypt.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mark-s/QnapBackupDecryptor/HEAD/Images/ExampleDecrypt.gif -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core.Tests/TestFiles/plaintext.txt: -------------------------------------------------------------------------------- 1 | line1: this is a plaintext file 2 | line2: End! 3 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "nuget" 4 | directory: "/src" 5 | schedule: 6 | interval: "daily" 7 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core.Tests/TestFiles/encrypted.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mark-s/QnapBackupDecryptor/HEAD/src/QnapBackupDecryptor.Core.Tests/TestFiles/encrypted.jpg -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core.Tests/TestFiles/encrypted.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mark-s/QnapBackupDecryptor/HEAD/src/QnapBackupDecryptor.Core.Tests/TestFiles/encrypted.txt -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/Models/DeleteResult.cs: -------------------------------------------------------------------------------- 1 | namespace QnapBackupDecryptor.Core.Models; 2 | 3 | public sealed record DeleteResult(FileSystemInfo FileToDelete, bool DeletedOk, string ErrorMessage); -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/Models/DecryptResult.cs: -------------------------------------------------------------------------------- 1 | namespace QnapBackupDecryptor.Core.Models; 2 | 3 | public sealed record DecryptResult(FileSystemInfo Source, FileSystemInfo Dest, bool DecryptedOk, string ErrorMessage); -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/QnapEncryptionCheckResult.cs: -------------------------------------------------------------------------------- 1 | namespace QnapBackupDecryptor.Core; 2 | 3 | public readonly record struct QnapEncryptionCheckResult(bool IsQnapEncrypted, int EncryptionVersion, bool Compressable); -------------------------------------------------------------------------------- /src/nuget.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/FileJobExtensions.cs: -------------------------------------------------------------------------------- 1 | using QnapBackupDecryptor.Core.Models; 2 | 3 | namespace QnapBackupDecryptor.Core; 4 | 5 | internal static class FileJobExtensions 6 | { 7 | internal static IReadOnlyList ToJobs(this DecryptJob job) 8 | => [job]; 9 | } -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/FileInfoExtensions.cs: -------------------------------------------------------------------------------- 1 | namespace QnapBackupDecryptor.Core; 2 | 3 | internal static class FileInfoExtensions 4 | { 5 | internal static bool TryDelete(this FileInfo fileInfo) 6 | { 7 | try 8 | { 9 | fileInfo.Refresh(); 10 | if (fileInfo.Exists) 11 | fileInfo.Delete(); 12 | 13 | return true; 14 | } 15 | catch 16 | { 17 | return false; 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/QnapBackupDecryptor.Core.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | true 8 | true 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/FileService.cs: -------------------------------------------------------------------------------- 1 | using QnapBackupDecryptor.Core.Models; 2 | 3 | namespace QnapBackupDecryptor.Core; 4 | 5 | public static class FileService 6 | { 7 | public static DeleteResult TryDelete(FileSystemInfo toDelete) 8 | { 9 | try 10 | { 11 | toDelete.Delete(); 12 | return new DeleteResult(toDelete, true, string.Empty); 13 | } 14 | catch (Exception ex) 15 | { 16 | return new DeleteResult(toDelete, false, ex.Message); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/FileHelpers.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.InteropServices; 2 | 3 | namespace QnapBackupDecryptor.Core; 4 | 5 | internal static class FileHelpers 6 | { 7 | internal static void HideFile(FileSystemInfo file) 8 | { 9 | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) 10 | file.Attributes |= FileAttributes.Hidden; 11 | } 12 | 13 | internal static void ShowFile(FileSystemInfo file) 14 | { 15 | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) 16 | file.Attributes -= FileAttributes.Hidden; 17 | } 18 | } -------------------------------------------------------------------------------- /.github/workflows/CIBuildTest-Win.yml: -------------------------------------------------------------------------------- 1 | name: BuildAndTest-Windows 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | 9 | jobs: 10 | BuildAndTest: 11 | runs-on: windows-latest 12 | env: 13 | DOTNET_NOLOGO: true 14 | 15 | steps: 16 | - name: Checkout 17 | uses: actions/checkout@v4 18 | with: 19 | fetch-depth: 0 20 | 21 | # Install the .NET Core workload 22 | - name: Install .NET Core 23 | uses: actions/setup-dotnet@v4 24 | with: 25 | dotnet-version: 8.0.x 26 | 27 | - name: Build 28 | working-directory: src 29 | run: dotnet build 30 | 31 | - name: Execute unit tests 32 | working-directory: src 33 | run: dotnet test -------------------------------------------------------------------------------- /.github/workflows/CIBuildTest-Linux.yml: -------------------------------------------------------------------------------- 1 | name: BuildAndTest-Linux 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | 9 | jobs: 10 | BuildAndTest: 11 | runs-on: ubuntu-latest 12 | env: 13 | DOTNET_NOLOGO: true 14 | 15 | steps: 16 | - name: Checkout 17 | uses: actions/checkout@v4 18 | with: 19 | fetch-depth: 0 20 | 21 | # Install the .NET Core workload 22 | - name: Install .NET Core 23 | uses: actions/setup-dotnet@v4 24 | with: 25 | dotnet-version: 8.0.x 26 | 27 | - name: Build 28 | working-directory: src 29 | run: dotnet build 30 | 31 | - name: Execute unit tests 32 | working-directory: src 33 | run: dotnet test 34 | -------------------------------------------------------------------------------- /.github/copilot-instructions.md: -------------------------------------------------------------------------------- 1 | Write tests using NUnit, FakeItEasy and Shouldly. 2 | Unit tests should follow the Arrange-Act-Assert pattern and use descriptive names to indicate what's being tested. 3 | Tests should be placed in a separate test project and should not be included in the main project. 4 | The test methods should be placed in a separate test class and should not be included in the main class. 5 | The test project should reference the main project and include the necessary NuGet packages for NUnit, FakeItEasy, and Shouldly. 6 | The test project should be named according to the convention of .Tests. 7 | The test class should be named according to the convention of Tests. 8 | The test methods should be named according to the convention of __. 9 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/DecryptorService.cs: -------------------------------------------------------------------------------- 1 | using QnapBackupDecryptor.Core.Models; 2 | 3 | namespace QnapBackupDecryptor.Core; 4 | 5 | public static class DecryptorService 6 | { 7 | public static DecryptResult TryDecrypt(byte[] password, DecryptJob job) 8 | { 9 | if (job.IsValid == false) 10 | return new DecryptResult(job.EncryptedFile, job.OutputFile, job.IsValid, job.ErrorMessage); 11 | 12 | var decryptionResult = OpenSsl.Decrypt( 13 | encryptedFile: new FileInfo(job.EncryptedFile.FullName), 14 | password: password, 15 | outputFile: new FileInfo(job.OutputFile.FullName)); 16 | 17 | return new DecryptResult(job.EncryptedFile, job.OutputFile, decryptionResult.IsSuccess, decryptionResult.ErrorMessage); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/Models/DecryptJob.cs: -------------------------------------------------------------------------------- 1 | namespace QnapBackupDecryptor.Core.Models; 2 | 3 | public sealed class DecryptJob 4 | { 5 | public FileSystemInfo EncryptedFile { get; } 6 | public FileSystemInfo OutputFile { get; } 7 | public bool IsValid { get; } 8 | public string ErrorMessage { get; } 9 | 10 | private DecryptJob(FileSystemInfo encryptedFile, FileSystemInfo outputFile, bool isValid, string errorMessage) 11 | { 12 | EncryptedFile = encryptedFile; 13 | OutputFile = outputFile; 14 | IsValid = isValid; 15 | ErrorMessage = errorMessage; 16 | } 17 | 18 | internal static DecryptJob Invalid(FileSystemInfo encryptedFile, FileSystemInfo outputFile, string errorMessage) 19 | => new(encryptedFile, outputFile, false, errorMessage); 20 | 21 | internal static DecryptJob Valid(FileSystemInfo encryptedFile, FileSystemInfo outputFile) 22 | => new(encryptedFile, outputFile, true, string.Empty); 23 | 24 | }; -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Console/QnapBackupDecryptor.Console.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | true 9 | true 10 | 11 | 12 | 13 | 1701;1702;CA1859 14 | 15 | 16 | 17 | 1701;1702;CA1859 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core.Tests/FileHelpersTests.cs: -------------------------------------------------------------------------------- 1 | namespace QnapBackupDecryptor.Core.Tests; 2 | 3 | [TestFixture] 4 | public class FileHelpersTests 5 | { 6 | [Test] 7 | public void IsOpenSslEncrypted_OpenSslFile_Binary_True() 8 | { 9 | // Arrange 10 | var oseFile = new FileInfo(Path.Combine("TestFiles", "encrypted.jpg")); 11 | 12 | // Act 13 | var result = OpenSsl.IsOpenSslEncrypted(oseFile); 14 | 15 | // Assert 16 | result.Data.ShouldBeTrue(); 17 | } 18 | 19 | [Test] 20 | public void IsOpenSslEncrypted_OpenSslFile_Text_True() 21 | { 22 | // Arrange 23 | var oseFile = new FileInfo(Path.Combine("TestFiles", "encrypted.txt")); 24 | 25 | // Act 26 | var result = OpenSsl.IsOpenSslEncrypted(oseFile); 27 | 28 | // Assert 29 | result.Data.ShouldBeTrue(); 30 | } 31 | 32 | [Test] 33 | public void IsOpenSslEncrypted_NotOpenSslFile_False() 34 | { 35 | // Arrange 36 | var oseFile = new FileInfo(Path.Combine("TestFiles", "plaintext.txt")); 37 | 38 | // Act 39 | var result = OpenSsl.IsOpenSslEncrypted(oseFile); 40 | 41 | // Assert 42 | result.Data.ShouldBeFalse(); 43 | } 44 | } -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/Models/Result.cs: -------------------------------------------------------------------------------- 1 | namespace QnapBackupDecryptor.Core.Models; 2 | 3 | public sealed class Result 4 | { 5 | public Exception? Exception { get; } 6 | public bool IsSuccess { get; } 7 | public bool IsError => !IsSuccess; 8 | public string ErrorMessage { get; } 9 | public string SuccessMessage { get; } 10 | 11 | public T Data { get; } 12 | 13 | private Result(bool isSuccess, string errorMessage, T data, string successMessage, Exception? exception) 14 | { 15 | IsSuccess = isSuccess; 16 | ErrorMessage = errorMessage; 17 | Data = data; 18 | SuccessMessage = successMessage; 19 | Exception = exception; 20 | } 21 | 22 | public static Result OkResult(T data, string message) 23 | => new(true, string.Empty, data, message, null); 24 | 25 | public static Result OkResult(T data) 26 | => new(true, string.Empty, data, string.Empty, null); 27 | 28 | public static Result ErrorResult(string errorMessage, T data) 29 | => new(false, errorMessage, data, string.Empty, null); 30 | 31 | public static Result ErrorResult(string errorMessage, T data, TE exception) where TE : Exception 32 | => new(false, errorMessage, data, string.Empty, exception); 33 | 34 | public static implicit operator T(Result a) 35 | => a.Data; 36 | } -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core.Tests/QnapBackupDecryptor.Core.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | false 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | PreserveNewest 20 | 21 | 22 | PreserveNewest 23 | 24 | 25 | PreserveNewest 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core.Tests/FileJobExtensionsTests.cs: -------------------------------------------------------------------------------- 1 | namespace QnapBackupDecryptor.Core.Tests; 2 | 3 | using QnapBackupDecryptor.Core.Models; 4 | 5 | [TestFixture] 6 | public class FileJobExtensionsTests 7 | { 8 | [Test] 9 | public void ToJobs_ValidDecryptJob_ReturnsSingleElementList() 10 | { 11 | // Arrange 12 | var encryptedFile = new FileInfo(Path.Combine("TestFiles", "encrypted.txt")); 13 | var outputFile = new FileInfo(Path.Combine("TestFiles", "output.txt")); 14 | var job = DecryptJob.Valid(encryptedFile, outputFile); 15 | 16 | // Act 17 | var result = job.ToJobs(); 18 | 19 | // Assert 20 | result.Count.ShouldBe(1); 21 | result[0].ShouldBeSameAs(job); 22 | } 23 | 24 | [Test] 25 | public void ToJobs_InvalidDecryptJob_ReturnsSingleElementList() 26 | { 27 | // Arrange 28 | var encryptedFile = new FileInfo(Path.Combine("TestFiles", "encrypted.txt")); 29 | var outputFile = new FileInfo(Path.Combine("TestFiles", "output.txt")); 30 | var errorMessage = "Test error message"; 31 | var job = DecryptJob.Invalid(encryptedFile, outputFile, errorMessage); 32 | 33 | // Act 34 | var result = job.ToJobs(); 35 | 36 | // Assert 37 | result.Count.ShouldBe(1); 38 | result[0].ShouldBeSameAs(job); 39 | result[0].IsValid.ShouldBeFalse(); 40 | result[0].ErrorMessage.ShouldBe(errorMessage); 41 | } 42 | 43 | [Test] 44 | public void ToJobs_PreservesOriginalJobProperties() 45 | { 46 | // Arrange 47 | var encryptedFile = new FileInfo(Path.Combine("TestFiles", "encrypted.txt")); 48 | var outputFile = new FileInfo(Path.Combine("TestFiles", "output.txt")); 49 | var job = DecryptJob.Valid(encryptedFile, outputFile); 50 | 51 | // Act 52 | var result = job.ToJobs(); 53 | 54 | // Assert 55 | result[0].EncryptedFile.ShouldBe(encryptedFile); 56 | result[0].OutputFile.ShouldBe(outputFile); 57 | result[0].IsValid.ShouldBeTrue(); 58 | result[0].ErrorMessage.ShouldBe(string.Empty); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.31005.135 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QnapBackupDecryptor.Console", "QnapBackupDecryptor.Console\QnapBackupDecryptor.Console.csproj", "{5F2A6DEE-4B0A-42A2-9583-5C5BFC40A704}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QnapBackupDecryptor.Core", "QnapBackupDecryptor.Core\QnapBackupDecryptor.Core.csproj", "{95F53606-3B59-45CA-AA6A-D72BBA134149}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "QnapBackupDecryptor.Core.Tests", "QnapBackupDecryptor.Core.Tests\QnapBackupDecryptor.Core.Tests.csproj", "{E8CBC8A0-1B18-4430-B313-68CAC469514F}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {5F2A6DEE-4B0A-42A2-9583-5C5BFC40A704}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {5F2A6DEE-4B0A-42A2-9583-5C5BFC40A704}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {5F2A6DEE-4B0A-42A2-9583-5C5BFC40A704}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {5F2A6DEE-4B0A-42A2-9583-5C5BFC40A704}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {95F53606-3B59-45CA-AA6A-D72BBA134149}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {95F53606-3B59-45CA-AA6A-D72BBA134149}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {95F53606-3B59-45CA-AA6A-D72BBA134149}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {95F53606-3B59-45CA-AA6A-D72BBA134149}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {E8CBC8A0-1B18-4430-B313-68CAC469514F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {E8CBC8A0-1B18-4430-B313-68CAC469514F}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {E8CBC8A0-1B18-4430-B313-68CAC469514F}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {E8CBC8A0-1B18-4430-B313-68CAC469514F}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {7D068B49-E8DC-4B97-9361-081F7AF0C85F} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Console/Prompts.cs: -------------------------------------------------------------------------------- 1 | using Spectre.Console; 2 | using System.Text; 3 | 4 | namespace QnapBackupDecryptor.Console; 5 | 6 | internal static class Prompts 7 | { 8 | private const string YES = "y"; 9 | private const string NO = "n"; 10 | private const string INVALID_OPTION_ENTERED = "[yellow]That's not a valid option[/]"; 11 | 12 | public static byte[] GetPassword() 13 | { 14 | var password = AnsiConsole.Prompt( 15 | new TextPrompt("[bold]>> Enter password[/]") 16 | .PromptStyle("yellow") 17 | .Secret()); 18 | 19 | return Encoding.UTF8.GetBytes(password); 20 | } 21 | 22 | public static bool EnsureDeleteWanted(Options options) 23 | { 24 | if (options.Silent) 25 | return true; 26 | 27 | if (options.RemoveEncrypted == false) 28 | return true; 29 | 30 | var response = AnsiConsole.Prompt( 31 | new TextPrompt("[bold]>> Are you sure you want to delete the encrypted files?[/]") 32 | .WithYesNoOptions(defaultOption: NO)); 33 | 34 | return response.IsYes(); 35 | } 36 | 37 | public static bool EnsureInPlaceWanted(Options options) 38 | { 39 | if (options.Silent) 40 | return true; 41 | 42 | if (options.InPlace == false) 43 | return true; 44 | 45 | var initialResponse = AnsiConsole.Prompt( 46 | new TextPrompt("[bold]>> Are you sure you want to decrypt the files in-place? If a decrypt produces a bad file - you will lose that file![/]") 47 | .WithYesNoOptions(defaultOption: NO)); 48 | 49 | var areYouSureResponse = AnsiConsole.Prompt( 50 | new TextPrompt("[bold]>> Are you really sure? Do you have a backup in case anything goes wrong?[/]") 51 | .WithYesNoOptions(defaultOption: NO)); 52 | 53 | return initialResponse.IsYes() && areYouSureResponse.IsYes(); 54 | } 55 | 56 | private static TextPrompt WithYesNoOptions(this TextPrompt prompt, string defaultOption) 57 | => prompt.InvalidChoiceMessage(INVALID_OPTION_ENTERED) 58 | .DefaultValue(defaultOption) 59 | .AddChoice(YES) 60 | .AddChoice(NO); 61 | 62 | private static bool IsYes(this string? value) 63 | => value?.Equals(YES, StringComparison.OrdinalIgnoreCase) ?? false; 64 | 65 | } -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core.Tests/DecryptorTests.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | namespace QnapBackupDecryptor.Core.Tests; 4 | 5 | [TestFixture] 6 | public class DecryptorTests 7 | { 8 | private const string VALID_TEST_PASSWORD = "wisLUBIMyBNcnvo3eDMS"; 9 | 10 | [Test] 11 | public void OpenSSLDecrypt_ValidPassword_OkResult() 12 | { 13 | // Arrange 14 | var encryptedFile = new FileInfo(Path.Combine("TestFiles", "encrypted.txt")); 15 | var outputFile = new FileInfo("decrypted.txt"); 16 | 17 | // Act 18 | var passwordBytes = Encoding.UTF8.GetBytes(VALID_TEST_PASSWORD); 19 | var sslDecrypt = OpenSsl.Decrypt(encryptedFile, passwordBytes, outputFile); 20 | 21 | // Assert 22 | sslDecrypt.IsSuccess.ShouldBeTrue(); 23 | } 24 | 25 | [Test] 26 | public void OpenSSLDecrypt_Text_ValidPassword_SuccessResult() 27 | { 28 | // Arrange 29 | var encryptedFile = new FileInfo(Path.Combine("TestFiles", "encrypted.txt")); 30 | var outputFile = new FileInfo("decrypted.txt"); 31 | 32 | // Act 33 | var passwordBytes = Encoding.UTF8.GetBytes(VALID_TEST_PASSWORD); 34 | var sslDecrypt = OpenSsl.Decrypt(encryptedFile, passwordBytes, outputFile); 35 | 36 | // Assert 37 | var decryptedText = File.ReadAllLines(sslDecrypt.Data.FullName); 38 | decryptedText.Length.ShouldBe(2); 39 | decryptedText[0].ShouldStartWith("line1: this is a plaintext file"); 40 | decryptedText[1].ShouldStartWith("line2: End!"); 41 | } 42 | 43 | [Test] 44 | public void OpenSSLDecrypt_Text_ValidPassword_ErrorResult() 45 | { 46 | // Arrange 47 | var encryptedFile = new FileInfo(Path.Combine("TestFiles", "encrypted.txt")); 48 | var outputFile = new FileInfo("decrypted.txt"); 49 | 50 | // Act 51 | var passwordBytes = "Invalid password!"u8.ToArray(); 52 | var decryptResult = OpenSsl.Decrypt(encryptedFile, passwordBytes, outputFile); 53 | 54 | // Assert 55 | decryptResult.IsError.ShouldBeTrue(); 56 | } 57 | 58 | [Test] 59 | public void OpenSSLDecrypt_Binary_InvalidPassword_ErrorResult() 60 | { 61 | // Arrange 62 | var encryptedFile = new FileInfo(Path.Combine("TestFiles", "encrypted.jpg")); 63 | var decryptedFile = new FileInfo(Path.Combine("TestFiles", "decrypted.jpg")); 64 | 65 | // Act 66 | var passwordBytes = "Invalid password!"u8.ToArray(); 67 | var decryptionResult = OpenSsl.Decrypt(encryptedFile, passwordBytes, decryptedFile); 68 | 69 | // Assert 70 | decryptionResult.IsError.ShouldBeTrue(); 71 | } 72 | 73 | } -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core.Tests/DecryptorServiceTests.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | using QnapBackupDecryptor.Core.Models; 3 | 4 | namespace QnapBackupDecryptor.Core.Tests; 5 | 6 | [TestFixture] 7 | public class DecryptorServiceTests 8 | { 9 | private const string TEST_PASSWORD = "testPassword123"; 10 | private FileInfo _encryptedFile = null!; 11 | private FileInfo _outputFile = null!; 12 | 13 | [SetUp] 14 | public void Setup() 15 | { 16 | _encryptedFile = new FileInfo(Path.Combine("TestFiles", "test.encrypted")); 17 | _outputFile = new FileInfo(Path.Combine("TestFiles", "test.decrypted")); 18 | } 19 | 20 | [Test] 21 | public void TryDecrypt_ValidJob_ReturnsSuccessResult() 22 | { 23 | // Arrange 24 | var file = new FileInfo(Path.Combine("TestFiles", Guid.NewGuid().ToString())); 25 | File.WriteAllText(file.FullName, "test test test"); 26 | 27 | OpenSsl.Encrypt(file, Encoding.UTF8.GetBytes(TEST_PASSWORD), _encryptedFile); 28 | var validJob = DecryptJob.Valid(_encryptedFile, _outputFile); 29 | var passwordBytes = Encoding.UTF8.GetBytes(TEST_PASSWORD); 30 | 31 | // Act 32 | DecryptResult result = DecryptorService.TryDecrypt(passwordBytes, validJob); 33 | 34 | // Assert 35 | result.DecryptedOk.ShouldBeTrue(); 36 | result.Source.ShouldBe(_encryptedFile); 37 | result.Dest.ShouldBe(_outputFile); 38 | } 39 | 40 | [Test] 41 | public void TryDecrypt_InvalidJob_ReturnsFailureWithError() 42 | { 43 | // Arrange 44 | const string ERROR_MESSAGE = "Invalid job error"; 45 | var invalidJob = DecryptJob.Invalid(_encryptedFile, _outputFile, ERROR_MESSAGE); 46 | var passwordBytes = Encoding.UTF8.GetBytes(TEST_PASSWORD); 47 | 48 | // Act 49 | var result = DecryptorService.TryDecrypt(passwordBytes, invalidJob); 50 | 51 | // Assert 52 | result.ErrorMessage.ShouldBe(ERROR_MESSAGE); 53 | result.DecryptedOk.ShouldBeFalse(); 54 | result.Source.ShouldBe(_encryptedFile); 55 | result.Dest.ShouldBe(_outputFile); 56 | } 57 | 58 | [Test] 59 | public void TryDecrypt_DecryptionFails_ReturnsFailureWithError() 60 | { 61 | // Arrange 62 | var validJob = DecryptJob.Valid(_encryptedFile, _outputFile); 63 | var invalidPassword = "wrong password"u8.ToArray(); 64 | 65 | // Act 66 | var result = DecryptorService.TryDecrypt(invalidPassword, validJob); 67 | 68 | // Assert 69 | result.DecryptedOk.ShouldBeFalse(); 70 | result.ErrorMessage.ShouldNotBeNullOrEmpty(); 71 | result.Source.ShouldBe(_encryptedFile); 72 | result.Dest.ShouldBe(_outputFile); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | *.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/Qnap.cs: -------------------------------------------------------------------------------- 1 | using QnapBackupDecryptor.Core.Models; 2 | 3 | namespace QnapBackupDecryptor.Core; 4 | 5 | public static class Qnap 6 | { 7 | private static readonly byte[] QnapFilePrefixV1 = "__QCS__"u8.ToArray(); 8 | 9 | private static readonly byte[] QnapFilePrefixV2 = [75, 54, 108, 114, 94, 125, 28, 49, 1]; 10 | 11 | private const byte QNAP_V2_COMPRESSED = 1; 12 | 13 | public static Result IsQnapEncrypted(FileInfo file) 14 | { 15 | if(file.Exists == false || file.Length < QnapFilePrefixV1.Length) 16 | return Result.ErrorResult("File does not exist or is too small", new QnapEncryptionCheckResult(false, 0, false)); 17 | 18 | if (IsV1Encrypted(file)) 19 | return Result.OkResult(new QnapEncryptionCheckResult(true, 1, false)); 20 | 21 | if (IsV2Encrypted(file)) 22 | return Result.OkResult(new QnapEncryptionCheckResult(true, 2, IsCompressed(file))); 23 | 24 | return Result.OkResult(new QnapEncryptionCheckResult(false, 0, false)); 25 | } 26 | 27 | private static Result IsV1Encrypted(FileInfo file) 28 | { 29 | var saltHeaderBytes = new byte[QnapFilePrefixV1.Length]; 30 | try 31 | { 32 | using var fileStream = file.OpenRead(); 33 | _ = fileStream.Read(saltHeaderBytes); 34 | return Result.OkResult(saltHeaderBytes.SequenceEqual(QnapFilePrefixV1)); 35 | } 36 | catch (Exception ex) 37 | { 38 | return Result.ErrorResult(ex.Message, false); 39 | } 40 | } 41 | 42 | private static Result IsV2Encrypted(FileInfo file) 43 | { 44 | var saltHeaderBytes = new byte[QnapFilePrefixV2.Length]; 45 | try 46 | { 47 | using var fileStream = file.OpenRead(); 48 | _ = fileStream.Read(saltHeaderBytes); 49 | return Result.OkResult(saltHeaderBytes.SequenceEqual(QnapFilePrefixV2)); 50 | } 51 | catch (Exception ex) 52 | { 53 | return Result.ErrorResult(ex.Message, false); 54 | } 55 | } 56 | 57 | private static Result IsCompressed(FileInfo file) 58 | { 59 | if (IsV2Encrypted(file) == false) 60 | return Result.OkResult(false); 61 | 62 | try 63 | { 64 | using var fileStream = file.OpenRead(); 65 | fileStream.Seek(9, SeekOrigin.Begin); 66 | return Result.OkResult(fileStream.ReadByte() == QNAP_V2_COMPRESSED); 67 | } 68 | catch (Exception ex) 69 | { 70 | return Result.ErrorResult(ex.Message, false); 71 | } 72 | } 73 | 74 | } -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Console/Options.cs: -------------------------------------------------------------------------------- 1 | using CommandLine; 2 | using CommandLine.Text; 3 | 4 | namespace QnapBackupDecryptor.Console; 5 | 6 | internal sealed class Options 7 | { 8 | [Option('p', "password", Required = false, HelpText = "Password")] 9 | public string? Password { get; init; } 10 | 11 | [Option('e', "encrypted", Required = true, HelpText = "Encrypted file or folder")] 12 | public required string EncryptedSource { get; init; } 13 | 14 | [Option('d', "decrypted", Required = true, HelpText = "Where to place the decrypted file(s)")] 15 | public required string OutputDestination { get; init; } 16 | 17 | [Option('s', "subfolders", Required = false, HelpText = "Include Subfolders (default: false)")] 18 | public bool IncludeSubfolders { get; init; } = false; 19 | 20 | [Option('v', "verbose", Required = false, HelpText = "Set output to verbose")] 21 | public bool Verbose { get; init; } 22 | 23 | [Option('o', "overwrite", Required = false, HelpText = "Overwrite file(s) in output (default: false)")] 24 | public bool Overwrite { get; init; } = false; 25 | 26 | [Option('r', "removeencrypted", Required = false, HelpText = "Delete encrypted files when decrypted (default: false)")] 27 | public bool RemoveEncrypted { get; init; } = false; 28 | 29 | [Option('i', "inplace", Required = false, HelpText = "Decrypt files in-place (default: false)")] 30 | public bool InPlace { get; init; } = false; 31 | 32 | [Option('y', "silent", Required = false, HelpText = "Silent - 'Yes' to all confirmation prompts (default: false)")] 33 | public bool Silent { get; init; } = false; 34 | 35 | [Usage(ApplicationAlias = "QnapBackupDecryptor")] 36 | // ReSharper disable once UnusedMember.Global // Used by the console 37 | public static IEnumerable Examples 38 | { 39 | get 40 | { 41 | yield return new Example("Decrypt a single file", new Options { EncryptedSource = "file.bin", OutputDestination = "out.bin", Password = "Pa$$word" }); 42 | yield return new Example("Decrypt a folder", new Options { EncryptedSource = "./encryptedfolder", OutputDestination = "./decryptedfolder", Password = "Pa$$word" }); 43 | yield return new Example("Decrypt a folder, and delete the source encrypted files", new Options { EncryptedSource = "./encryptedfolder", OutputDestination = "./decryptedfolder", RemoveEncrypted = true }); 44 | yield return new Example("Decrypt a folder, overwriting files in the destination", new Options { EncryptedSource = "./encryptedfolder", OutputDestination = "./decryptedfolder", Password = "Pa$$word", Overwrite = true }); 45 | yield return new Example("Decrypt a folder and all subfolders, and prompt for password", new Options { EncryptedSource = "./encryptedfolder", OutputDestination = "./decryptedfolder", IncludeSubfolders = true }); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /.github/workflows/ReleaseAll.yml: -------------------------------------------------------------------------------- 1 | name: ReleaseAll 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | release: 9 | name: Release 10 | strategy: 11 | matrix: 12 | kind: ["linux", "windows", "macOS"] 13 | include: 14 | - kind: linux 15 | os: ubuntu-latest 16 | target: linux-x64 17 | - kind: windows 18 | os: windows-latest 19 | target: win-x64 20 | - kind: macOS 21 | os: macos-latest 22 | target: osx-x64 23 | runs-on: ${{ matrix.os }} 24 | env: 25 | DOTNET_NOLOGO: true 26 | steps: 27 | - name: Checkout 28 | uses: actions/checkout@v1 29 | 30 | - name: Setup .NET 31 | uses: actions/setup-dotnet@v1 32 | with: 33 | dotnet-version: 8.0.x 34 | 35 | - name: BuildFrameworkDep 36 | shell: bash 37 | working-directory: src 38 | run: | 39 | tag=$(git describe --tags --abbrev=0) 40 | release_name="QnapBackupDecryptor-FD-$tag-${{ matrix.target }}" 41 | 42 | # Build everything 43 | dotnet publish ./QnapBackupDecryptor.Console/QnapBackupDecryptor.Console.csproj -c Release -f net8.0 -r ${{ matrix.target }} --self-contained false -p:PublishSingleFile=true -o "./releases/$release_name" -p:DebugType=None -p:DebugSymbols=false -p:Version=${tag} 44 | 45 | # Pack files 46 | if [ "${{ matrix.target }}" == "win-x64" ]; then 47 | # Pack to zip for Windows 48 | mv ./releases/$release_name/QnapBackupDecryptor.Console.exe ./releases/$release_name/QnapBackupDecryptor.exe 49 | 7z a -tzip "../${release_name}.zip" "./releases/${release_name}/*" 50 | else 51 | mv ./releases/$release_name/QnapBackupDecryptor.Console ./releases/$release_name/QnapBackupDecryptor 52 | tar czvf "../${release_name}.tar.gz" "./releases/$release_name" 53 | fi 54 | 55 | # Delete output directory 56 | rm -r "./releases/$release_name" 57 | 58 | - name: Publish 59 | uses: softprops/action-gh-release@v1 60 | with: 61 | files: "QnapBackupDecryptor-*" 62 | env: 63 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 64 | 65 | - name: BuildSelfContained 66 | shell: bash 67 | working-directory: src 68 | run: | 69 | tag=$(git describe --tags --abbrev=0) 70 | release_name="QnapBackupDecryptor-SC-$tag-${{ matrix.target }}" 71 | 72 | # Build everything 73 | dotnet publish QnapBackupDecryptor.sln -c Release -f net8.0 -r ${{ matrix.target }} --self-contained true -o "./releases/$release_name" -p:DebugType=None -p:DebugSymbols=false -p:Version=${tag} 74 | 75 | # Pack files 76 | if [ "${{ matrix.target }}" == "win-x64" ]; then 77 | # Pack to zip for Windows 78 | 7z a -tzip "../${release_name}.zip" "./releases/${release_name}/*" 79 | else 80 | tar czvf "../${release_name}.tar.gz" "./releases/$release_name" 81 | fi 82 | 83 | # Delete output directory 84 | rm -r "./releases/$release_name" 85 | 86 | - name: Publish 87 | uses: softprops/action-gh-release@v1 88 | with: 89 | files: "QnapBackupDecryptor-*" 90 | env: 91 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 92 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/JobMaker.cs: -------------------------------------------------------------------------------- 1 | using QnapBackupDecryptor.Core.Models; 2 | 3 | namespace QnapBackupDecryptor.Core; 4 | 5 | public static class JobMaker 6 | { 7 | public static IReadOnlyList CreateDecryptJobs(string encryptedSource, string decryptedTarget, bool overwrite, bool includeSubFolders) 8 | { 9 | if (Directory.Exists(encryptedSource) == false && File.Exists(encryptedSource) == false) 10 | return DecryptJob.Invalid(new DirectoryInfo(encryptedSource), new FileInfo(decryptedTarget), "Source does not exist").ToJobs(); 11 | 12 | var sourceIsFolder = IsFolder(encryptedSource); 13 | var destIsFolder = Directory.Exists(decryptedTarget) && IsFolder(decryptedTarget); 14 | 15 | if (sourceIsFolder & destIsFolder == false) 16 | return DecryptJob.Invalid(new DirectoryInfo(encryptedSource), new FileInfo(decryptedTarget), "Cannot write an encrypted folder to a single file").ToJobs(); 17 | 18 | if (sourceIsFolder & destIsFolder) 19 | return FolderToFolderJobs(new DirectoryInfo(encryptedSource), new DirectoryInfo(decryptedTarget), overwrite, includeSubFolders); 20 | 21 | if (destIsFolder) 22 | return FileToFolderJob(new FileInfo(encryptedSource), new DirectoryInfo(decryptedTarget), overwrite).ToJobs(); 23 | else 24 | return FileToFileJob(new FileInfo(encryptedSource), new FileInfo(decryptedTarget), overwrite).ToJobs(); 25 | } 26 | 27 | private static DecryptJob FileToFileJob(FileInfo encryptedFile, FileInfo outputFile, bool overwrite) 28 | { 29 | if (encryptedFile.Exists == false) 30 | return DecryptJob.Invalid(encryptedFile, outputFile, "Encrypted file doesn't exist"); 31 | 32 | if (outputFile.Exists & overwrite == false) 33 | return DecryptJob.Invalid(encryptedFile, outputFile, "Output file already exists, use --overwrite to overwrite files."); 34 | 35 | if (outputFile.Exists & outputFile.Attributes.HasFlag(FileAttributes.ReadOnly)) 36 | return DecryptJob.Invalid(encryptedFile, outputFile, "Cannot write to output file - it's ReadOnly in the file system."); 37 | 38 | if (OpenSsl.IsOpenSslEncrypted(encryptedFile) == false) 39 | return DecryptJob.Invalid(encryptedFile, outputFile, "File is not encrypted with the OpenSSL method."); 40 | 41 | return DecryptJob.Valid(encryptedFile, outputFile); 42 | } 43 | 44 | private static DecryptJob FileToFolderJob(FileInfo encryptedFile, FileSystemInfo outputFolder, bool overwrite) 45 | { 46 | var outputFile = new FileInfo(Path.Combine(outputFolder.FullName, encryptedFile.Name)); 47 | return FileToFileJob(encryptedFile, outputFile, overwrite); 48 | } 49 | 50 | private static IReadOnlyList FolderToFolderJobs(DirectoryInfo encryptedFolder, FileSystemInfo outputFolder, bool overwrite, bool includeSubfolders) 51 | { 52 | if (encryptedFolder.Exists == false) 53 | return DecryptJob.Invalid(encryptedFolder, outputFolder, "Encrypted folder doesn't exist").ToJobs(); 54 | 55 | if (outputFolder.Exists & outputFolder.Attributes.HasFlag(FileAttributes.ReadOnly)) 56 | return DecryptJob.Invalid(encryptedFolder, outputFolder, "Cannot write to output folder - it's ReadOnly in the file system.").ToJobs(); 57 | 58 | return encryptedFolder 59 | .EnumerateFiles("*.*", includeSubfolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) 60 | .AsParallel() 61 | .Select(encryptedFile => FileToFolderJob(encryptedFile, outputFolder, overwrite)) 62 | .ToList(); 63 | } 64 | 65 | private static bool IsFolder(string encryptedSource) 66 | => File.GetAttributes(encryptedSource).HasFlag(FileAttributes.Directory); 67 | } -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core.Tests/QnapTests.cs: -------------------------------------------------------------------------------- 1 | namespace QnapBackupDecryptor.Core.Tests; 2 | 3 | [TestFixture] 4 | public class QnapTests 5 | { 6 | private FileInfo _validFileV1 = null!; 7 | private FileInfo _validFileV2Compressed = null!; 8 | private FileInfo _validFileV2NoCompressed = null!; 9 | private FileInfo _invalidFile = null!; 10 | 11 | [SetUp] 12 | public void Setup() 13 | { 14 | var testFilesDir = Path.Combine("TestFiles", Guid.NewGuid().ToString()); 15 | Directory.CreateDirectory(testFilesDir); 16 | 17 | _validFileV1 = new FileInfo(Path.Combine(testFilesDir, "validV1.qnap")); 18 | File.WriteAllBytes(_validFileV1.FullName, "__QCS__"u8.ToArray()); 19 | 20 | _validFileV2Compressed = new FileInfo(Path.Combine(testFilesDir, "validV2Compressed.qnap")); 21 | File.WriteAllBytes(_validFileV2Compressed.FullName, [75, 54, 108, 114, 94, 125, 28, 49, 1, 1, 33, 22, 44, 55]); 22 | 23 | _validFileV2NoCompressed = new FileInfo(Path.Combine(testFilesDir, "validV2NoCompressed.qnap")); 24 | File.WriteAllBytes(_validFileV2NoCompressed.FullName, [75, 54, 108, 114, 94, 125, 28, 49, 1, 0, 33, 22, 44, 55]); 25 | 26 | _invalidFile = new FileInfo(Path.Combine(testFilesDir, "invalid.qnap")); 27 | File.WriteAllBytes(_invalidFile.FullName, [1, 2, 3, 4]); 28 | } 29 | 30 | [TearDown] 31 | public void TearDown() 32 | { 33 | if (_validFileV1.Directory?.Exists == true) 34 | _validFileV1.Directory.Delete(true); 35 | } 36 | 37 | [Test] 38 | public void IsQnapEncrypted_ValidV1File_ReturnsEncryptionVersion1() 39 | { 40 | // Act 41 | var result = Qnap.IsQnapEncrypted(_validFileV1); 42 | 43 | // Assert 44 | result.IsSuccess.ShouldBeTrue(); 45 | result.Data.IsQnapEncrypted.ShouldBeTrue(); 46 | result.Data.EncryptionVersion.ShouldBe(1); 47 | result.Data.Compressable.ShouldBeFalse(); 48 | } 49 | 50 | [Test] 51 | public void IsQnapEncrypted_ValidV2CompressedFile_ReturnsEncryptionVersion2WithCompression() 52 | { 53 | // Act 54 | var result = Qnap.IsQnapEncrypted(_validFileV2Compressed); 55 | 56 | // Assert 57 | result.IsSuccess.ShouldBeTrue(); 58 | result.Data.IsQnapEncrypted.ShouldBeTrue(); 59 | result.Data.EncryptionVersion.ShouldBe(2); 60 | result.Data.Compressable.ShouldBeTrue(); 61 | } 62 | 63 | [Test] 64 | public void IsQnapEncrypted_ValidV2NoCompressedFile_ReturnsEncryptionVersion2WithoutCompression() 65 | { 66 | // Act 67 | var result = Qnap.IsQnapEncrypted(_validFileV2NoCompressed); 68 | 69 | // Assert 70 | result.IsSuccess.ShouldBeTrue(); 71 | result.Data.IsQnapEncrypted.ShouldBeTrue(); 72 | result.Data.EncryptionVersion.ShouldBe(2); 73 | result.Data.Compressable.ShouldBeFalse(); 74 | } 75 | 76 | [Test] 77 | public void IsQnapEncrypted_InvalidFile_ReturnsError() 78 | { 79 | // Act 80 | var result = Qnap.IsQnapEncrypted(_invalidFile); 81 | 82 | // Assert 83 | result.IsError.ShouldBeTrue(); 84 | result.Data.IsQnapEncrypted.ShouldBeFalse(); 85 | result.Data.EncryptionVersion.ShouldBe(0); 86 | result.Data.Compressable.ShouldBeFalse(); 87 | } 88 | 89 | [Test] 90 | public void IsQnapEncrypted_FileTooSmall_ReturnsError() 91 | { 92 | // Arrange 93 | var smallFile = new FileInfo(Path.Combine("TestFiles", "small.qnap")); 94 | File.WriteAllBytes(smallFile.FullName, [1]); 95 | 96 | // Act 97 | var result = Qnap.IsQnapEncrypted(smallFile); 98 | 99 | // Assert 100 | result.IsError.ShouldBeTrue(); 101 | result.Data.IsQnapEncrypted.ShouldBeFalse(); 102 | result.Data.EncryptionVersion.ShouldBe(0); 103 | result.Data.Compressable.ShouldBeFalse(); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Console/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | using System.Diagnostics; 3 | using System.Text; 4 | using CommandLine; 5 | using QnapBackupDecryptor.Core; 6 | using QnapBackupDecryptor.Core.Models; 7 | using Spectre.Console; 8 | 9 | namespace QnapBackupDecryptor.Console; 10 | 11 | class Program 12 | { 13 | static void Main(string[] args) 14 | { 15 | Parser.Default 16 | .ParseArguments(args) 17 | .WithParsed(Run); 18 | } 19 | 20 | private static void Run(Options options) 21 | { 22 | // Double check delete is wanted 23 | if (Prompts.EnsureDeleteWanted(options) == false) 24 | return; 25 | 26 | // Double check in-place change is wanted 27 | if (Prompts.EnsureInPlaceWanted(options) == false) 28 | return; 29 | 30 | var stopwatch = Stopwatch.StartNew(); 31 | 32 | // Decrypt Files 33 | var decryptJobs = GetDecryptJobs(options).Where(j => j.IsValid).ToList(); 34 | var decryptResults = Decrypt(decryptJobs, GetPassword(options)); 35 | 36 | // Delete Files (if requested) 37 | var filesToDelete = GetFilesToDelete(decryptResults, options); 38 | var deleteResults = Delete(filesToDelete); 39 | 40 | stopwatch.Stop(); 41 | 42 | Output.ShowResults(decryptResults, deleteResults, options.Verbose, stopwatch.Elapsed); 43 | } 44 | 45 | private static byte[] GetPassword(Options options) 46 | => string.IsNullOrEmpty(options.Password) 47 | ? Prompts.GetPassword() 48 | : Encoding.UTF8.GetBytes(options.Password); 49 | 50 | private static IReadOnlyList GetDecryptJobs(Options options) 51 | { 52 | return AnsiConsole 53 | .Status() 54 | .Start("Getting Files...", statusContext => 55 | { 56 | statusContext.Spinner(Spinner.Known.SimpleDots); 57 | statusContext.SpinnerStyle(Style.Parse("green")); 58 | 59 | return JobMaker.CreateDecryptJobs( 60 | encryptedSource: options.EncryptedSource, 61 | decryptedTarget: options.OutputDestination, 62 | overwrite: options.Overwrite, 63 | includeSubFolders: options.IncludeSubfolders); 64 | }); 65 | } 66 | 67 | private static IReadOnlyList Decrypt(IReadOnlyCollection decryptJobs, byte[] password) 68 | { 69 | var decryptResults = new ConcurrentBag(); 70 | 71 | AnsiConsole.Progress() 72 | .Columns(Output.GetProgressColumns()) 73 | .AutoClear(true) 74 | .Start(progressContext => 75 | { 76 | var progressTask = progressContext.AddTask("[green]Decrypting Files[/]"); 77 | progressTask.MaxValue = decryptJobs.Count; 78 | 79 | Parallel.ForEach(decryptJobs, job => 80 | { 81 | var decryptResult = DecryptorService.TryDecrypt(password, job); 82 | decryptResults.Add(decryptResult); 83 | progressTask.Increment(1); 84 | }); 85 | }); 86 | 87 | return decryptResults.ToList(); 88 | } 89 | 90 | private static IReadOnlyList GetFilesToDelete(IReadOnlyList deleteResults, Options options) 91 | { 92 | if (options.RemoveEncrypted == false) 93 | return []; 94 | 95 | return deleteResults 96 | .Where(r => r.DecryptedOk) 97 | .Select(r => r.Source) 98 | .ToList(); 99 | } 100 | 101 | private static IReadOnlyList Delete(IReadOnlyList filesToDelete) 102 | { 103 | var deleteResults = new ConcurrentBag(); 104 | 105 | AnsiConsole.Progress() 106 | .Columns(Output.GetProgressColumns()) 107 | .AutoClear(true) 108 | .Start(progressContext => 109 | { 110 | var progressTask = progressContext.AddTask("[yellow]Deleting Files\t[/]"); 111 | progressTask.MaxValue = filesToDelete.Count; 112 | 113 | Parallel.ForEach(filesToDelete, job => 114 | { 115 | var deleteResult = FileService.TryDelete(job); 116 | deleteResults.Add(deleteResult); 117 | progressTask.Increment(1); 118 | }); 119 | 120 | }); 121 | 122 | return deleteResults.ToList(); 123 | } 124 | 125 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![BuildAndTest-Linux](https://github.com/mark-s/QnapBackupDecryptor/actions/workflows/CIBuildTest-Linux.yml/badge.svg)](https://github.com/mark-s/QnapBackupDecryptor/actions/workflows/CIBuildTest-Linux.yml) [![BuildAndTest-Windows](https://github.com/mark-s/QnapBackupDecryptor/actions/workflows/CIBuildTest-Win.yml/badge.svg)](https://github.com/mark-s/QnapBackupDecryptor/actions/workflows/CIBuildTest-Win.yml) [![ReleaseAll](https://github.com/mark-s/QnapBackupDecryptor/actions/workflows/ReleaseAll.yml/badge.svg)](https://github.com/mark-s/QnapBackupDecryptor/actions/workflows/ReleaseAll.yml) 2 | # Qnap Backup Decryptor 3 | 4 | A tool to decrypt QNAP NAS encrypted backup files. 5 | 6 | This will decrypt **backup** files (not sync files) created using the [QNAP Hybrid Backup Sync](https://www.qnap.com/en-uk/software/hybrid-backup-sync) tool. 7 | 8 | This tool is an alternative to the [QENC Decrypter](https://www.qnap.com/en-uk/utilities/enterprise) provided by QNAP. **This tool is faster by orders of magnitude** (eg: 1,800 files takes 0.9 seconds using this tool and approx 20 seconds using the QNAP tool). 9 | 10 | ![See it in action](https://raw.githubusercontent.com/mark-s/QnapBackupDecryptor/master/Images/ExampleDecrypt.gif) 11 | 12 | ## Installation 13 | 14 | Binaries for Windows, Linux and Mac, are available in [Releases](https://github.com/mark-s/QnapBackupDecryptor/releases). 15 | 16 | The QnapBackupDecryptor-FD files are *Framework dependent* and require an install of .NET 8 to be installed on the system. Available from [here](https://dotnet.microsoft.com/download/dotnet/8.0). 17 | If installing .NET is not an option, the QnapBackupDecryptor-SC files are larger, but do not require a .NET 8 install. 18 | 19 | ## Quickstart 20 | 21 | **Decrypt a Folder, prompt for password and see the complete output file list** 22 | 23 | This is the same as the eample gif above. 24 | 25 | - Windows 26 | `QnapBackupDecryptor.exe -e c:\Files\Enc -d c:\Files\Dec --verbose` 27 | - Linux 28 | `./QnapBackupDecryptor.Console -e ./Files/Enc -d ./Files/Dec --verbose` 29 | 30 | **Decrypt a Folder and see the complete list of files, but specify the password** 31 | 32 | - Windows 33 | `QnapBackupDecryptor.exe -e c:\Files\Enc -d c:\Files\Dec --verbose -p Pa$$w0rd` 34 | - Linux 35 | `./QnapBackupDecryptor.Console -e ./Files/Enc -d ./Files/Dec --verbose -p Pa$$w0rd` 36 | 37 | **Decrypt a Folder and overwrite any duplicate files in the destination** 38 | 39 | - Windows 40 | `QnapBackupDecryptor.exe -e c:\Files\Enc -d c:\Files\Dec --verbose --overwrite` 41 | - Linux 42 | `./QnapBackupDecryptor.Console -e ./Files/Enc -d ./Files/Dec --verbose --overwrite` 43 | 44 | **Decrypt a Folder and delete successfully decrypted source files** 45 | 46 | WARNING: This will delete the Encrypted files if they are successfully decrypted. 47 | Ensure you have backups as the files will not be recoverable! 48 | 49 | This will prompt for confirmation (unless you specify -y / --silent) 50 | 51 | - Windows 52 | `QnapBackupDecryptor.exe -e c:\Files\Enc -d c:\Files\Dec --verbose --removeencrypted` 53 | - Linux 54 | `./QnapBackupDecryptor.Console -e ./Files/Enc -d ./Files/Dec --verbose --removeencrypted` 55 | 56 | **Decrypt a single file to a folder** 57 | 58 | - Windows 59 | `QnapBackupDecryptor.exe -e c:\Files\Enc\Encrypted.jpg -d c:\Files\Dec --verbose` 60 | - Linux 61 | `./QnapBackupDecryptor.Console -e ./Files/Enc/Encrypted.jpg -d ./Files/Dec --verbose` 62 | 63 | **Decrypt a single file and specify the new name** 64 | 65 | - Windows 66 | `QnapBackupDecryptor.exe -e c:\Files\Enc\Encrypted.jpg -d c:\Files\Dec\Decrypted.jpg --verbose` 67 | - Linux 68 | `./QnapBackupDecryptor.Console -e ./Files/Enc/Encrypted.jpg -d ./Files/Dec/Decrypted.jpg --verbose` 69 | 70 | ## Available Options 71 | 72 | |Short|Long| |Default| 73 | |------------- |------------- |------------- |------------- | 74 | |-e|--encrypted|Required. Encrypted file or folder|| 75 | |-d|--decrypted|Required. Where to place the decrypted file(s)|| 76 | |-p|--password|Password|will prompt| 77 | |-s|--subfolders|Include Subfolders|false| 78 | |-r|--removeencrypted|Delete encrypted files (will prompt)|false| 79 | |-v|--verbose|Set output to verbose|false| 80 | |-o|--overwrite|Overwrite file(s) in output|false| 81 | |-y|--silent|Silent - 'Yes' to all confirmation prompts|false| 82 | | |--help|Display this help screen.|| 83 | | |--version|Display version information.|| 84 | 85 | ## License 86 | 87 | This project is licensed under the GPL-3.0 License - see the [LICENSE.md](LICENSE.md) file for details 88 | 89 | # Disclaimer 90 | 91 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 92 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Console/Output.cs: -------------------------------------------------------------------------------- 1 | using QnapBackupDecryptor.Core.Models; 2 | using Spectre.Console; 3 | 4 | namespace QnapBackupDecryptor.Console; 5 | 6 | internal static class Output 7 | { 8 | public static void ShowResults(IReadOnlyList decryptResults, IReadOnlyList deleteResults, bool verbose, TimeSpan elapsedTime) 9 | { 10 | if (verbose && decryptResults.Count > 1) 11 | { 12 | ShowFileListResults(decryptResults, deleteResults); 13 | ShowSimpleResults(decryptResults, deleteResults); 14 | } 15 | else 16 | { 17 | ShowSimpleResults(decryptResults, deleteResults); 18 | AnsiConsole.MarkupLine("Add --verbose to see details."); 19 | } 20 | 21 | ShowTiming(elapsedTime); 22 | 23 | if (decryptResults.Any(r => r.DecryptedOk == false) || deleteResults.Any(r => r.DeletedOk == false)) 24 | Environment.ExitCode = 1; 25 | } 26 | 27 | private static void ShowSimpleResults(IReadOnlyList decryptResults, IReadOnlyList deleteResults) 28 | { 29 | var table = new Table(); 30 | table 31 | .AddColumn(new TableColumn("Total encrypted files").RightAligned()) 32 | .AddColumn(new TableColumn("Decrypt Ok").RightAligned()) 33 | .AddColumn(new TableColumn("Decrypt Failed").RightAligned()) 34 | .AddColumn(new TableColumn("Delete Ok").RightAligned()) 35 | .AddColumn(new TableColumn("Delete Failed").RightAligned()); 36 | 37 | table.AddRow( 38 | $"{decryptResults.Count}", 39 | $"[green]{decryptResults.Count(r => r.DecryptedOk)}[/]", 40 | $"[red]{decryptResults.Count(r => !r.DecryptedOk)}[/]", 41 | $"[green]{deleteResults.Count(r => r.DeletedOk)}[/]", 42 | $"[red]{deleteResults.Count(r => !r.DeletedOk)}[/]" 43 | ); 44 | 45 | AnsiConsole.Write(table); 46 | } 47 | 48 | private static void ShowFileListResults(IReadOnlyList decryptResults, IReadOnlyList deleteResults) 49 | { 50 | var table = new Table(); 51 | table 52 | .AddColumn(new TableColumn("Decrypt Status").Centered()) 53 | .AddColumn("Encrypted") 54 | .AddColumn("Decrypted"); 55 | 56 | if (decryptResults.Any(r => r.DecryptedOk == false)) 57 | table.AddColumn("Error"); 58 | 59 | if (deleteResults.Any()) 60 | { 61 | table.AddColumn(new TableColumn("Delete Status").Centered()); 62 | if (deleteResults.Any(r => r.DeletedOk == false)) 63 | table.AddColumn("Error"); 64 | } 65 | 66 | var deleteResultsLookup = deleteResults.ToDictionary(r => r.FileToDelete, r => r); 67 | 68 | foreach (var result in decryptResults) 69 | { 70 | var resultRow = DecryptResultToRow(result); 71 | 72 | if (deleteResultsLookup.TryGetValue(result.Source, out var deleteResult)) 73 | resultRow.AddRange(DeleteResultToRow(deleteResult)); 74 | 75 | table.AddRow(resultRow.ToArray()); 76 | } 77 | 78 | AnsiConsole.Write(table); 79 | 80 | } 81 | 82 | private static List DecryptResultToRow(DecryptResult decryptResult) 83 | { 84 | var colour = decryptResult.DecryptedOk ? "green" : "red"; 85 | var status = decryptResult.DecryptedOk ? "OK" : "Fail"; 86 | 87 | var row = new List 88 | { 89 | $"[{colour}]{status}[/]", 90 | $"[{colour}]{decryptResult.Source.FullName}[/]", 91 | $"[{colour}]{decryptResult.Dest.FullName}[/]" 92 | }; 93 | 94 | if (decryptResult.DecryptedOk == false) 95 | row.Add($"[{colour}]{decryptResult.ErrorMessage}[/]"); 96 | 97 | return row; 98 | } 99 | 100 | private static List DeleteResultToRow(DeleteResult? deleteResult) 101 | { 102 | if (deleteResult == null) 103 | return []; 104 | 105 | var colour = deleteResult.DeletedOk ? "green" : "red"; 106 | var status = deleteResult.DeletedOk ? "Deleted" : "Failed"; 107 | 108 | var row = new List 109 | { 110 | $"[{colour}]{status}[/]" 111 | }; 112 | 113 | if (deleteResult.DeletedOk == false) 114 | row.Add($"[{colour}]{deleteResult.ErrorMessage}[/]"); 115 | 116 | return row; 117 | } 118 | 119 | private static void ShowTiming(TimeSpan swElapsed) 120 | { 121 | switch (swElapsed.TotalMinutes) 122 | { 123 | case < 1: 124 | AnsiConsole.MarkupLine($"[bold]Took {swElapsed.TotalSeconds:0.000} seconds[/]"); 125 | break; 126 | default: 127 | AnsiConsole.MarkupLine($"[bold]Took {swElapsed.TotalMinutes} minutes[/]"); 128 | break; 129 | } 130 | } 131 | 132 | public static ProgressColumn[] GetProgressColumns() 133 | => [ 134 | new TaskDescriptionColumn(), 135 | new ProgressBarColumn(), 136 | new PercentageColumn(), 137 | new SpinnerColumn(Spinner.Known.SimpleDots) 138 | ]; 139 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb 341 | /src/QnapBackupDecryptor.Console/Properties/launchSettings.json 342 | -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core/OpenSsl.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography; 2 | using QnapBackupDecryptor.Core.Models; 3 | 4 | namespace QnapBackupDecryptor.Core; 5 | 6 | public static class OpenSsl 7 | { 8 | private const string SALT_HEADER_TEXT = "Salted__"; 9 | private const int SALT_HEADER_SIZE = 8; 10 | private const int SALT_SIZE = 8; 11 | private const int KEY_SIZE = 32; 12 | private const int IV_SIZE = 16; 13 | private const int COMBINED_KEY_AND_IV_LENGTH = KEY_SIZE + IV_SIZE; 14 | 15 | public static Result IsOpenSslEncrypted(FileInfo file) 16 | { 17 | var saltHeaderBytes = new byte[SALT_HEADER_SIZE]; 18 | try 19 | { 20 | using var fileStream = file.OpenRead(); 21 | _ = fileStream.Read(saltHeaderBytes); 22 | var startsWithHeaderText = System.Text.Encoding.UTF8.GetString(saltHeaderBytes) == SALT_HEADER_TEXT; 23 | return Result.OkResult(startsWithHeaderText); 24 | } 25 | catch (Exception ex) 26 | { 27 | return Result.ErrorResult(ex.Message, false); 28 | } 29 | } 30 | 31 | // create openSSl encrypted file 32 | public static Result Encrypt(FileInfo file, byte[] password, FileInfo outputFile) 33 | { 34 | var salt = GenerateSecureRandomBytes(SALT_SIZE); 35 | 36 | var (key, iv) = DeriveKeyAndIV(password, salt); 37 | if (key.Length == 0 || iv.Length == 0 || salt.Length == 0) 38 | return Result.ErrorResult("Key / IV / Salt is invalid", outputFile); 39 | return EncryptFile(file, key, iv, salt, outputFile); 40 | } 41 | 42 | private static Result EncryptFile(FileInfo file, byte[] key, byte[] iv, byte[] salt, FileInfo outputFile) 43 | { 44 | var couldOpenOutputFileForWrite = false; 45 | using var aes = CreateAes(key, iv); 46 | try 47 | { 48 | using var source = file.OpenRead(); 49 | using var destination = outputFile.OpenWrite(); 50 | couldOpenOutputFileForWrite = true; 51 | var encryptor = aes.CreateEncryptor(); 52 | using var cryptoStream = new CryptoStream(destination, encryptor, CryptoStreamMode.Write); 53 | // write the salt header 54 | var saltHeader = System.Text.Encoding.UTF8.GetBytes(SALT_HEADER_TEXT); 55 | destination.Write(saltHeader, 0, SALT_HEADER_SIZE); 56 | // write the salt 57 | destination.Write(salt, 0, SALT_SIZE); 58 | FileHelpers.HideFile(outputFile); 59 | source.CopyTo(cryptoStream); 60 | FileHelpers.ShowFile(outputFile); 61 | return Result.OkResult(outputFile); 62 | } 63 | catch (Exception ex) 64 | { 65 | if (couldOpenOutputFileForWrite == false) 66 | return Result.ErrorResult("could not encrypt - could not write to output file", outputFile, ex); 67 | if (outputFile.TryDelete()) 68 | return Result.ErrorResult("could not encrypt", outputFile, ex); 69 | else 70 | return Result.ErrorResult("could not encrypt and failed to delete temp encrypt file.", outputFile, ex); 71 | } 72 | } 73 | 74 | public static Result Decrypt(FileInfo encryptedFile, byte[] password, FileInfo outputFile) 75 | { 76 | encryptedFile.Refresh(); 77 | if (encryptedFile.Exists == false) 78 | return Result.ErrorResult($"Encrypted file {outputFile.FullName} does not exist", outputFile); 79 | 80 | // check encrypted file size is at least the size of the salt header and salt 81 | if (encryptedFile.Length < SALT_HEADER_SIZE + SALT_SIZE) 82 | return Result.ErrorResult($"Encrypted file {outputFile.FullName} is too small to be encrypted", outputFile); 83 | 84 | var salt = GetSalt(encryptedFile); 85 | 86 | var (key, iv) = DeriveKeyAndIV(password, salt); 87 | 88 | if (key.Length == 0 || iv.Length == 0 || salt.Length == 0) 89 | return Result.ErrorResult("Key / IV / Salt is invalid", outputFile); 90 | 91 | return DecryptFile(encryptedFile, key, iv, outputFile); 92 | } 93 | 94 | private static byte[] GetSalt(FileInfo encryptedFile) 95 | { 96 | using var fileStream = encryptedFile.OpenRead(); 97 | 98 | var salt = new byte[SALT_SIZE]; 99 | fileStream.Position = SALT_HEADER_SIZE; 100 | _ = fileStream.Read(salt, 0, SALT_SIZE); 101 | 102 | return salt; 103 | } 104 | 105 | // This inspired by https://gist.github.com/scottlowe/1411917/bdb474d03da42b6bd46e339ef03780f5301b14d7 106 | private static (byte[] key, byte[] iv) DeriveKeyAndIV(byte[] password, byte[] salt) 107 | { 108 | var keyAndIvBytes = new List(COMBINED_KEY_AND_IV_LENGTH); 109 | 110 | var currentHash = Array.Empty(); 111 | 112 | while (keyAndIvBytes.Count < COMBINED_KEY_AND_IV_LENGTH) 113 | { 114 | var preHashLength = currentHash.Length + password.Length + salt.Length; 115 | var preHash = new byte[preHashLength]; 116 | 117 | Buffer.BlockCopy(currentHash, 0, preHash, 0, currentHash.Length); 118 | Buffer.BlockCopy(password, 0, preHash, currentHash.Length, password.Length); 119 | Buffer.BlockCopy(salt, 0, preHash, currentHash.Length + password.Length, salt.Length); 120 | 121 | currentHash = MD5.HashData(preHash); 122 | keyAndIvBytes.AddRange(currentHash); 123 | } 124 | 125 | // pull out the key 126 | var key = new byte[KEY_SIZE]; 127 | keyAndIvBytes.CopyTo(0, key, 0, KEY_SIZE); 128 | 129 | // pull out the IV 130 | var iv = new byte[IV_SIZE]; 131 | keyAndIvBytes.CopyTo(KEY_SIZE, iv, 0, IV_SIZE); 132 | 133 | return (key, iv); 134 | } 135 | 136 | private static Result DecryptFile(FileInfo encryptedFile, byte[] key, byte[] iv, FileInfo outputFile) 137 | { 138 | var couldOpenOutputFileForWrite = false; 139 | using var aes = CreateAes(key, iv); 140 | 141 | try 142 | { 143 | using var encryptedFileStream = encryptedFile.OpenRead(); 144 | encryptedFileStream.Position = SALT_HEADER_SIZE + SALT_SIZE; 145 | 146 | using var destination = outputFile.OpenWrite(); 147 | couldOpenOutputFileForWrite = true; 148 | 149 | var decryptor = aes.CreateDecryptor(); 150 | using var cryptoStream = new CryptoStream(encryptedFileStream, decryptor, CryptoStreamMode.Read); 151 | 152 | FileHelpers.HideFile(outputFile); 153 | 154 | cryptoStream.CopyTo(destination); 155 | 156 | FileHelpers.ShowFile(outputFile); 157 | 158 | return Result.OkResult(outputFile); 159 | } 160 | catch (Exception ex) 161 | { 162 | if (couldOpenOutputFileForWrite == false) 163 | return Result.ErrorResult("could not decrypt - could not write to output file", outputFile, ex); 164 | 165 | if (outputFile.TryDelete()) 166 | return Result.ErrorResult("could not decrypt", outputFile, ex); 167 | else 168 | return Result.ErrorResult("could not decrypt and failed to delete temp decrypt file.", outputFile, ex); 169 | } 170 | 171 | } 172 | 173 | private static Aes CreateAes(byte[] key, byte[] iv) 174 | { 175 | var aes = Aes.Create(); 176 | 177 | aes.Mode = CipherMode.CBC; 178 | aes.KeySize = 256; 179 | aes.BlockSize = 128; 180 | aes.Key = key; 181 | aes.IV = iv; 182 | aes.Padding = PaddingMode.PKCS7; 183 | 184 | return aes; 185 | } 186 | 187 | private static byte[] GenerateSecureRandomBytes(int length) 188 | { 189 | var randomBytes = new byte[length]; 190 | using (var rng = RandomNumberGenerator.Create()) 191 | { 192 | rng.GetBytes(randomBytes); 193 | } 194 | return randomBytes; 195 | } 196 | } -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core.Tests/JobMakerTests.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | 3 | namespace QnapBackupDecryptor.Core.Tests; 4 | 5 | [TestFixture] 6 | public class JobMakerTests 7 | { 8 | 9 | [Test] 10 | public void GetDecryptJobs_TwoFolders_SourceDoesntExist_Error() 11 | { 12 | // Arrange 13 | // Act 14 | var result = JobMaker.CreateDecryptJobs("/somefolder1", "/somefolder2", false, false); 15 | 16 | // Assert 17 | result.Count.ShouldBe(1); 18 | result[0].IsValid.ShouldBeFalse(); 19 | result[0].ErrorMessage.ShouldBe("Source does not exist"); 20 | } 21 | 22 | [Test] 23 | public void GetDecryptJobs_TwoFolders_DestDoesntExist_ErrorAssumesFileOutput() 24 | { 25 | // Arrange 26 | var path = Directory.GetCurrentDirectory(); 27 | var destPath = Path.Combine(path, "somefolder"); 28 | 29 | // Act 30 | var result = JobMaker.CreateDecryptJobs(path, destPath, false, false); 31 | 32 | // Assert 33 | result.Count.ShouldBe(1); 34 | result[0].IsValid.ShouldBeFalse(); 35 | result[0].ErrorMessage.ShouldBe("Cannot write an encrypted folder to a single file"); 36 | } 37 | 38 | [Test] 39 | public void GetDecryptJobs_EncryptedFileExists_TargetDoesntExist_ProducesValidJob() 40 | { 41 | // Arrange 42 | var encFile = Path.Combine("TestFiles", "encrypted.txt"); 43 | var decFile = Path.Combine("TestFiles", "dec.txt"); 44 | 45 | // Act 46 | var result = JobMaker.CreateDecryptJobs(encFile, decFile, false, false); 47 | 48 | // Assert 49 | result.Count.ShouldBe(1); 50 | result[0].IsValid.ShouldBeTrue(); 51 | result[0].EncryptedFile.FullName.ShouldEndWith(encFile); 52 | result[0].OutputFile.FullName.ShouldEndWith(decFile); 53 | } 54 | 55 | [Test] 56 | public void GetDecryptJobs_EncryptedFileDoesntExist_TargetExists_OverwriteTrue_ProducesInValidJob() 57 | { 58 | // Arrange 59 | var encFile = Path.Combine("TestFiles", "encrypted.txt_NO"); 60 | var decFile = Path.GetTempFileName(); 61 | 62 | // Act 63 | var result = JobMaker.CreateDecryptJobs(encFile, decFile, overwrite: true, false); 64 | 65 | // Assert 66 | result.Count.ShouldBe(1); 67 | result[0].IsValid.ShouldBeFalse(); 68 | result[0].ErrorMessage.ShouldBe("Source does not exist"); 69 | } 70 | 71 | [Test] 72 | public void GetDecryptJobs_EncryptedFileExists_TargetExists_OverwriteFalse_ProducesInValidJob() 73 | { 74 | // Arrange 75 | var encFile = Path.Combine("TestFiles", "encrypted.txt"); 76 | var decFile = Path.GetTempFileName(); 77 | 78 | // Act 79 | var result = JobMaker.CreateDecryptJobs(encFile, decFile, overwrite: false, false); 80 | 81 | // Assert 82 | result.Count.ShouldBe(1); 83 | result[0].IsValid.ShouldBeFalse(); 84 | result[0].ErrorMessage.ShouldBe("Output file already exists, use --overwrite to overwrite files."); 85 | } 86 | 87 | [Test] 88 | public void GetDecryptJobs_EncryptedFileExists_TargetExistsAndReadOnly_ProducesInvalidJob() 89 | { 90 | // Arrange 91 | var encFile = Path.Combine("TestFiles", "encrypted.txt"); 92 | var decFile = Path.GetTempFileName(); 93 | File.SetAttributes(decFile, FileAttributes.ReadOnly); 94 | 95 | try 96 | { 97 | // Act 98 | var result = JobMaker.CreateDecryptJobs(encFile, decFile, overwrite: true, false); 99 | 100 | // Assert 101 | result.Count.ShouldBe(1); 102 | result[0].IsValid.ShouldBeFalse(); 103 | result[0].ErrorMessage.ShouldBe("Cannot write to output file - it's ReadOnly in the file system."); 104 | } 105 | finally 106 | { 107 | // Cleanup 108 | File.SetAttributes(decFile, FileAttributes.Normal); 109 | File.Delete(decFile); 110 | } 111 | } 112 | 113 | [Test] 114 | public void GetDecryptJobs_FileNotEncryptedWithOpenSsl_ProducesInvalidJob() 115 | { 116 | // Arrange 117 | var plainFile = Path.Combine("TestFiles", "plaintext.txt"); 118 | var decFile = Path.Combine("TestFiles", "dec_plain.txt"); 119 | 120 | // Act 121 | var result = JobMaker.CreateDecryptJobs(plainFile, decFile, false, false); 122 | 123 | // Assert 124 | result.Count.ShouldBe(1); 125 | result[0].IsValid.ShouldBeFalse(); 126 | result[0].ErrorMessage.ShouldBe("File is not encrypted with the OpenSSL method."); 127 | } 128 | 129 | [Test] 130 | public void GetDecryptJobs_EncryptedFileExists_TargetExists_OverwriteTrue_ProducesValidJob() 131 | { 132 | // Arrange 133 | var encFile = Path.Combine("TestFiles", "encrypted.txt"); 134 | var decFile = Path.GetTempFileName(); 135 | 136 | try 137 | { 138 | // Act 139 | var result = JobMaker.CreateDecryptJobs(encFile, decFile, overwrite: true, false); 140 | 141 | // Assert 142 | result.Count.ShouldBe(1); 143 | result[0].IsValid.ShouldBeTrue(); 144 | result[0].EncryptedFile.FullName.ShouldEndWith(encFile); 145 | result[0].OutputFile.FullName.ShouldBe(decFile); 146 | } 147 | finally 148 | { 149 | // Cleanup 150 | File.Delete(decFile); 151 | } 152 | } 153 | 154 | [Test] 155 | public void GetDecryptJobs_EncryptedFileToFolder_ProducesValidJob() 156 | { 157 | // Arrange 158 | var encFile = Path.Combine("TestFiles", "encrypted.txt"); 159 | var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); 160 | Directory.CreateDirectory(tempDir); 161 | 162 | try 163 | { 164 | // Act 165 | var result = JobMaker.CreateDecryptJobs(encFile, tempDir, false, false); 166 | 167 | // Assert 168 | result.Count.ShouldBe(1); 169 | result[0].IsValid.ShouldBeTrue(); 170 | result[0].EncryptedFile.FullName.ShouldEndWith(encFile); 171 | result[0].OutputFile.FullName.ShouldEndWith(Path.Combine(tempDir, "encrypted.txt")); 172 | } 173 | finally 174 | { 175 | // Cleanup 176 | Directory.Delete(tempDir, true); 177 | } 178 | } 179 | 180 | [Test] 181 | public void GetDecryptJobs_FolderToFolder_IncludeSubFoldersTrue_ProducesMultipleJobs() 182 | { 183 | // Arrange 184 | List testFileNames = ["encrypted.jpg", "encrypted.txt", "plaintext.txt"]; 185 | var tempDir1 = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); 186 | Directory.CreateDirectory(tempDir1); 187 | foreach (var file in Directory.GetFiles("TestFiles", "*.*", SearchOption.TopDirectoryOnly).Where(x => testFileNames.Contains(x.Split(Path.DirectorySeparatorChar).Last()))) 188 | { 189 | var destFile = Path.Combine(tempDir1, Path.GetFileName(file)); 190 | File.Copy(file, destFile); 191 | } 192 | 193 | var tempDir2 = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); 194 | Directory.CreateDirectory(tempDir2); 195 | 196 | try 197 | { 198 | // Act 199 | var result = JobMaker.CreateDecryptJobs(tempDir1, tempDir2, false, true); 200 | 201 | // Assert 202 | result.Count.ShouldBe(3); 203 | result.Count(j => j.IsValid).ShouldBe(2); // one of the files is not encrypted 204 | 205 | } 206 | finally 207 | { 208 | // Cleanup 209 | Directory.Delete(tempDir2, true); 210 | } 211 | } 212 | 213 | [Test] 214 | public void GetDecryptJobs_FolderToFolder_IncludeSubFoldersFalse_OnlyIncludesTopLevelFiles() 215 | { 216 | // Arrange 217 | var sourceDir = "TestFiles"; // Contains encrypted files 218 | var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); 219 | Directory.CreateDirectory(tempDir); 220 | 221 | try 222 | { 223 | // First count all files (recursive) 224 | var allFiles = Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories).Length; 225 | var topLevelFiles = Directory.GetFiles(sourceDir, "*.*", SearchOption.TopDirectoryOnly).Length; 226 | 227 | // If no subdirectories with files exist, we'll skip this test 228 | if (allFiles == topLevelFiles) 229 | { 230 | Assert.Ignore("No subdirectories with files to test with"); 231 | } 232 | 233 | // Act 234 | var result = JobMaker.CreateDecryptJobs(sourceDir, tempDir, false, false); 235 | 236 | // Assert 237 | result.Count.ShouldBe(topLevelFiles); 238 | } 239 | finally 240 | { 241 | // Cleanup 242 | Directory.Delete(tempDir, true); 243 | } 244 | } 245 | 246 | [Test] 247 | public void GetDecryptJobs_DestFolderReadOnly_ProducesInvalidJob() 248 | { 249 | // Arrange 250 | var sourceDir = "TestFiles"; 251 | var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); 252 | Directory.CreateDirectory(tempDir); 253 | File.SetAttributes(tempDir, FileAttributes.ReadOnly); 254 | 255 | try 256 | { 257 | // Act 258 | var result = JobMaker.CreateDecryptJobs(sourceDir, tempDir, false, false); 259 | 260 | // Assert 261 | result.Count.ShouldBe(1); 262 | result[0].IsValid.ShouldBeFalse(); 263 | result[0].ErrorMessage.ShouldBe("Cannot write to output folder - it's ReadOnly in the file system."); 264 | } 265 | finally 266 | { 267 | // Cleanup 268 | File.SetAttributes(tempDir, FileAttributes.Normal); 269 | Directory.Delete(tempDir, true); 270 | } 271 | } 272 | 273 | [Test] 274 | public void GetDecryptJobs_EncryptedFolderDoesntExist_ProducesInvalidJob() 275 | { 276 | // Arrange 277 | var nonExistentDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); 278 | var tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); 279 | Directory.CreateDirectory(tempDir); 280 | 281 | try 282 | { 283 | // Act - Create another directory to ensure we're testing "Encrypted folder doesn't exist" not just "Source doesn't exist" 284 | var result = JobMaker.CreateDecryptJobs(nonExistentDir, tempDir, false, false); 285 | 286 | // Assert 287 | result.Count.ShouldBe(1); 288 | result[0].IsValid.ShouldBeFalse(); 289 | // The specific message depends on whether the code checks if it's a folder before checking existence 290 | result[0].ErrorMessage.ShouldBeOneOf("Encrypted folder doesn't exist", "Source does not exist"); 291 | } 292 | finally 293 | { 294 | // Cleanup 295 | Directory.Delete(tempDir, true); 296 | } 297 | } 298 | } -------------------------------------------------------------------------------- /src/QnapBackupDecryptor.Core.Tests/OpenSslTests.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Security.Cryptography; 3 | using System.Text; 4 | 5 | namespace QnapBackupDecryptor.Core.Tests; 6 | 7 | [TestFixture] 8 | public class OpenSslTests 9 | { 10 | private const string VALID_TEST_PASSWORD = "wisLUBIMyBNcnvo3eDMS"; 11 | private readonly byte[] _validPasswordBytes = Encoding.UTF8.GetBytes(VALID_TEST_PASSWORD); 12 | private readonly byte[] _invalidPasswordBytes = "Invalid password!"u8.ToArray(); 13 | 14 | [Test] 15 | public void IsOpenSslEncrypted_WhenFileDoesNotExist_ReturnsErrorResult() 16 | { 17 | // Arrange 18 | var nonExistentFile = new FileInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); 19 | 20 | // Act 21 | var result = OpenSsl.IsOpenSslEncrypted(nonExistentFile); 22 | 23 | // Assert 24 | result.IsError.ShouldBeTrue(); 25 | result.Data.ShouldBeFalse(); 26 | } 27 | 28 | [Test] 29 | public void IsOpenSslEncrypted_WhenFileExists_ButEmptyFile_ReturnsFalse() 30 | { 31 | // Arrange 32 | var tempFile = Path.GetTempFileName(); 33 | var emptyFile = new FileInfo(tempFile); 34 | 35 | try 36 | { 37 | // Act 38 | var result = OpenSsl.IsOpenSslEncrypted(emptyFile); 39 | 40 | // Assert 41 | result.IsSuccess.ShouldBeTrue(); 42 | result.Data.ShouldBeFalse(); 43 | } 44 | finally 45 | { 46 | // Cleanup 47 | File.Delete(tempFile); 48 | } 49 | } 50 | 51 | [Test] 52 | public void IsOpenSslEncrypted_WhenFileExistsWithWrongHeader_ReturnsFalse() 53 | { 54 | // Arrange 55 | var tempFile = Path.GetTempFileName(); 56 | File.WriteAllText(tempFile, "NotSalted"); 57 | var fileWithWrongHeader = new FileInfo(tempFile); 58 | 59 | try 60 | { 61 | // Act 62 | var result = OpenSsl.IsOpenSslEncrypted(fileWithWrongHeader); 63 | 64 | // Assert 65 | result.IsSuccess.ShouldBeTrue(); 66 | result.Data.ShouldBeFalse(); 67 | } 68 | finally 69 | { 70 | // Cleanup 71 | File.Delete(tempFile); 72 | } 73 | } 74 | 75 | [Test] 76 | public void Decrypt_WhenFileDoesNotExist_ReturnsErrorResult() 77 | { 78 | // Arrange 79 | var nonExistentFile = new FileInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); 80 | var outputFile = new FileInfo(Path.Combine(Path.GetTempPath(), "output.txt")); 81 | 82 | // Act 83 | var result = OpenSsl.Decrypt(nonExistentFile, _validPasswordBytes, outputFile); 84 | 85 | // Assert 86 | result.IsError.ShouldBeTrue(); 87 | result.ErrorMessage.ShouldNotBeNullOrEmpty(); 88 | } 89 | 90 | [Test] 91 | public void Decrypt_WithTooShortFile_ReturnsErrorResult() 92 | { 93 | // Arrange 94 | var tempFile = Path.GetTempFileName(); 95 | File.WriteAllText(tempFile, "Salted__"); // Only header, no salt 96 | var shortFile = new FileInfo(tempFile); 97 | var outputFile = new FileInfo(Path.Combine(Path.GetTempPath(), "output.txt")); 98 | 99 | try 100 | { 101 | // Act 102 | var result = OpenSsl.Decrypt(shortFile, _validPasswordBytes, outputFile); 103 | 104 | // Assert 105 | result.IsError.ShouldBeTrue(); 106 | } 107 | finally 108 | { 109 | // Cleanup 110 | File.Delete(tempFile); 111 | } 112 | } 113 | 114 | [Test] 115 | public void Decrypt_WithReadOnlyOutputFile_ReturnsErrorResult() 116 | { 117 | // Arrange 118 | var encryptedFile = new FileInfo(Path.Combine("TestFiles", "encrypted.txt")); 119 | var outputTempFile = Path.GetTempFileName(); 120 | File.SetAttributes(outputTempFile, FileAttributes.ReadOnly); 121 | var readOnlyOutputFile = new FileInfo(outputTempFile); 122 | 123 | try 124 | { 125 | // Act 126 | var result = OpenSsl.Decrypt(encryptedFile, _validPasswordBytes, readOnlyOutputFile); 127 | 128 | // Assert 129 | result.IsError.ShouldBeTrue(); 130 | } 131 | finally 132 | { 133 | // Cleanup 134 | File.SetAttributes(outputTempFile, FileAttributes.Normal); 135 | File.Delete(outputTempFile); 136 | } 137 | } 138 | 139 | [Test] 140 | public void Decrypt_WithValidCredentials_DecryptsTextFile() 141 | { 142 | // Arrange 143 | var encryptedFile = new FileInfo(Path.Combine("TestFiles", "encrypted.txt")); 144 | var outputFile = new FileInfo(Path.Combine(Path.GetTempPath(), Path.GetTempFileName())); 145 | 146 | if (outputFile.Exists) 147 | outputFile.Delete(); 148 | 149 | try 150 | { 151 | // Act 152 | var result = OpenSsl.Decrypt(encryptedFile, _validPasswordBytes, outputFile); 153 | 154 | // Assert 155 | result.IsSuccess.ShouldBeTrue(); 156 | outputFile.Exists.ShouldBeTrue(); 157 | 158 | var decryptedContent = File.ReadAllText(outputFile.FullName); 159 | decryptedContent.ShouldContain("line1: this is a plaintext file"); 160 | } 161 | finally 162 | { 163 | // Cleanup 164 | if (outputFile.Exists) 165 | outputFile.Delete(); 166 | } 167 | } 168 | 169 | [Test] 170 | public void Decrypt_WithInvalidPassword_ReturnsErrorResult() 171 | { 172 | // Arrange 173 | var encryptedFile = new FileInfo(Path.Combine("TestFiles", "encrypted.jpg")); 174 | var outputFile = new FileInfo(Path.Combine(Path.GetTempPath(), Path.GetTempFileName())); 175 | 176 | try 177 | { 178 | // Act 179 | var result = OpenSsl.Decrypt(encryptedFile, _invalidPasswordBytes, outputFile); 180 | 181 | // Assert 182 | result.IsError.ShouldBeTrue(); 183 | outputFile.Exists.ShouldBeFalse(); // Should be deleted on error 184 | } 185 | finally 186 | { 187 | // Cleanup 188 | if (outputFile.Exists) 189 | outputFile.Delete(); 190 | } 191 | } 192 | 193 | [Test] 194 | public void DeriveKeyAndIV_WithValidInputs_ReturnsCorrectKeySizes() 195 | { 196 | // Arrange 197 | var password = _validPasswordBytes; 198 | var salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }; // 8 bytes salt 199 | 200 | // Access private method using reflection 201 | var methodInfo = typeof(OpenSsl).GetMethod("DeriveKeyAndIV", 202 | BindingFlags.NonPublic | BindingFlags.Static); 203 | 204 | // Act 205 | var result = methodInfo!.Invoke(null, [password, salt]); 206 | 207 | // Assert 208 | result.ShouldBeOfType>(); 209 | var (key, iv) = ((byte[], byte[]))result; 210 | 211 | key.ShouldNotBeNull(); 212 | iv.ShouldNotBeNull(); 213 | key.Length.ShouldBe(32); // KEY_SIZE 214 | iv.Length.ShouldBe(16); // IV_SIZE 215 | } 216 | 217 | [Test] 218 | public void GetSalt_WithValidEncryptedFile_Returns8BytesSalt() 219 | { 220 | // Arrange 221 | var encryptedFile = new FileInfo(Path.Combine("TestFiles", "encrypted.txt")); 222 | 223 | // Access private method using reflection 224 | var methodInfo = typeof(OpenSsl).GetMethod("GetSalt", 225 | BindingFlags.NonPublic | BindingFlags.Static); 226 | 227 | // Act 228 | var result = methodInfo!.Invoke(null, [encryptedFile]); 229 | 230 | // Assert 231 | result.ShouldBeOfType(); 232 | var saltBytes = (byte[])result; 233 | saltBytes.Length.ShouldBe(8); // SALT_SIZE 234 | } 235 | 236 | [Test] 237 | public void CreateAes_WithKeyAndIv_CreatesCorrectAesInstance() 238 | { 239 | // Arrange 240 | var key = new byte[32]; // 32 bytes key 241 | var iv = new byte[16]; // 16 bytes IV 242 | 243 | // Access private method using reflection 244 | var methodInfo = typeof(OpenSsl).GetMethod("CreateAes", 245 | BindingFlags.NonPublic | BindingFlags.Static); 246 | 247 | // Act 248 | var result = methodInfo!.Invoke(null, [key, iv]); 249 | 250 | // Assert 251 | var aes = result as Aes; 252 | 253 | aes.ShouldNotBeNull(); 254 | aes.Mode.ShouldBe(CipherMode.CBC); 255 | aes.KeySize.ShouldBe(256); 256 | aes.BlockSize.ShouldBe(128); 257 | aes.Padding.ShouldBe(PaddingMode.PKCS7); 258 | } 259 | 260 | [Test] 261 | public void Encrypt_WithValidTextFile_CreatesEncryptedFile() 262 | { 263 | // Arrange 264 | var sourceFile = new FileInfo(Path.Combine("TestFiles", "plaintext.txt")); 265 | var outputFile = new FileInfo(Path.Combine(Path.GetTempPath(), "encrypted.txt")); 266 | 267 | if (!Directory.Exists("TestFiles")) 268 | Directory.CreateDirectory("TestFiles"); 269 | 270 | File.WriteAllText(sourceFile.FullName, "Test content\nSecond line"); 271 | 272 | try 273 | { 274 | // Act 275 | var result = OpenSsl.Encrypt(sourceFile, _validPasswordBytes, outputFile); 276 | 277 | // Assert 278 | result.IsSuccess.ShouldBeTrue(); 279 | outputFile.Exists.ShouldBeTrue(); 280 | outputFile.Length.ShouldBeGreaterThan(16); // At least header + salt 281 | 282 | var isEncrypted = OpenSsl.IsOpenSslEncrypted(outputFile); 283 | isEncrypted.Data.ShouldBeTrue(); 284 | } 285 | finally 286 | { 287 | // Cleanup 288 | if (outputFile.Exists) outputFile.Delete(); 289 | if (sourceFile.Exists) sourceFile.Delete(); 290 | } 291 | } 292 | 293 | [Test] 294 | public void Encrypt_WithBinaryFile_CreatesEncryptedFile() 295 | { 296 | // Arrange 297 | var sourceFile = new FileInfo(Path.Combine("TestFiles", "sample.bin")); 298 | var outputFile = new FileInfo(Path.Combine(Path.GetTempPath(), "encrypted.bin")); 299 | 300 | if (!Directory.Exists("TestFiles")) 301 | Directory.CreateDirectory("TestFiles"); 302 | 303 | File.WriteAllBytes(sourceFile.FullName, [0x00, 0x01, 0x02, 0x03, 0x04]); 304 | 305 | try 306 | { 307 | // Act 308 | var result = OpenSsl.Encrypt(sourceFile, _validPasswordBytes, outputFile); 309 | 310 | // Assert 311 | result.IsSuccess.ShouldBeTrue(); 312 | outputFile.Exists.ShouldBeTrue(); 313 | 314 | var isEncrypted = OpenSsl.IsOpenSslEncrypted(outputFile); 315 | isEncrypted.Data.ShouldBeTrue(); 316 | } 317 | finally 318 | { 319 | // Cleanup 320 | if (outputFile.Exists) outputFile.Delete(); 321 | if (sourceFile.Exists) sourceFile.Delete(); 322 | } 323 | } 324 | 325 | [Test] 326 | public void Encrypt_WithInvalidOutputPath_ReturnsErrorResult() 327 | { 328 | // Arrange 329 | var sourceFile = new FileInfo(Path.Combine("TestFiles", "plaintext.txt")); 330 | var outputFile = new FileInfo(Path.Combine("NonExistentFolder", "encrypted.txt")); 331 | 332 | File.WriteAllText(sourceFile.FullName, "Test content"); 333 | 334 | try 335 | { 336 | // Act 337 | var result = OpenSsl.Encrypt(sourceFile, _validPasswordBytes, outputFile); 338 | 339 | // Assert 340 | result.IsError.ShouldBeTrue(); 341 | outputFile.Exists.ShouldBeFalse(); 342 | } 343 | finally 344 | { 345 | // Cleanup 346 | if (sourceFile.Exists) sourceFile.Delete(); 347 | } 348 | } 349 | 350 | [Test] 351 | public void Encrypt_WithEmptyFile_CreatesValidEncryptedFile() 352 | { 353 | // Arrange 354 | var sourceFile = new FileInfo(Path.Combine("TestFiles", "empty.txt")); 355 | var outputFile = new FileInfo(Path.Combine(Path.GetTempPath(), "encrypted-empty.txt")); 356 | 357 | File.WriteAllText(sourceFile.FullName, ""); 358 | 359 | try 360 | { 361 | // Act 362 | var result = OpenSsl.Encrypt(sourceFile, _validPasswordBytes, outputFile); 363 | 364 | // Assert 365 | result.IsSuccess.ShouldBeTrue(); 366 | outputFile.Exists.ShouldBeTrue(); 367 | 368 | var isEncrypted = OpenSsl.IsOpenSslEncrypted(outputFile); 369 | isEncrypted.Data.ShouldBeTrue(); 370 | } 371 | finally 372 | { 373 | // Cleanup 374 | if (outputFile.Exists) outputFile.Delete(); 375 | if (sourceFile.Exists) sourceFile.Delete(); 376 | } 377 | } 378 | 379 | [Test] 380 | public void Encrypt_WithNonExistentFile_ReturnsErrorResult() 381 | { 382 | // Arrange 383 | var sourceFile = new FileInfo(Path.Combine(Path.GetTempPath(), "nonexistent.txt")); 384 | var outputFile = new FileInfo(Path.Combine(Path.GetTempPath(), "encrypted.txt")); 385 | 386 | // Act 387 | var result = OpenSsl.Encrypt(sourceFile, _validPasswordBytes, outputFile); 388 | 389 | // Assert 390 | result.IsError.ShouldBeTrue(); 391 | outputFile.Exists.ShouldBeFalse(); 392 | } 393 | 394 | [Test] 395 | public void IsOpenSslEncrypted_WithValidEncryptedFile_ReturnsTrue() 396 | { 397 | // Arrange 398 | var encryptedFile = new FileInfo(Path.Combine("TestFiles", "encrypted.txt")); 399 | 400 | // Act 401 | var result = OpenSsl.IsOpenSslEncrypted(encryptedFile); 402 | 403 | // Assert 404 | result.IsSuccess.ShouldBeTrue(); 405 | result.Data.ShouldBeTrue(); 406 | } 407 | 408 | [Test] 409 | public void EncryptAndDecrypt_WithTextFile_PreservesContent() 410 | { 411 | // Arrange 412 | var originalContent = "Test content\nWith multiple lines\nAnd some special chars: !@#$%"; 413 | var sourceFile = new FileInfo(Path.Combine(Path.GetTempPath(), "original.txt")); 414 | var encryptedFile = new FileInfo(Path.Combine(Path.GetTempPath(), "encrypted.txt")); 415 | var decryptedFile = new FileInfo(Path.Combine(Path.GetTempPath(), "decrypted.txt")); 416 | 417 | File.WriteAllText(sourceFile.FullName, originalContent); 418 | 419 | try 420 | { 421 | // Act 422 | var encryptResult = OpenSsl.Encrypt(sourceFile, _validPasswordBytes, encryptedFile); 423 | var decryptResult = OpenSsl.Decrypt(encryptedFile, _validPasswordBytes, decryptedFile); 424 | 425 | // Assert 426 | encryptResult.IsSuccess.ShouldBeTrue(); 427 | decryptResult.IsSuccess.ShouldBeTrue(); 428 | 429 | var decryptedContent = File.ReadAllText(decryptedFile.FullName); 430 | decryptedContent.ShouldBe(originalContent); 431 | } 432 | finally 433 | { 434 | // Cleanup 435 | if (sourceFile.Exists) sourceFile.Delete(); 436 | if (encryptedFile.Exists) encryptedFile.Delete(); 437 | if (decryptedFile.Exists) decryptedFile.Delete(); 438 | } 439 | } 440 | 441 | [Test] 442 | public void EncryptAndDecrypt_WithLargeFile_WorksCorrectly() 443 | { 444 | // Arrange 445 | var sourceFile = new FileInfo(Path.Combine(Path.GetTempPath(), "large.dat")); 446 | var encryptedFile = new FileInfo(Path.Combine(Path.GetTempPath(), "large.encrypted")); 447 | var decryptedFile = new FileInfo(Path.Combine(Path.GetTempPath(), "large.decrypted")); 448 | 449 | // Create 1MB file 450 | using (var fs = sourceFile.Create()) 451 | { 452 | fs.SetLength(1024 * 1024); 453 | } 454 | 455 | try 456 | { 457 | // Act 458 | var encryptResult = OpenSsl.Encrypt(sourceFile, _validPasswordBytes, encryptedFile); 459 | var decryptResult = OpenSsl.Decrypt(encryptedFile, _validPasswordBytes, decryptedFile); 460 | 461 | // Assert 462 | encryptResult.IsSuccess.ShouldBeTrue(); 463 | decryptResult.IsSuccess.ShouldBeTrue(); 464 | 465 | sourceFile.Length.ShouldBe(decryptedFile.Length); 466 | } 467 | finally 468 | { 469 | // Cleanup 470 | if (sourceFile.Exists) sourceFile.Delete(); 471 | if (encryptedFile.Exists) encryptedFile.Delete(); 472 | if (decryptedFile.Exists) decryptedFile.Delete(); 473 | } 474 | } 475 | 476 | [Test] 477 | public void EncryptAndDecrypt_WithDifferentPasswordLengths_WorksCorrectly() 478 | { 479 | // Arrange 480 | var content = "Test content"; 481 | var sourceFile = new FileInfo(Path.Combine(Path.GetTempPath(), "original.txt")); 482 | var encryptedFile = new FileInfo(Path.Combine(Path.GetTempPath(), "encrypted.txt")); 483 | var decryptedFile = new FileInfo(Path.Combine(Path.GetTempPath(), "decrypted.txt")); 484 | 485 | File.WriteAllText(sourceFile.FullName, content); 486 | var shortPassword = "short"u8.ToArray(); 487 | var longPassword = "ThisIsAVeryLongPasswordThatShouldStillWork!!!"u8.ToArray(); 488 | 489 | try 490 | { 491 | // Act & Assert - Short password 492 | var encryptResult1 = OpenSsl.Encrypt(sourceFile, shortPassword, encryptedFile); 493 | var decryptResult1 = OpenSsl.Decrypt(encryptedFile, shortPassword, decryptedFile); 494 | 495 | encryptResult1.IsSuccess.ShouldBeTrue(); 496 | decryptResult1.IsSuccess.ShouldBeTrue(); 497 | File.ReadAllText(decryptedFile.FullName).ShouldBe(content); 498 | 499 | // Cleanup between tests 500 | encryptedFile.Delete(); 501 | decryptedFile.Delete(); 502 | 503 | // Act & Assert - Long password 504 | var encryptResult2 = OpenSsl.Encrypt(sourceFile, longPassword, encryptedFile); 505 | var decryptResult2 = OpenSsl.Decrypt(encryptedFile, longPassword, decryptedFile); 506 | 507 | encryptResult2.IsSuccess.ShouldBeTrue(); 508 | decryptResult2.IsSuccess.ShouldBeTrue(); 509 | File.ReadAllText(decryptedFile.FullName).ShouldBe(content); 510 | } 511 | finally 512 | { 513 | // Cleanup 514 | if (sourceFile.Exists) sourceFile.Delete(); 515 | if (encryptedFile.Exists) encryptedFile.Delete(); 516 | if (decryptedFile.Exists) decryptedFile.Delete(); 517 | } 518 | } 519 | } 520 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The GNU General Public License is a free, copyleft license for 12 | software and other kinds of works. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | the GNU General Public License is intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. We, the Free Software Foundation, use the 19 | GNU General Public License for most of our software; it applies also to 20 | any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not 24 | price. Our General Public Licenses are designed to make sure that you 25 | have the freedom to distribute copies of free software (and charge for 26 | them if you wish), that you receive source code or can get it if you 27 | want it, that you can change the software or use pieces of it in new 28 | free programs, and that you know you can do these things. 29 | 30 | To protect your rights, we need to prevent others from denying you 31 | these rights or asking you to surrender the rights. Therefore, you have 32 | certain responsibilities if you distribute copies of the software, or if 33 | you modify it: responsibilities to respect the freedom of others. 34 | 35 | For example, if you distribute copies of such a program, whether 36 | gratis or for a fee, you must pass on to the recipients the same 37 | freedoms that you received. You must make sure that they, too, receive 38 | or can get the source code. And you must show them these terms so they 39 | know their rights. 40 | 41 | Developers that use the GNU GPL protect your rights with two steps: 42 | (1) assert copyright on the software, and (2) offer you this License 43 | giving you legal permission to copy, distribute and/or modify it. 44 | 45 | For the developers' and authors' protection, the GPL clearly explains 46 | that there is no warranty for this free software. For both users' and 47 | authors' sake, the GPL requires that modified versions be marked as 48 | changed, so that their problems will not be attributed erroneously to 49 | authors of previous versions. 50 | 51 | Some devices are designed to deny users access to install or run 52 | modified versions of the software inside them, although the manufacturer 53 | can do so. This is fundamentally incompatible with the aim of 54 | protecting users' freedom to change the software. The systematic 55 | pattern of such abuse occurs in the area of products for individuals to 56 | use, which is precisely where it is most unacceptable. Therefore, we 57 | have designed this version of the GPL to prohibit the practice for those 58 | products. If such problems arise substantially in other domains, we 59 | stand ready to extend this provision to those domains in future versions 60 | of the GPL, as needed to protect the freedom of users. 61 | 62 | Finally, every program is threatened constantly by software patents. 63 | States should not allow patents to restrict development and use of 64 | software on general-purpose computers, but in those that do, we wish to 65 | avoid the special danger that patents applied to a free program could 66 | make it effectively proprietary. To prevent this, the GPL assures that 67 | patents cannot be used to render the program non-free. 68 | 69 | The precise terms and conditions for copying, distribution and 70 | modification follow. 71 | 72 | TERMS AND CONDITIONS 73 | 74 | 0. Definitions. 75 | 76 | "This License" refers to version 3 of the GNU General Public License. 77 | 78 | "Copyright" also means copyright-like laws that apply to other kinds of 79 | works, such as semiconductor masks. 80 | 81 | "The Program" refers to any copyrightable work licensed under this 82 | License. Each licensee is addressed as "you". "Licensees" and 83 | "recipients" may be individuals or organizations. 84 | 85 | To "modify" a work means to copy from or adapt all or part of the work 86 | in a fashion requiring copyright permission, other than the making of an 87 | exact copy. The resulting work is called a "modified version" of the 88 | earlier work or a work "based on" the earlier work. 89 | 90 | A "covered work" means either the unmodified Program or a work based 91 | on the Program. 92 | 93 | To "propagate" a work means to do anything with it that, without 94 | permission, would make you directly or secondarily liable for 95 | infringement under applicable copyright law, except executing it on a 96 | computer or modifying a private copy. Propagation includes copying, 97 | distribution (with or without modification), making available to the 98 | public, and in some countries other activities as well. 99 | 100 | To "convey" a work means any kind of propagation that enables other 101 | parties to make or receive copies. Mere interaction with a user through 102 | a computer network, with no transfer of a copy, is not conveying. 103 | 104 | An interactive user interface displays "Appropriate Legal Notices" 105 | to the extent that it includes a convenient and prominently visible 106 | feature that (1) displays an appropriate copyright notice, and (2) 107 | tells the user that there is no warranty for the work (except to the 108 | extent that warranties are provided), that licensees may convey the 109 | work under this License, and how to view a copy of this License. If 110 | the interface presents a list of user commands or options, such as a 111 | menu, a prominent item in the list meets this criterion. 112 | 113 | 1. Source Code. 114 | 115 | The "source code" for a work means the preferred form of the work 116 | for making modifications to it. "Object code" means any non-source 117 | form of a work. 118 | 119 | A "Standard Interface" means an interface that either is an official 120 | standard defined by a recognized standards body, or, in the case of 121 | interfaces specified for a particular programming language, one that 122 | is widely used among developers working in that language. 123 | 124 | The "System Libraries" of an executable work include anything, other 125 | than the work as a whole, that (a) is included in the normal form of 126 | packaging a Major Component, but which is not part of that Major 127 | Component, and (b) serves only to enable use of the work with that 128 | Major Component, or to implement a Standard Interface for which an 129 | implementation is available to the public in source code form. A 130 | "Major Component", in this context, means a major essential component 131 | (kernel, window system, and so on) of the specific operating system 132 | (if any) on which the executable work runs, or a compiler used to 133 | produce the work, or an object code interpreter used to run it. 134 | 135 | The "Corresponding Source" for a work in object code form means all 136 | the source code needed to generate, install, and (for an executable 137 | work) run the object code and to modify the work, including scripts to 138 | control those activities. However, it does not include the work's 139 | System Libraries, or general-purpose tools or generally available free 140 | programs which are used unmodified in performing those activities but 141 | which are not part of the work. For example, Corresponding Source 142 | includes interface definition files associated with source files for 143 | the work, and the source code for shared libraries and dynamically 144 | linked subprograms that the work is specifically designed to require, 145 | such as by intimate data communication or control flow between those 146 | subprograms and other parts of the work. 147 | 148 | The Corresponding Source need not include anything that users 149 | can regenerate automatically from other parts of the Corresponding 150 | Source. 151 | 152 | The Corresponding Source for a work in source code form is that 153 | same work. 154 | 155 | 2. Basic Permissions. 156 | 157 | All rights granted under this License are granted for the term of 158 | copyright on the Program, and are irrevocable provided the stated 159 | conditions are met. This License explicitly affirms your unlimited 160 | permission to run the unmodified Program. The output from running a 161 | covered work is covered by this License only if the output, given its 162 | content, constitutes a covered work. This License acknowledges your 163 | rights of fair use or other equivalent, as provided by copyright law. 164 | 165 | You may make, run and propagate covered works that you do not 166 | convey, without conditions so long as your license otherwise remains 167 | in force. You may convey covered works to others for the sole purpose 168 | of having them make modifications exclusively for you, or provide you 169 | with facilities for running those works, provided that you comply with 170 | the terms of this License in conveying all material for which you do 171 | not control copyright. Those thus making or running the covered works 172 | for you must do so exclusively on your behalf, under your direction 173 | and control, on terms that prohibit them from making any copies of 174 | your copyrighted material outside their relationship with you. 175 | 176 | Conveying under any other circumstances is permitted solely under 177 | the conditions stated below. Sublicensing is not allowed; section 10 178 | makes it unnecessary. 179 | 180 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 181 | 182 | No covered work shall be deemed part of an effective technological 183 | measure under any applicable law fulfilling obligations under article 184 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 185 | similar laws prohibiting or restricting circumvention of such 186 | measures. 187 | 188 | When you convey a covered work, you waive any legal power to forbid 189 | circumvention of technological measures to the extent such circumvention 190 | is effected by exercising rights under this License with respect to 191 | the covered work, and you disclaim any intention to limit operation or 192 | modification of the work as a means of enforcing, against the work's 193 | users, your or third parties' legal rights to forbid circumvention of 194 | technological measures. 195 | 196 | 4. Conveying Verbatim Copies. 197 | 198 | You may convey verbatim copies of the Program's source code as you 199 | receive it, in any medium, provided that you conspicuously and 200 | appropriately publish on each copy an appropriate copyright notice; 201 | keep intact all notices stating that this License and any 202 | non-permissive terms added in accord with section 7 apply to the code; 203 | keep intact all notices of the absence of any warranty; and give all 204 | recipients a copy of this License along with the Program. 205 | 206 | You may charge any price or no price for each copy that you convey, 207 | and you may offer support or warranty protection for a fee. 208 | 209 | 5. Conveying Modified Source Versions. 210 | 211 | You may convey a work based on the Program, or the modifications to 212 | produce it from the Program, in the form of source code under the 213 | terms of section 4, provided that you also meet all of these conditions: 214 | 215 | a) The work must carry prominent notices stating that you modified 216 | it, and giving a relevant date. 217 | 218 | b) The work must carry prominent notices stating that it is 219 | released under this License and any conditions added under section 220 | 7. This requirement modifies the requirement in section 4 to 221 | "keep intact all notices". 222 | 223 | c) You must license the entire work, as a whole, under this 224 | License to anyone who comes into possession of a copy. This 225 | License will therefore apply, along with any applicable section 7 226 | additional terms, to the whole of the work, and all its parts, 227 | regardless of how they are packaged. This License gives no 228 | permission to license the work in any other way, but it does not 229 | invalidate such permission if you have separately received it. 230 | 231 | d) If the work has interactive user interfaces, each must display 232 | Appropriate Legal Notices; however, if the Program has interactive 233 | interfaces that do not display Appropriate Legal Notices, your 234 | work need not make them do so. 235 | 236 | A compilation of a covered work with other separate and independent 237 | works, which are not by their nature extensions of the covered work, 238 | and which are not combined with it such as to form a larger program, 239 | in or on a volume of a storage or distribution medium, is called an 240 | "aggregate" if the compilation and its resulting copyright are not 241 | used to limit the access or legal rights of the compilation's users 242 | beyond what the individual works permit. Inclusion of a covered work 243 | in an aggregate does not cause this License to apply to the other 244 | parts of the aggregate. 245 | 246 | 6. Conveying Non-Source Forms. 247 | 248 | You may convey a covered work in object code form under the terms 249 | of sections 4 and 5, provided that you also convey the 250 | machine-readable Corresponding Source under the terms of this License, 251 | in one of these ways: 252 | 253 | a) Convey the object code in, or embodied in, a physical product 254 | (including a physical distribution medium), accompanied by the 255 | Corresponding Source fixed on a durable physical medium 256 | customarily used for software interchange. 257 | 258 | b) Convey the object code in, or embodied in, a physical product 259 | (including a physical distribution medium), accompanied by a 260 | written offer, valid for at least three years and valid for as 261 | long as you offer spare parts or customer support for that product 262 | model, to give anyone who possesses the object code either (1) a 263 | copy of the Corresponding Source for all the software in the 264 | product that is covered by this License, on a durable physical 265 | medium customarily used for software interchange, for a price no 266 | more than your reasonable cost of physically performing this 267 | conveying of source, or (2) access to copy the 268 | Corresponding Source from a network server at no charge. 269 | 270 | c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | 276 | d) Convey the object code by offering access from a designated 277 | place (gratis or for a charge), and offer equivalent access to the 278 | Corresponding Source in the same way through the same place at no 279 | further charge. You need not require recipients to copy the 280 | Corresponding Source along with the object code. If the place to 281 | copy the object code is a network server, the Corresponding Source 282 | may be on a different server (operated by you or a third party) 283 | that supports equivalent copying facilities, provided you maintain 284 | clear directions next to the object code saying where to find the 285 | Corresponding Source. Regardless of what server hosts the 286 | Corresponding Source, you remain obligated to ensure that it is 287 | available for as long as needed to satisfy these requirements. 288 | 289 | e) Convey the object code using peer-to-peer transmission, provided 290 | you inform other peers where the object code and Corresponding 291 | Source of the work are being offered to the general public at no 292 | charge under subsection 6d. 293 | 294 | A separable portion of the object code, whose source code is excluded 295 | from the Corresponding Source as a System Library, need not be 296 | included in conveying the object code work. 297 | 298 | A "User Product" is either (1) a "consumer product", which means any 299 | tangible personal property which is normally used for personal, family, 300 | or household purposes, or (2) anything designed or sold for incorporation 301 | into a dwelling. In determining whether a product is a consumer product, 302 | doubtful cases shall be resolved in favor of coverage. For a particular 303 | product received by a particular user, "normally used" refers to a 304 | typical or common use of that class of product, regardless of the status 305 | of the particular user or of the way in which the particular user 306 | actually uses, or expects or is expected to use, the product. A product 307 | is a consumer product regardless of whether the product has substantial 308 | commercial, industrial or non-consumer uses, unless such uses represent 309 | the only significant mode of use of the product. 310 | 311 | "Installation Information" for a User Product means any methods, 312 | procedures, authorization keys, or other information required to install 313 | and execute modified versions of a covered work in that User Product from 314 | a modified version of its Corresponding Source. The information must 315 | suffice to ensure that the continued functioning of the modified object 316 | code is in no case prevented or interfered with solely because 317 | modification has been made. 318 | 319 | If you convey an object code work under this section in, or with, or 320 | specifically for use in, a User Product, and the conveying occurs as 321 | part of a transaction in which the right of possession and use of the 322 | User Product is transferred to the recipient in perpetuity or for a 323 | fixed term (regardless of how the transaction is characterized), the 324 | Corresponding Source conveyed under this section must be accompanied 325 | by the Installation Information. But this requirement does not apply 326 | if neither you nor any third party retains the ability to install 327 | modified object code on the User Product (for example, the work has 328 | been installed in ROM). 329 | 330 | The requirement to provide Installation Information does not include a 331 | requirement to continue to provide support service, warranty, or updates 332 | for a work that has been modified or installed by the recipient, or for 333 | the User Product in which it has been modified or installed. Access to a 334 | network may be denied when the modification itself materially and 335 | adversely affects the operation of the network or violates the rules and 336 | protocols for communication across the network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders of 364 | that material) supplement the terms of this License with terms: 365 | 366 | a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | 369 | b) Requiring preservation of specified reasonable legal notices or 370 | author attributions in that material or in the Appropriate Legal 371 | Notices displayed by works containing it; or 372 | 373 | c) Prohibiting misrepresentation of the origin of that material, or 374 | requiring that modified versions of such material be marked in 375 | reasonable ways as different from the original version; or 376 | 377 | d) Limiting the use for publicity purposes of names of licensors or 378 | authors of the material; or 379 | 380 | e) Declining to grant rights under trademark law for use of some 381 | trade names, trademarks, or service marks; or 382 | 383 | f) Requiring indemnification of licensors and authors of that 384 | material by anyone who conveys the material (or modified versions of 385 | it) with contractual assumptions of liability to the recipient, for 386 | any liability that these contractual assumptions directly impose on 387 | those licensors and authors. 388 | 389 | All other non-permissive additional terms are considered "further 390 | restrictions" within the meaning of section 10. If the Program as you 391 | received it, or any part of it, contains a notice stating that it is 392 | governed by this License along with a term that is a further 393 | restriction, you may remove that term. If a license document contains 394 | a further restriction but permits relicensing or conveying under this 395 | License, you may add to a covered work material governed by the terms 396 | of that license document, provided that the further restriction does 397 | not survive such relicensing or conveying. 398 | 399 | If you add terms to a covered work in accord with this section, you 400 | must place, in the relevant source files, a statement of the 401 | additional terms that apply to those files, or a notice indicating 402 | where to find the applicable terms. 403 | 404 | Additional terms, permissive or non-permissive, may be stated in the 405 | form of a separately written license, or stated as exceptions; 406 | the above requirements apply either way. 407 | 408 | 8. Termination. 409 | 410 | You may not propagate or modify a covered work except as expressly 411 | provided under this License. Any attempt otherwise to propagate or 412 | modify it is void, and will automatically terminate your rights under 413 | this License (including any patent licenses granted under the third 414 | paragraph of section 11). 415 | 416 | However, if you cease all violation of this License, then your 417 | license from a particular copyright holder is reinstated (a) 418 | provisionally, unless and until the copyright holder explicitly and 419 | finally terminates your license, and (b) permanently, if the copyright 420 | holder fails to notify you of the violation by some reasonable means 421 | prior to 60 days after the cessation. 422 | 423 | Moreover, your license from a particular copyright holder is 424 | reinstated permanently if the copyright holder notifies you of the 425 | violation by some reasonable means, this is the first time you have 426 | received notice of violation of this License (for any work) from that 427 | copyright holder, and you cure the violation prior to 30 days after 428 | your receipt of the notice. 429 | 430 | Termination of your rights under this section does not terminate the 431 | licenses of parties who have received copies or rights from you under 432 | this License. If your rights have been terminated and not permanently 433 | reinstated, you do not qualify to receive new licenses for the same 434 | material under section 10. 435 | 436 | 9. Acceptance Not Required for Having Copies. 437 | 438 | You are not required to accept this License in order to receive or 439 | run a copy of the Program. Ancillary propagation of a covered work 440 | occurring solely as a consequence of using peer-to-peer transmission 441 | to receive a copy likewise does not require acceptance. However, 442 | nothing other than this License grants you permission to propagate or 443 | modify any covered work. These actions infringe copyright if you do 444 | not accept this License. Therefore, by modifying or propagating a 445 | covered work, you indicate your acceptance of this License to do so. 446 | 447 | 10. Automatic Licensing of Downstream Recipients. 448 | 449 | Each time you convey a covered work, the recipient automatically 450 | receives a license from the original licensors, to run, modify and 451 | propagate that work, subject to this License. You are not responsible 452 | for enforcing compliance by third parties with this License. 453 | 454 | An "entity transaction" is a transaction transferring control of an 455 | organization, or substantially all assets of one, or subdividing an 456 | organization, or merging organizations. If propagation of a covered 457 | work results from an entity transaction, each party to that 458 | transaction who receives a copy of the work also receives whatever 459 | licenses to the work the party's predecessor in interest had or could 460 | give under the previous paragraph, plus a right to possession of the 461 | Corresponding Source of the work from the predecessor in interest, if 462 | the predecessor has it or can get it with reasonable efforts. 463 | 464 | You may not impose any further restrictions on the exercise of the 465 | rights granted or affirmed under this License. For example, you may 466 | not impose a license fee, royalty, or other charge for exercise of 467 | rights granted under this License, and you may not initiate litigation 468 | (including a cross-claim or counterclaim in a lawsuit) alleging that 469 | any patent claim is infringed by making, using, selling, offering for 470 | sale, or importing the Program or any portion of it. 471 | 472 | 11. Patents. 473 | 474 | A "contributor" is a copyright holder who authorizes use under this 475 | License of the Program or a work on which the Program is based. The 476 | work thus licensed is called the contributor's "contributor version". 477 | 478 | A contributor's "essential patent claims" are all patent claims 479 | owned or controlled by the contributor, whether already acquired or 480 | hereafter acquired, that would be infringed by some manner, permitted 481 | by this License, of making, using, or selling its contributor version, 482 | but do not include claims that would be infringed only as a 483 | consequence of further modification of the contributor version. For 484 | purposes of this definition, "control" includes the right to grant 485 | patent sublicenses in a manner consistent with the requirements of 486 | this License. 487 | 488 | Each contributor grants you a non-exclusive, worldwide, royalty-free 489 | patent license under the contributor's essential patent claims, to 490 | make, use, sell, offer for sale, import and otherwise run, modify and 491 | propagate the contents of its contributor version. 492 | 493 | In the following three paragraphs, a "patent license" is any express 494 | agreement or commitment, however denominated, not to enforce a patent 495 | (such as an express permission to practice a patent or covenant not to 496 | sue for patent infringement). To "grant" such a patent license to a 497 | party means to make such an agreement or commitment not to enforce a 498 | patent against the party. 499 | 500 | If you convey a covered work, knowingly relying on a patent license, 501 | and the Corresponding Source of the work is not available for anyone 502 | to copy, free of charge and under the terms of this License, through a 503 | publicly available network server or other readily accessible means, 504 | then you must either (1) cause the Corresponding Source to be so 505 | available, or (2) arrange to deprive yourself of the benefit of the 506 | patent license for this particular work, or (3) arrange, in a manner 507 | consistent with the requirements of this License, to extend the patent 508 | license to downstream recipients. "Knowingly relying" means you have 509 | actual knowledge that, but for the patent license, your conveying the 510 | covered work in a country, or your recipient's use of the covered work 511 | in a country, would infringe one or more identifiable patents in that 512 | country that you have reason to believe are valid. 513 | 514 | If, pursuant to or in connection with a single transaction or 515 | arrangement, you convey, or propagate by procuring conveyance of, a 516 | covered work, and grant a patent license to some of the parties 517 | receiving the covered work authorizing them to use, propagate, modify 518 | or convey a specific copy of the covered work, then the patent license 519 | you grant is automatically extended to all recipients of the covered 520 | work and works based on it. 521 | 522 | A patent license is "discriminatory" if it does not include within 523 | the scope of its coverage, prohibits the exercise of, or is 524 | conditioned on the non-exercise of one or more of the rights that are 525 | specifically granted under this License. You may not convey a covered 526 | work if you are a party to an arrangement with a third party that is 527 | in the business of distributing software, under which you make payment 528 | to the third party based on the extent of your activity of conveying 529 | the work, and under which the third party grants, to any of the 530 | parties who would receive the covered work from you, a discriminatory 531 | patent license (a) in connection with copies of the covered work 532 | conveyed by you (or copies made from those copies), or (b) primarily 533 | for and in connection with specific products or compilations that 534 | contain the covered work, unless you entered into that arrangement, 535 | or that patent license was granted, prior to 28 March 2007. 536 | 537 | Nothing in this License shall be construed as excluding or limiting 538 | any implied license or other defenses to infringement that may 539 | otherwise be available to you under applicable patent law. 540 | 541 | 12. No Surrender of Others' Freedom. 542 | 543 | If conditions are imposed on you (whether by court order, agreement or 544 | otherwise) that contradict the conditions of this License, they do not 545 | excuse you from the conditions of this License. If you cannot convey a 546 | covered work so as to satisfy simultaneously your obligations under this 547 | License and any other pertinent obligations, then as a consequence you may 548 | not convey it at all. For example, if you agree to terms that obligate you 549 | to collect a royalty for further conveying from those to whom you convey 550 | the Program, the only way you could satisfy both those terms and this 551 | License would be to refrain entirely from conveying the Program. 552 | 553 | 13. Use with the GNU Affero General Public License. 554 | 555 | Notwithstanding any other provision of this License, you have 556 | permission to link or combine any covered work with a work licensed 557 | under version 3 of the GNU Affero General Public License into a single 558 | combined work, and to convey the resulting work. The terms of this 559 | License will continue to apply to the part which is the covered work, 560 | but the special requirements of the GNU Affero General Public License, 561 | section 13, concerning interaction through a network will apply to the 562 | combination as such. 563 | 564 | 14. Revised Versions of this License. 565 | 566 | The Free Software Foundation may publish revised and/or new versions of 567 | the GNU General Public License from time to time. Such new versions will 568 | be similar in spirit to the present version, but may differ in detail to 569 | address new problems or concerns. 570 | 571 | Each version is given a distinguishing version number. If the 572 | Program specifies that a certain numbered version of the GNU General 573 | Public License "or any later version" applies to it, you have the 574 | option of following the terms and conditions either of that numbered 575 | version or of any later version published by the Free Software 576 | Foundation. If the Program does not specify a version number of the 577 | GNU General Public License, you may choose any version ever published 578 | by the Free Software Foundation. 579 | 580 | If the Program specifies that a proxy can decide which future 581 | versions of the GNU General Public License can be used, that proxy's 582 | public statement of acceptance of a version permanently authorizes you 583 | to choose that version for the Program. 584 | 585 | Later license versions may give you additional or different 586 | permissions. However, no additional obligations are imposed on any 587 | author or copyright holder as a result of your choosing to follow a 588 | later version. 589 | 590 | 15. Disclaimer of Warranty. 591 | 592 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 593 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 594 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 595 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 596 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 597 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 598 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 599 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 600 | 601 | 16. Limitation of Liability. 602 | 603 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 604 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 605 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 606 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 607 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 608 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 609 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 610 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 611 | SUCH DAMAGES. 612 | 613 | 17. Interpretation of Sections 15 and 16. 614 | 615 | If the disclaimer of warranty and limitation of liability provided 616 | above cannot be given local legal effect according to their terms, 617 | reviewing courts shall apply local law that most closely approximates 618 | an absolute waiver of all civil liability in connection with the 619 | Program, unless a warranty or assumption of liability accompanies a 620 | copy of the Program in return for a fee. 621 | 622 | END OF TERMS AND CONDITIONS 623 | 624 | How to Apply These Terms to Your New Programs 625 | 626 | If you develop a new program, and you want it to be of the greatest 627 | possible use to the public, the best way to achieve this is to make it 628 | free software which everyone can redistribute and change under these terms. 629 | 630 | To do so, attach the following notices to the program. It is safest 631 | to attach them to the start of each source file to most effectively 632 | state the exclusion of warranty; and each file should have at least 633 | the "copyright" line and a pointer to where the full notice is found. 634 | 635 | 636 | Copyright (C) 637 | 638 | This program is free software: you can redistribute it and/or modify 639 | it under the terms of the GNU General Public License as published by 640 | the Free Software Foundation, either version 3 of the License, or 641 | (at your option) any later version. 642 | 643 | This program is distributed in the hope that it will be useful, 644 | but WITHOUT ANY WARRANTY; without even the implied warranty of 645 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 646 | GNU General Public License for more details. 647 | 648 | You should have received a copy of the GNU General Public License 649 | along with this program. If not, see . 650 | 651 | Also add information on how to contact you by electronic and paper mail. 652 | 653 | If the program does terminal interaction, make it output a short 654 | notice like this when it starts in an interactive mode: 655 | 656 | Copyright (C) 657 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 658 | This is free software, and you are welcome to redistribute it 659 | under certain conditions; type `show c' for details. 660 | 661 | The hypothetical commands `show w' and `show c' should show the appropriate 662 | parts of the General Public License. Of course, your program's commands 663 | might be different; for a GUI interface, you would use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or school, 666 | if any, to sign a "copyright disclaimer" for the program, if necessary. 667 | For more information on this, and how to apply and follow the GNU GPL, see 668 | . 669 | 670 | The GNU General Public License does not permit incorporating your program 671 | into proprietary programs. If your program is a subroutine library, you 672 | may consider it more useful to permit linking proprietary applications with 673 | the library. If this is what you want to do, use the GNU Lesser General 674 | Public License instead of this License. But first, please read 675 | . 676 | --------------------------------------------------------------------------------