diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..0d93a8b --- /dev/null +++ b/.editorconfig @@ -0,0 +1,237 @@ +# Remove the line below if you want to inherit .editorconfig settings from higher directories +root = true + +# C# files +[*.cs] + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_size = 4 +indent_style = space +tab_width = 4 + +# New line preferences +end_of_line = crlf +insert_final_newline = false + +#### .NET Coding Conventions #### + +# Organize usings +dotnet_separate_import_directive_groups = false +dotnet_sort_system_directives_first = false +file_header_template = unset + +# this. and Me. preferences +dotnet_style_qualification_for_event = false +dotnet_style_qualification_for_field = false +dotnet_style_qualification_for_method = false +dotnet_style_qualification_for_property = false + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true +dotnet_style_predefined_type_for_member_access = true + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity +dotnet_style_parentheses_in_other_operators = never_if_unnecessary +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members + +# Expression-level preferences +dotnet_style_coalesce_expression = true +dotnet_style_collection_initializer = true +dotnet_style_explicit_tuple_names = true +dotnet_style_namespace_match_folder = true +dotnet_style_null_propagation = true +dotnet_style_object_initializer = true +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_prefer_auto_properties = true +dotnet_style_prefer_compound_assignment = true +dotnet_style_prefer_conditional_expression_over_assignment = true +dotnet_style_prefer_conditional_expression_over_return = true +dotnet_style_prefer_inferred_anonymous_type_member_names = true +dotnet_style_prefer_inferred_tuple_names = true +dotnet_style_prefer_is_null_check_over_reference_equality_method = true +dotnet_style_prefer_simplified_boolean_expressions = true +dotnet_style_prefer_simplified_interpolation = true + +# Field preferences +dotnet_style_readonly_field = true + +# Parameter preferences +dotnet_code_quality_unused_parameters = all + +# Suppression preferences +dotnet_remove_unnecessary_suppression_exclusions = none + +# New line preferences +dotnet_style_allow_multiple_blank_lines_experimental = true +dotnet_style_allow_statement_immediately_after_block_experimental = true + +#### C# Coding Conventions #### + +# var preferences +csharp_style_var_elsewhere = false +csharp_style_var_for_built_in_types = false +csharp_style_var_when_type_is_apparent = false + +# Expression-bodied members +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent + +# Pattern matching preferences +csharp_style_pattern_matching_over_as_with_null_check = true +csharp_style_pattern_matching_over_is_with_cast_check = true +csharp_style_prefer_extended_property_pattern = true +csharp_style_prefer_not_pattern = true +csharp_style_prefer_pattern_matching = true +csharp_style_prefer_switch_expression = true + +# Null-checking preferences +csharp_style_conditional_delegate_call = true +csharp_style_prefer_parameter_null_checking = true + +# Modifier preferences +csharp_prefer_static_local_function = true +csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async + +# Code-block preferences +csharp_prefer_braces = true:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_style_namespace_declarations = block_scoped:silent +csharp_style_prefer_method_group_conversion = true:silent + +# Expression-level preferences +csharp_prefer_simple_default_expression = true +csharp_style_deconstructed_variable_declaration = true +csharp_style_implicit_object_creation_when_type_is_apparent = true +csharp_style_inlined_variable_declaration = true +csharp_style_prefer_index_operator = true +csharp_style_prefer_local_over_anonymous_function = true +csharp_style_prefer_null_check_over_type_check = true +csharp_style_prefer_range_operator = true +csharp_style_prefer_tuple_swap = true +csharp_style_throw_expression = true +csharp_style_unused_value_assignment_preference = discard_variable +csharp_style_unused_value_expression_statement_preference = discard_variable + +# 'using' directive preferences +csharp_using_directive_placement = outside_namespace:silent + +# New line preferences +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = true +csharp_style_allow_embedded_statements_on_same_line_experimental = true + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = true +csharp_new_line_before_else = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = all +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Wrapping preferences +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +# Symbol specifications + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +[*.{cs,vb}] +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:silent +dotnet_style_object_initializer = true:suggestion +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = crlf +dotnet_style_collection_initializer = true:suggestion + +file_header_template = PdfAutoSigner signs PDF files automatically using a hardware security module. \nCopyright (C) Plant An App\n \nThis program is free software: you can redistribute it and/or modify \nit under the terms of the GNU Affero General Public License as \npublished by the Free Software Foundation, either version 3 of the \nLicense, or (at your option) any later version. \n \nThis program is distributed in the hope that it will be useful, \nbut WITHOUT ANY WARRANTY; without even the implied warranty of \nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \nGNU Affero General Public License for more details. \n \nYou should have received a copy of the GNU Affero General Public License \nalong with this program. If not, see . \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..39d07c7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +################################################################################ +# This .gitignore file was automatically created by Microsoft(R) Visual Studio. +################################################################################ + +**/bin/ +**/obj/ +.vs/ +**/*.csproj.user + +**/hello-signed-pkcs11.pdf +**/hello-signed-cert.pdf +PdfAutoSigner.LocalApi.Installer/Installs/** +PdfAutoSigner.LocalApi.Installer/ComponentsGenerated.wxs +/PdfAutoSigner.LocalApi.Installer/ComponentsGenerated.wxs diff --git a/Directory.Build.Props b/Directory.Build.Props new file mode 100644 index 0000000..dd04406 --- /dev/null +++ b/Directory.Build.Props @@ -0,0 +1,13 @@ + + + 1.0.0.0 + 1.0.0.0 + 1.0.0.0 + PlantAnApp, iText Group + Plant An App, iText Group + (C) Plant An App, (C) iText Group + C:\Work\Projects\PdfAutoSignerAndJava\_code\PlantAnApp.PdfAutoSigner\license.rtf + True + https://github.com/razvanionapp/PlantAnApp.PdfAutoSigner.git + + \ No newline at end of file diff --git a/PdfAutoSigner.Lib.App/CommandLineOptions.cs b/PdfAutoSigner.Lib.App/CommandLineOptions.cs new file mode 100644 index 0000000..89d8600 --- /dev/null +++ b/PdfAutoSigner.Lib.App/CommandLineOptions.cs @@ -0,0 +1,40 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using CommandLine; +using System.Diagnostics.CodeAnalysis; + +namespace PdfAutoSigner.Lib.App +{ + internal class CommandLineOptions + { + [Value(index: 0, Required = true, HelpText = "Input Pdf to sign.")] + [NotNull] + public string? InputFilePath { get; set; } + + [Value(index: 1, Required = true, HelpText = "Output Pdf to sign.")] + [NotNull] + public string? OutputFilePath { get; set; } + + [Value(index: 2, Required = true, HelpText = "Lib path (for PKCS11 mode) or issuer name (for certificates mode).")] + [NotNull] + public string? LibPathOrIssuerName { get; set; } + + [Option(shortName: 'c', Required = false, HelpText = "Use certificates to sign. By default it uses PKCS11.", Default = false)] + public bool UseCertificates { get; set; } + + [Option(shortName: 'p', Required = false, HelpText = "Pin for the usb token. If not provided, it will try to read the 'TokenPin' from the config.", Default = null)] + public string? Pin { get; set; } + + [Option(shortName: 'i', Required = false, HelpText = "Index of the signature to sign the certificate with.", Default = 0UL)] + public ulong SignatureIdx { get; set; } + } +} diff --git a/PdfAutoSigner.Lib.App/ConfigHelper.cs b/PdfAutoSigner.Lib.App/ConfigHelper.cs new file mode 100644 index 0000000..86732fd --- /dev/null +++ b/PdfAutoSigner.Lib.App/ConfigHelper.cs @@ -0,0 +1,32 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using Microsoft.Extensions.Configuration; +namespace PdfAutoSigner.Lib.App +{ + internal class ConfigHelper + { + private const string PinSecretsManagerPath = "TokenPin"; + + public static IConfigurationRoot GetIConfigurationRoot() + { + return new ConfigurationBuilder() + .AddUserSecrets("fb3dd1b7-a8ac-499d-bd09-c2760b970f39") + .Build(); + } + + public static string GetPin() + { + var config = GetIConfigurationRoot(); + return config[PinSecretsManagerPath]; + } + } +} diff --git a/PdfAutoSigner.Lib.App/PdfAutoSigner.Lib.App.csproj b/PdfAutoSigner.Lib.App/PdfAutoSigner.Lib.App.csproj new file mode 100644 index 0000000..505f693 --- /dev/null +++ b/PdfAutoSigner.Lib.App/PdfAutoSigner.Lib.App.csproj @@ -0,0 +1,23 @@ + + + + Exe + net6.0 + enable + enable + fb3dd1b7-a8ac-499d-bd09-c2760b970f39 + AnyCPU + + + + + + + + + + + + + + diff --git a/PdfAutoSigner.Lib.App/Program.cs b/PdfAutoSigner.Lib.App/Program.cs new file mode 100644 index 0000000..92cb6f5 --- /dev/null +++ b/PdfAutoSigner.Lib.App/Program.cs @@ -0,0 +1,96 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using CommandLine; +using iText.Kernel.Geom; +using Microsoft.Extensions.Logging; +using PdfAutoSigner.Lib.App; +using PdfAutoSigner.Lib.Signatures; +using PdfAutoSigner.Lib.Signers; + +using var loggerFactory = LoggerFactory.Create(builder => +{ + builder.AddDebug().AddConsole(); +}); +ILogger logger = loggerFactory.CreateLogger(); +// Read input params from arguments +var result = Parser.Default.ParseArguments(args).WithParsed(RunOptions) + .WithNotParsed(HandleParseErrors) + ; + +void RunOptions(CommandLineOptions options) +{ + var pin = !string.IsNullOrEmpty(options.Pin) ? options.Pin : ConfigHelper.GetPin(); + + if (string.IsNullOrEmpty(pin)) + { + logger.LogCritical("You must specify the pin"); + throw new InvalidProgramException("You must specify the pin"); + } + + // Create the signature + var factory = new SignatureFactory(); + IExternalSignatureWithChain? signature = null; + if (options.UseCertificates) + { + var availableSignatures = factory.GetAvailableX509Certificate2Signatures(new List { options.LibPathOrIssuerName }); + signature = availableSignatures?.ElementAt((int)options.SignatureIdx); + } + else + { + var availableSignatures = factory.GetAvailablePkcs11Signatures(new List { options.LibPathOrIssuerName }); + signature = availableSignatures?.ElementAt((int)options.SignatureIdx); + } + + signature = signature?.Select(pin); + if (signature == null) + { + throw new ApplicationException("Could not get the correct signature"); + } + + IDocAutoSigner docSigner = new PdfDocAutoSigner(); + // Read file + using (var inputStream = new MemoryStream()) + { + using (var inputFileStream = new FileStream(options.InputFilePath, FileMode.Open, FileAccess.Read)) + { + inputFileStream.CopyTo(inputStream); + } + + // Need to move to the beginning of the stream + inputStream.Seek(0, SeekOrigin.Begin); + + var signatureApperance = new SignatureAppearanceDetails + { + Contact = "CustomContact", + Reason = "CustomReason", + Location = "Bucharest", + PageNumber = 1, + Rectangle = new Rectangle(360, 60, 100, 40) + }; + + // Sign stream + using (var outputStream = docSigner.Sign(inputStream, signature, signatureApperance)) + { + + // Write file + using (var outputFileStream = new FileStream(options.OutputFilePath, FileMode.Create, System.IO.FileAccess.Write)) + { + outputStream.CopyTo(outputFileStream); + } + } + } +} + +void HandleParseErrors(IEnumerable errors) +{ + throw new InvalidProgramException("Could not parse command line arguments."); +} \ No newline at end of file diff --git a/PdfAutoSigner.Lib.App/Properties/launchSettings.json b/PdfAutoSigner.Lib.App/Properties/launchSettings.json new file mode 100644 index 0000000..6d8f5a0 --- /dev/null +++ b/PdfAutoSigner.Lib.App/Properties/launchSettings.json @@ -0,0 +1,15 @@ +{ + "profiles": { + "PdfAutoSigner.Lib.App": { + "commandName": "Project" + }, + "Lib.App - PKCS11": { + "commandName": "Project", + "commandLineArgs": "../../../hello.pdf ../../../hello-signed-pkcs11.pdf \"C:\\Program Files (x86)\\Gemalto\\IDGo 800 PKCS#11\\IDPrimePKCS1164.dll\"" + }, + "Lib.App - Cert": { + "commandName": "Project", + "commandLineArgs": "../../../hello.pdf ../../../hello-signed-cert.pdf certSign -c" + } + } +} \ No newline at end of file diff --git a/PdfAutoSigner.Lib.App/README.md b/PdfAutoSigner.Lib.App/README.md new file mode 100644 index 0000000..6461778 --- /dev/null +++ b/PdfAutoSigner.Lib.App/README.md @@ -0,0 +1,19 @@ +Publish as a self-contained app: +dotnet publish -c Release --self-contained -r win-x64 -p:PublishSingleFile=true +dotnet publish -c Release --self-contained -r osx-x64 -p:PublishSingleFile=true + +Run on mac: +- pkcs11 +./PdfAutoSigner.Lib.App ../hello.pdf ../hello-signed.pdf /usr/local/lib/libeTPkcs11.dylib -p [pin] +- cert +./PdfAutoSigner.Lib.App ./hello.pdf ./hello-signed.pdf certSign -p [pin] -c + +Run on win: +- pkcs11 +./PdfAutoSigner.Lib.App ./hello.pdf ./hello-signed.pdf "C:\Program Files (x86)\Gemalto\IDGo 800 PKCS#11\IDPrimePKCS1164.dll" -p [pin] +- cert +./PdfAutoSigner.Lib.App ./hello.pdf ./hello-signed.pdf certSign -p [pin] -c + +Observations: +The pin can also be obtained from UserSecrets (in VS) from the "TokenPin" path. +For ease of use a hello.pdf file was provided in the root of the project and also 2 launch configurations that can be used to quickly test both types of signatures. Bear in mind you would need the appropiate usb token and setup the pin in the "TokenPin" in UserSecrets if you want to use the launch configurations as they are. \ No newline at end of file diff --git a/PdfAutoSigner.Lib.App/hello.pdf b/PdfAutoSigner.Lib.App/hello.pdf new file mode 100644 index 0000000..ed1c344 Binary files /dev/null and b/PdfAutoSigner.Lib.App/hello.pdf differ diff --git a/PdfAutoSigner.Lib.Tests/PdfAutoSigner.Lib.Tests.csproj b/PdfAutoSigner.Lib.Tests/PdfAutoSigner.Lib.Tests.csproj new file mode 100644 index 0000000..67c7f82 --- /dev/null +++ b/PdfAutoSigner.Lib.Tests/PdfAutoSigner.Lib.Tests.csproj @@ -0,0 +1,30 @@ + + + + net6.0 + enable + enable + + false + + AnyCPU + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/PdfAutoSigner.Lib.Tests/Usings.cs b/PdfAutoSigner.Lib.Tests/Usings.cs new file mode 100644 index 0000000..0acf1d3 --- /dev/null +++ b/PdfAutoSigner.Lib.Tests/Usings.cs @@ -0,0 +1,12 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +global using Xunit; \ No newline at end of file diff --git a/PdfAutoSigner.Lib/ExtensionMethods/PdfSignerExtensions.cs b/PdfAutoSigner.Lib/ExtensionMethods/PdfSignerExtensions.cs new file mode 100644 index 0000000..4e55285 --- /dev/null +++ b/PdfAutoSigner.Lib/ExtensionMethods/PdfSignerExtensions.cs @@ -0,0 +1,31 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using iText.Signatures; +using PdfAutoSigner.Lib.Signers; + +namespace PdfAutoSigner.Lib.ExtensionMethods +{ + public static class PdfSignerExtensions + { + public static void UpdateSignatureAppearance(this PdfSigner pdfSigner, SignatureAppearanceDetails signatureAppearanceDetails) + { + var appearance = pdfSigner.GetSignatureAppearance(); + appearance + .SetReason(signatureAppearanceDetails.Reason) + .SetContact(signatureAppearanceDetails.Contact) + .SetLocation(signatureAppearanceDetails.Location) + .SetPageNumber(signatureAppearanceDetails.PageNumber) + .SetPageRect(signatureAppearanceDetails.Rectangle); + appearance.SetRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION); + } + } +} diff --git a/PdfAutoSigner.Lib/PdfAutoSigner.Lib.csproj b/PdfAutoSigner.Lib/PdfAutoSigner.Lib.csproj new file mode 100644 index 0000000..bad9816 --- /dev/null +++ b/PdfAutoSigner.Lib/PdfAutoSigner.Lib.csproj @@ -0,0 +1,15 @@ + + + + net6.0 + enable + enable + AnyCPU + + + + + + + + diff --git a/PdfAutoSigner.Lib/Signatures/IExternalSignatureWithChain.cs b/PdfAutoSigner.Lib/Signatures/IExternalSignatureWithChain.cs new file mode 100644 index 0000000..1813d21 --- /dev/null +++ b/PdfAutoSigner.Lib/Signatures/IExternalSignatureWithChain.cs @@ -0,0 +1,25 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using iText.Signatures; +using Org.BouncyCastle.X509; + +namespace PdfAutoSigner.Lib.Signatures +{ + public interface IExternalSignatureWithChain : IExternalSignature + { + // Build an unique name for each signature + string GetSignatureIdentifyingName(); + X509Certificate[]? GetChain(); + + IExternalSignatureWithChain Select(string pin); + } +} diff --git a/PdfAutoSigner.Lib/Signatures/ISignatureFactory.cs b/PdfAutoSigner.Lib/Signatures/ISignatureFactory.cs new file mode 100644 index 0000000..3829294 --- /dev/null +++ b/PdfAutoSigner.Lib/Signatures/ISignatureFactory.cs @@ -0,0 +1,19 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +namespace PdfAutoSigner.Lib.Signatures +{ + public interface ISignatureFactory + { + List GetAvailablePkcs11Signatures(List libraryPaths); + List GetAvailableX509Certificate2Signatures(List issuerNames); + } +} \ No newline at end of file diff --git a/PdfAutoSigner.Lib/Signatures/Pkcs11Signature.cs b/PdfAutoSigner.Lib/Signatures/Pkcs11Signature.cs new file mode 100644 index 0000000..eac025c --- /dev/null +++ b/PdfAutoSigner.Lib/Signatures/Pkcs11Signature.cs @@ -0,0 +1,290 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using iText.Signatures; +using Net.Pkcs11Interop.Common; +using Net.Pkcs11Interop.HighLevelAPI; +using Net.Pkcs11Interop.HighLevelAPI.Factories; +using Org.BouncyCastle.Asn1.X509; +using Org.BouncyCastle.X509; + +namespace PdfAutoSigner.Lib.Signatures +{ + /// + /// Original code obtained from https://git.itextsupport.com/projects/I7NS/repos/samples/browse/itext/itext.publications/itext.publications.signing-examples.pkcs11/iText/SigningExamples/Pkcs11/Pkcs11Signature.cs + /// + public class Pkcs11Signature : IExternalSignatureWithChain, IDisposable + { + // For now only SHA256 is supported. + public static readonly string Pkcs11HashAlgorithm = "SHA256"; + + ISlot? slot; + ITokenInfo tokenInfo; + ISession? session; + IObjectHandle? privateKeyHandle; + + X509Certificate[]? chain; + string? encryptionAlgorithm; + string? hashAlgorithm; + + public Pkcs11Signature(ISlot slot) + { + this.slot = slot; + this.tokenInfo = slot.GetTokenInfo(); + this.hashAlgorithm = DigestAlgorithms.GetDigest(DigestAlgorithms.GetAllowedDigest(Pkcs11HashAlgorithm)); + } + + public IExternalSignatureWithChain Select(string pin) + { + return Select(null, null, pin); + } + + public Pkcs11Signature Select(string? alias, string? certLabel, string pin) + { + List pkAttributeKeys = new List(); + pkAttributeKeys.Add(CKA.CKA_KEY_TYPE); + pkAttributeKeys.Add(CKA.CKA_LABEL); + pkAttributeKeys.Add(CKA.CKA_ID); + List certAttributeKeys = new List(); + certAttributeKeys.Add(CKA.CKA_VALUE); + certAttributeKeys.Add(CKA.CKA_LABEL); + + + CloseSession(); + if (slot == null) + { + throw new ApplicationException("Signature device's slot cannot be found"); + } + + session = slot.OpenSession(SessionType.ReadWrite); + var sessionInfo = session.GetSessionInfo(); + + try + { + // Try to logout the user if it was already logged in + if (sessionInfo.State != CKS.CKS_RO_PUBLIC_SESSION && sessionInfo.State != CKS.CKS_RW_PUBLIC_SESSION) + session.Logout(); + } + catch (Exception) + { + // Continue + } + + session.Login(CKU.CKU_USER, pin); + ObjectAttributeFactory objectAttributeFactory = new ObjectAttributeFactory(); + + List attributes = new List(); + attributes.Add(objectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY)); + List keys = session.FindAllObjects(attributes); + + bool found = false; + foreach (IObjectHandle key in keys) + { + List keyAttributes = session.GetAttributeValue(key, pkAttributeKeys); + + ulong type = keyAttributes[0].GetValueAsUlong(); + string encryptionAlgorithm; + switch (type) + { + case (ulong)CKK.CKK_RSA: + encryptionAlgorithm = "RSA"; + break; + case (ulong)CKK.CKK_DSA: + encryptionAlgorithm = "DSA"; + break; + case (ulong)CKK.CKK_ECDSA: + encryptionAlgorithm = "ECDSA"; + break; + default: + continue; + } + string thisAlias = keyAttributes[1].GetValueAsString(); + if (thisAlias == null || thisAlias.Length == 0) + thisAlias = keyAttributes[2].GetValueAsString(); + if (alias != null && !alias.Equals(thisAlias)) + continue; + + attributes.Clear(); + attributes.Add(objectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE)); + attributes.Add(objectAttributeFactory.Create(CKA.CKA_CERTIFICATE_TYPE, CKC.CKC_X_509)); + if (certLabel == null && thisAlias != null && thisAlias.Length > 0) + certLabel = thisAlias; + if (certLabel != null) + attributes.Add(objectAttributeFactory.Create(CKA.CKA_LABEL, certLabel)); + List certificates = session.FindAllObjects(attributes); + if (certificates.Count != 1) + continue; + + IObjectHandle certificate = certificates[0]; + List certificateAttributes = session.GetAttributeValue(certificate, certAttributeKeys); + X509Certificate x509Certificate = new X509Certificate(X509CertificateStructure.GetInstance(certificateAttributes[0].GetValueAsByteArray())); + + List x509Certificates = new List(); + x509Certificates.Add(x509Certificate); + attributes.Clear(); + attributes.Add(objectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_CERTIFICATE)); + attributes.Add(objectAttributeFactory.Create(CKA.CKA_CERTIFICATE_TYPE, CKC.CKC_X_509)); + List otherCertificates = session.FindAllObjects(attributes); + foreach (IObjectHandle otherCertificate in otherCertificates) + { + if (!certificate.ObjectId.Equals(otherCertificate.ObjectId)) + { + certificateAttributes = session.GetAttributeValue(otherCertificate, certAttributeKeys); + X509Certificate otherX509Certificate = new X509Certificate(X509CertificateStructure.GetInstance(certificateAttributes[0].GetValueAsByteArray())); + x509Certificates.Add(otherX509Certificate); + } + } + + found = true; + this.encryptionAlgorithm = encryptionAlgorithm; + this.privateKeyHandle = key; + this.chain = x509Certificates.ToArray(); + break; + } + + if (!found) + { + this.encryptionAlgorithm = null; + this.privateKeyHandle = null; + this.chain = null; + } + + return this; + } + + public void Dispose() + { + CloseSession(); + slot = null; + } + + private void CloseSession() + { + if (session != null) + { + try + { + session.Logout(); + session.Dispose(); + } + finally + { + privateKeyHandle = null; + session = null; + } + } + } + + public X509Certificate[]? GetChain() + { + return chain; + } + + public string GetSignatureIdentifyingName() + { + return $"{tokenInfo.ManufacturerId} - {tokenInfo.Model} - {tokenInfo.SerialNumber}"; + } + + public string? GetEncryptionAlgorithm() + { + return encryptionAlgorithm; + } + + public string? GetHashAlgorithm() + { + return hashAlgorithm; + } + + public byte[] Sign(byte[] message) + { + MechanismFactory mechanismFactory = new MechanismFactory(); + IMechanism mechanism; + + switch (encryptionAlgorithm) + { + case "DSA": + switch (hashAlgorithm) + { + case "SHA1": + mechanism = mechanismFactory.Create(CKM.CKM_DSA_SHA1); + break; + case "SHA224": + mechanism = mechanismFactory.Create(CKM.CKM_DSA_SHA224); + break; + case "SHA256": + mechanism = mechanismFactory.Create(CKM.CKM_DSA_SHA256); + break; + case "SHA384": + mechanism = mechanismFactory.Create(CKM.CKM_DSA_SHA384); + break; + case "SHA512": + mechanism = mechanismFactory.Create(CKM.CKM_DSA_SHA512); + break; + default: + throw new ArgumentException("Not supported: " + hashAlgorithm + "with" + encryptionAlgorithm); + } + break; + case "ECDSA": + switch (hashAlgorithm) + { + case "SHA1": + mechanism = mechanismFactory.Create(CKM.CKM_ECDSA_SHA1); + break; + case "SHA224": + mechanism = mechanismFactory.Create(CKM.CKM_ECDSA_SHA224); + break; + case "SHA256": + mechanism = mechanismFactory.Create(CKM.CKM_ECDSA_SHA256); + break; + case "SHA384": + mechanism = mechanismFactory.Create(CKM.CKM_ECDSA_SHA384); + break; + case "SHA512": + mechanism = mechanismFactory.Create(CKM.CKM_ECDSA_SHA512); + break; + default: + throw new ArgumentException("Not supported: " + hashAlgorithm + "with" + encryptionAlgorithm); + } + break; + case "RSA": + switch (hashAlgorithm) + { + case "SHA1": + mechanism = mechanismFactory.Create(CKM.CKM_SHA1_RSA_PKCS); + break; + case "SHA224": + mechanism = mechanismFactory.Create(CKM.CKM_SHA224_RSA_PKCS); + break; + case "SHA256": + mechanism = mechanismFactory.Create(CKM.CKM_SHA256_RSA_PKCS); + break; + case "SHA384": + mechanism = mechanismFactory.Create(CKM.CKM_SHA384_RSA_PKCS); + break; + case "SHA512": + mechanism = mechanismFactory.Create(CKM.CKM_SHA512_RSA_PKCS); + break; + default: + throw new ArgumentException("Not supported: " + hashAlgorithm + "with" + encryptionAlgorithm); + } + break; + default: + throw new ArgumentException("Not supported: " + hashAlgorithm + "with" + encryptionAlgorithm); + } + + if (session == null) + { + throw new ApplicationException("Session is not instantiated."); + } + return session.Sign(mechanism, privateKeyHandle, message); + } + } +} diff --git a/PdfAutoSigner.Lib/Signatures/SignatureFactory.cs b/PdfAutoSigner.Lib/Signatures/SignatureFactory.cs new file mode 100644 index 0000000..8bc3452 --- /dev/null +++ b/PdfAutoSigner.Lib/Signatures/SignatureFactory.cs @@ -0,0 +1,99 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Net.Pkcs11Interop.Common; +using Net.Pkcs11Interop.HighLevelAPI; +using System.Security.Cryptography.X509Certificates; + +namespace PdfAutoSigner.Lib.Signatures +{ + public class SignatureFactory : ISignatureFactory + { + + + + private readonly ILogger logger; + + public SignatureFactory(ILogger? logger = null) + { + this.logger = logger ?? NullLogger.Instance; + } + + /// + /// Need to call .Select() on the final signatures. + /// + /// + /// + public List GetAvailablePkcs11Signatures(List libraryPaths) + { + var pkcs11Signatures = new List(); + foreach (var libraryPath in libraryPaths) + { + // Attempt to get the correct signatures + var pkcs11Factories = new Pkcs11InteropFactories(); + IPkcs11Library? pkcs11Library = null; + try + { + pkcs11Library = pkcs11Factories.Pkcs11LibraryFactory.LoadPkcs11Library(pkcs11Factories, libraryPath, AppType.MultiThreaded); + } + catch (Exception) + { + logger.LogDebug($"Could not find PKCS11 library {libraryPath}"); + continue; + } + + List? slots = null; + try + { + slots = pkcs11Library.GetSlotList(SlotsType.WithTokenPresent); + } + catch (Exception) + { + logger.LogDebug($"Could not find any token that uses PKCS11 library {libraryPath}"); + continue; + } + + foreach (var slot in slots ?? new List()) + { + logger.LogInformation($"Found token using library {libraryPath} on slot {slot.SlotId}"); + var pkcs11Signature = new Pkcs11Signature(slot); + pkcs11Signatures.Add(pkcs11Signature); + } + } + + return pkcs11Signatures; + } + + public List GetAvailableX509Certificate2Signatures(List issuerNames) + { + var x509Certificate2Signatures = new List(); + var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); + store.Open(OpenFlags.MaxAllowed); + foreach (var issuerName in issuerNames) + { + var certificates = store.Certificates.Where(x => x.HasPrivateKey && x.Issuer.ToLower().Contains(issuerName.ToLower())); + + foreach (var cert in certificates) + { + logger.LogInformation($"Found certificate {cert.FriendlyName} for issuer {issuerNames}"); + var x509Certificate2Signature = new X509Certificate2Signature(cert); + x509Certificate2Signatures.Add(x509Certificate2Signature); + } + } + + store.Close(); + + return x509Certificate2Signatures; + } + } +} diff --git a/PdfAutoSigner.Lib/Signatures/X509Certificate2Extensions.cs b/PdfAutoSigner.Lib/Signatures/X509Certificate2Extensions.cs new file mode 100644 index 0000000..b715d13 --- /dev/null +++ b/PdfAutoSigner.Lib/Signatures/X509Certificate2Extensions.cs @@ -0,0 +1,42 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace PdfAutoSigner.Lib.Signatures +{ + public static class X509Certificate2Extensions + { + const String RSA = "1.2.840.113549.1.1.1"; + const String DSA = "1.2.840.10040.4.1"; + const String ECC = "1.2.840.10045.2.1"; + + public static AsymmetricAlgorithm? GetPrivateKey(this X509Certificate2 cert) + { + AsymmetricAlgorithm? key = null; + switch (cert.PublicKey.Oid.Value) + { + case RSA: + key = cert.GetRSAPrivateKey(); + break; + case DSA: + key = cert.GetDSAPrivateKey(); + break; + case ECC: + key = cert.GetECDsaPrivateKey(); + break; + } + + return key; + } + } +} diff --git a/PdfAutoSigner.Lib/Signatures/X509Certificate2Signature.cs b/PdfAutoSigner.Lib/Signatures/X509Certificate2Signature.cs new file mode 100644 index 0000000..36532b0 --- /dev/null +++ b/PdfAutoSigner.Lib/Signatures/X509Certificate2Signature.cs @@ -0,0 +1,201 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using iText.Signatures; +using Org.BouncyCastle.X509; +using System.Net; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using PdfAutoSigner.Lib.Signatures; + +namespace PdfAutoSigner.Lib.Signatures +{ + /// + /// Original code obtained from https://git.itextsupport.com/projects/I5N/repos/itextsharp/browse/src/core/iTextSharp/text/pdf/security/X509Certificate2Signature.cs?at=refs/heads/develop + /// + public class X509Certificate2Signature: IExternalSignatureWithChain + { + // For now only SHA256 is supported. + // public static readonly string X509CertHashAlgorithm = "SHA256"; + private static readonly HashAlgorithmName X509CertHashAlgorithmName = HashAlgorithmName.SHA256; + + /// + /// The certificate with the private key + /// + private X509Certificate2 certificate; + /** The hash algorithm. */ + private String hashAlgorithm; + /** The encryption algorithm (obtained from the private key) */ + private String encryptionAlgorithm; + + private Org.BouncyCastle.X509.X509Certificate[]? chain; + + /// + /// Creates a signature using a X509Certificate2. It supports smartcards without + /// exportable private keys. + /// + /// The certificate with the private key + /// The hash algorithm for the signature. As the Windows CAPI is used + /// to do the signature the only hash guaranteed to exist is SHA-1 + public X509Certificate2Signature(X509Certificate2 certificate) + { + if (certificate == null) + { + throw new ArgumentException("Certificate should not be null"); + } + + if (!certificate.HasPrivateKey) + throw new ArgumentException("No private key."); + this.certificate = certificate; + this.hashAlgorithm = DigestAlgorithms.GetDigest(DigestAlgorithms.GetAllowedDigest(X509CertHashAlgorithmName.Name)); + var privateKey = certificate.GetPrivateKey(); + if (privateKey is RSA) + { + encryptionAlgorithm = "RSA"; + } + else if (privateKey is RSACng) + { + encryptionAlgorithm = "RSA"; + } + else if (privateKey is DSA) + { + encryptionAlgorithm = "DSA"; + } + else + throw new ArgumentException("Unknown encryption algorithm " + privateKey); + } + + public IExternalSignatureWithChain Select(string pin) + { + X509CertificateParser objCP = new X509CertificateParser(); + chain = new Org.BouncyCastle.X509.X509Certificate[] { objCP.ReadCertificate(certificate.RawData) }; + + if (!string.IsNullOrWhiteSpace(pin)) + { + SetPin(pin); + } + + return this; + } + + private X509Certificate2Signature SetPin(string pin) + { + var privateKey = certificate.GetPrivateKey(); + // For RSA and DSA + if (privateKey is ICspAsymmetricAlgorithm cspAsymAlg) + { + //var cspAsymAlg = (ICspAsymmetricAlgorithm)privateKey; + CspParameters cspParameters = + new CspParameters + { + ProviderType = cspAsymAlg.CspKeyContainerInfo.ProviderType, + ProviderName = cspAsymAlg.CspKeyContainerInfo.ProviderName, + KeyContainerName = cspAsymAlg.CspKeyContainerInfo.KeyContainerName, + //KeyNumber = ((int)cspAsymAlg.CspKeyContainerInfo.KeyNumber), + KeyPassword = new NetworkCredential("", pin).SecurePassword, + Flags = CspProviderFlags.UseExistingKey | CspProviderFlags.NoPrompt + }; + + // set modified RSA crypto provider back + if (privateKey is RSACryptoServiceProvider) + { + var newPrivateKey = new RSACryptoServiceProvider(cspParameters); + certificate = certificate.CopyWithPrivateKey(newPrivateKey); + } + else if (privateKey is DSACryptoServiceProvider) + { + var newPrivateKey = new DSACryptoServiceProvider(cspParameters); + certificate = certificate.CopyWithPrivateKey(newPrivateKey); + } + } + // Different approach is needed for RSACng + else if (privateKey is RSACng rsaCng) + { + // Set the PIN, an explicit null terminator is required to this Unicode/UCS-2 string. + + byte[] propertyBytes; + + if (pin[pin.Length - 1] == '\0') + { + propertyBytes = Encoding.Unicode.GetBytes(pin); + } + else + { + propertyBytes = new byte[Encoding.Unicode.GetByteCount(pin) + 2]; + Encoding.Unicode.GetBytes(pin, 0, pin.Length, propertyBytes, 0); + } + + const string NCRYPT_PIN_PROPERTY = "SmartCardPin"; + + CngProperty pinProperty = new CngProperty( + NCRYPT_PIN_PROPERTY, + propertyBytes, + CngPropertyOptions.None); + + rsaCng.Key.SetProperty(pinProperty); + } + + return this; + } + + public virtual byte[] Sign(byte[] message) + { + var privateKey = certificate.GetPrivateKey(); + + if (privateKey is RSA rsa) + { + return rsa.SignData(message, X509CertHashAlgorithmName, RSASignaturePadding.Pkcs1); + } + //else if (privateKey is RSACng) + //{ + // RSACng rsa = (RSACng)certificate.PrivateKey; + // return rsa.SignData(message, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + //} + else if (privateKey is DSA dsa) + { + return dsa.SignData(message, X509CertHashAlgorithmName); + } + + return Array.Empty(); + } + + public Org.BouncyCastle.X509.X509Certificate[]? GetChain() + { + return chain; + } + + public string GetSignatureIdentifyingName() + { + return $"{certificate.Subject} - {certificate.SerialNumber}"; + } + + /** + * Returns the hash algorithm. + * @return the hash algorithm (e.g. "SHA-1", "SHA-256,...") + * @see com.itextpdf.text.pdf.security.ExternalSignature#getHashAlgorithm() + */ + public virtual String GetHashAlgorithm() + { + return hashAlgorithm; + } + + /** + * Returns the encryption algorithm used for signing. + * @return the encryption algorithm ("RSA" or "DSA") + * @see com.itextpdf.text.pdf.security.ExternalSignature#getEncryptionAlgorithm() + */ + public virtual String GetEncryptionAlgorithm() + { + return encryptionAlgorithm; + } + } +} diff --git a/PdfAutoSigner.Lib/Signers/IDocAutoSigner.cs b/PdfAutoSigner.Lib/Signers/IDocAutoSigner.cs new file mode 100644 index 0000000..707b9f6 --- /dev/null +++ b/PdfAutoSigner.Lib/Signers/IDocAutoSigner.cs @@ -0,0 +1,20 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using PdfAutoSigner.Lib.Signatures; + +namespace PdfAutoSigner.Lib.Signers +{ + public interface IDocAutoSigner + { + MemoryStream Sign(Stream inputStream, IExternalSignatureWithChain externalSignature, SignatureAppearanceDetails signatureAppearanceDetails); + } +} \ No newline at end of file diff --git a/PdfAutoSigner.Lib/Signers/PdfDocAutoSigner.cs b/PdfAutoSigner.Lib/Signers/PdfDocAutoSigner.cs new file mode 100644 index 0000000..54d6752 --- /dev/null +++ b/PdfAutoSigner.Lib/Signers/PdfDocAutoSigner.cs @@ -0,0 +1,54 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using iText.Kernel.Pdf; +using iText.Signatures; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using PdfAutoSigner.Lib.ExtensionMethods; +using PdfAutoSigner.Lib.Signatures; +using static iText.Signatures.PdfSigner; + +namespace PdfAutoSigner.Lib.Signers +{ + public class PdfDocAutoSigner : IDocAutoSigner + { + private readonly ILogger logger; + + public PdfDocAutoSigner(ILogger? logger = null) + { + this.logger = logger ?? NullLogger.Instance; + } + + public MemoryStream Sign(Stream inputStream, IExternalSignatureWithChain externalSignature, SignatureAppearanceDetails signatureAppearanceDetails) + { + using var reader = new PdfReader(inputStream); + using var tempOutputStream = new MemoryStream(0); + + var stampingProperties = new StampingProperties().UseAppendMode(); + + // Signer.SignDetached will close the stream. We need to create a temporary stream to be used from the signer and then copy the content into the output + + var signer = new PdfSigner(reader, tempOutputStream, stampingProperties); + + // Set appearance + signer.UpdateSignatureAppearance(signatureAppearanceDetails); + + // TODO: Might need to give extimated size + signer.SignDetached(externalSignature, externalSignature.GetChain(), null, null, null, 0, CryptoStandard.CMS); + logger.LogInformation($"Signed document with signature {externalSignature.GetSignatureIdentifyingName()}"); + + // Copy the data from the closed temporary output stream into the final output stream. + var outputData = tempOutputStream.GetBuffer(); + return new MemoryStream(outputData); + } + } +} diff --git a/PdfAutoSigner.Lib/Signers/SignatureAppearanceDetails.cs b/PdfAutoSigner.Lib/Signers/SignatureAppearanceDetails.cs new file mode 100644 index 0000000..48307c3 --- /dev/null +++ b/PdfAutoSigner.Lib/Signers/SignatureAppearanceDetails.cs @@ -0,0 +1,24 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using iText.Kernel.Geom; + +namespace PdfAutoSigner.Lib.Signers +{ + public class SignatureAppearanceDetails + { + public string? Reason { get; set; } + public string? Contact { get; set; } + public string? Location { get; set; } + public int PageNumber { get; set; } + public Rectangle? Rectangle { get; set; } + } +} diff --git a/PdfAutoSigner.LocalApi.Installer/Common.wxl b/PdfAutoSigner.LocalApi.Installer/Common.wxl new file mode 100644 index 0000000..dd83f54 --- /dev/null +++ b/PdfAutoSigner.LocalApi.Installer/Common.wxl @@ -0,0 +1,12 @@ + + + Plant An App + PlantAnApp + PdfAutoSigner + Pdf Auto Signer (32bit) + Pdf Auto Signer (64bit) + PlantAnApp.PdfAutoSigner + 1033 + Auto signs PDFs using USB tokens. + A newer version of Pdf Auto Signer is already installed. + diff --git a/PdfAutoSigner.LocalApi.Installer/ComponentsGenerated.wxs b/PdfAutoSigner.LocalApi.Installer/ComponentsGenerated.wxs new file mode 100644 index 0000000..3b56e0d --- /dev/null +++ b/PdfAutoSigner.LocalApi.Installer/ComponentsGenerated.wxs @@ -0,0 +1,47 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/PdfAutoSigner.LocalApi.Installer/PdfAutoSigner.LocalApi.Installer.wixproj b/PdfAutoSigner.LocalApi.Installer/PdfAutoSigner.LocalApi.Installer.wixproj new file mode 100644 index 0000000..0e4c258 --- /dev/null +++ b/PdfAutoSigner.LocalApi.Installer/PdfAutoSigner.LocalApi.Installer.wixproj @@ -0,0 +1,98 @@ + + + + Debug + x86 + 3.10 + 242f7161-3a21-49fb-96df-0b0dc81a40a0 + 2.0 + PdfAutoSigner-$(Configuration)-$(Platform) + Package + ; + PdfAutoSigner.LocalApi.Installer + + + bin\$(Configuration)\ + obj\$(Configuration)\ + Debug + + + bin\$(Configuration)\ + obj\$(Configuration)\ + + + bin\$(Configuration)\ + obj\$(Configuration)\ + Debug + + + bin\$(Configuration)\ + obj\$(Configuration)\ + + + + + + + + + + + + + + + + PdfAutoSigner.LocalApi + {ac02edfd-ea1e-4ce5-ae0b-a51eda689740} + True + True + Binaries;Content;Satellites + INSTALLFOLDER + + + + + $(WixExtDir)\WixUtilExtension.dll + WixUtilExtension + + + $(WixExtDir)\WixUIExtension.dll + WixUIExtension + + + + + + + + + + + + + + + + + + + + + BuildVersion=%(AssemblyVersion.Version);BasePath=..\PdfAutoSigner.LocalApi\bin\$(Configuration)\net6.0\win-$(Platform)\publish + true + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/PdfAutoSigner.LocalApi.Installer/Product.wxs b/PdfAutoSigner.LocalApi.Installer/Product.wxs new file mode 100644 index 0000000..a47580a --- /dev/null +++ b/PdfAutoSigner.LocalApi.Installer/Product.wxs @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NOT Installed AND NOT WIX_UPGRADE_DETECTED AND NOT WIX_DOWNGRADE_DETECTED + + + Installed AND (REMOVE="ALL") AND NOT (WIX_UPGRADE_DETECTED OR UPGRADINGPRODUCTCODE) + Installed AND (REMOVE="ALL") AND NOT (WIX_UPGRADE_DETECTED OR UPGRADINGPRODUCTCODE) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/PdfAutoSigner.LocalApi.Installer/README.md b/PdfAutoSigner.LocalApi.Installer/README.md new file mode 100644 index 0000000..fa24a97 --- /dev/null +++ b/PdfAutoSigner.LocalApi.Installer/README.md @@ -0,0 +1,16 @@ +Project built based on https://www.youtube.com/watch?v=6Yf-eDsRrnM + +# Project details +Install the WIX Toolset and the Wix Extension for Visual Studio from https://wixtoolset.org/ + +Change the two ProductCode entries each time you change the version of the application. Never change the UpgradeCode. + +The project has some before sections to run customized scripts: in order to see it the project has to be edited in an editor. +In the before section there is a HeatDirectory instruction. This uses heat to automatically generate the ComponentsGenerated.wxs file which contains the files from the publish folder. The first time this was run I needed to first comment out the corresponding lines from the Product.wxs; you should not need to do this any longer. +Regarding the HeatDirectory there is a RunWixToolsOutOfProc line in the PropertyGroup and a RunAsSeparateProcess attribute in the HeatDirectory: this is because heat has some issues running on 64 bit machines. Do not alter this part without properly testing it. +Also, regarding the HeatDirectory: we use a RemoveExeComponentsTransform.xslt. This is because we cannot easily exclude files from the harvesting process. This allows us to remove any executables. We need to manually add the executable for the local api in the Product.wxs file so that we can create a Windows Service that links to this executable. + +I recommend not to change the ProductCode at all. Keeping the same ProductCode will force the client to uninstall the previous version, which I think it is the safest approach. Uninstalling or installing the application should first cause the related existing Windows Service to uninstall. + +# Instructions for clients +The client has to run the msi as an administrator. He should also restart the PC after installing and uninstalling the application. \ No newline at end of file diff --git a/PdfAutoSigner.LocalApi.Installer/RemoveExeComponentsTransform.xslt b/PdfAutoSigner.LocalApi.Installer/RemoveExeComponentsTransform.xslt new file mode 100644 index 0000000..07b984a --- /dev/null +++ b/PdfAutoSigner.LocalApi.Installer/RemoveExeComponentsTransform.xslt @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/PdfAutoSigner.LocalApi.Tests/AutoDomainData.cs b/PdfAutoSigner.LocalApi.Tests/AutoDomainData.cs new file mode 100644 index 0000000..ad691b8 --- /dev/null +++ b/PdfAutoSigner.LocalApi.Tests/AutoDomainData.cs @@ -0,0 +1,25 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using AutoFixture; +using AutoFixture.AutoMoq; +using AutoFixture.Xunit2; + +namespace PdfAutoSigner.LocalApi.Tests +{ + public class AutoDomainDataAttribute: AutoDataAttribute + { + public AutoDomainDataAttribute(): + base(() => new Fixture().Customize(new AutoMoqCustomization())) + { + } + } +} diff --git a/PdfAutoSigner.LocalApi.Tests/Controllers/SignControllerTests.cs b/PdfAutoSigner.LocalApi.Tests/Controllers/SignControllerTests.cs new file mode 100644 index 0000000..6088b98 --- /dev/null +++ b/PdfAutoSigner.LocalApi.Tests/Controllers/SignControllerTests.cs @@ -0,0 +1,119 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using AutoFixture; +using AutoFixture.Xunit2; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Moq; +using PdfAutoSigner.Lib.Signatures; +using PdfAutoSigner.LocalApi.Controllers; +using PdfAutoSigner.LocalApi.Models; +using PdfAutoSigner.LocalApi.Services; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; + +namespace PdfAutoSigner.LocalApi.Tests.Controllers +{ + public class SignControllerTests + { + [Theory] + [AutoDomainData] + public void GetAvailableSignatures_ReturnsAllSignaturesIdentifyingNames( + Mock signatureMock1, Mock signatureMock2, + [Frozen] Mock signaturesProviderServiceMock, [NoAutoProperties] SignController signController) + { + signatureMock1.Setup(s => s.GetSignatureIdentifyingName()).Returns("Sign1"); + signatureMock2.Setup(s => s.GetSignatureIdentifyingName()).Returns("Sign2"); + + signaturesProviderServiceMock.Setup(sp => sp.GetAvailableSignatures()).Returns(new List() + { + signatureMock1.Object, signatureMock2.Object + }); + + var result = signController.GetAvailableSignatures(); + + var okResult = result.Result as OkObjectResult; + var signatures = okResult?.Value as List; + Assert.Equal(2, signatures?.Count); + Assert.Contains("Sign1", signatures); + Assert.Contains("Sign2", signatures); + } + + [Theory] + [AutoDomainData] + public void Sign_MissingPin_ReturnsBadRequest( + [Frozen] Mock formFileMock, + [NoAutoProperties] SignController signController) + { + var inputData = new SignInputData { Pin = "" }; + var inputDataJson = JsonSerializer.Serialize(inputData); + + var result = signController.Sign(formFileMock.Object, inputDataJson); + + Assert.IsType(result); + } + + [Theory] + [AutoDomainData] + public void Sign_MissingSignature_ReturnsBadRequest( + [Frozen] Mock formFileMock, + [NoAutoProperties] SignController signController) + { + var inputData = new SignInputData { SignatureName = "" }; + var inputDataJson = JsonSerializer.Serialize(inputData); + + var result = signController.Sign(formFileMock.Object, inputDataJson); + + Assert.IsType(result); + } + + [Theory] + [AutoDomainData] + public void Sign_CallsSignWithCorrectParameters( + [Frozen] Mock formFileMock, [Frozen] Mock signerServiceMock, + [NoAutoProperties] SignController signController) + { + var inputData = new SignInputData { Pin = "123456", SignatureName = "Sign1" }; + var inputDataJson = JsonSerializer.Serialize(inputData); + + Stream? inputStream = null; + formFileMock.Setup(f => f.CopyTo(It.IsAny())).Callback(s => inputStream = s); + + var result = signController.Sign(formFileMock.Object, inputDataJson); + + signerServiceMock.Verify(s => s.Sign(inputStream!, "Sign1", "123456")); + } + + [Theory] + [AutoDomainData] + public void Sign_ReturnsResultFromSign( + SignInputData signInputData, Mock outputMemStreamMock, + [Frozen] Mock formFileMock, [Frozen] Mock signerServiceMock, + [NoAutoProperties] SignController signController) + { + var inputDataJson = JsonSerializer.Serialize(signInputData); + byte[] signedByteArr = Encoding.ASCII.GetBytes("test result"); + outputMemStreamMock.Setup(ms => ms.ToArray()).Returns(signedByteArr); + signerServiceMock.Setup(s => s.Sign(It.IsAny(), It.IsAny(), It.IsAny())).Returns(outputMemStreamMock.Object); + + var result = signController.Sign(formFileMock.Object, inputDataJson); + + var fileContentResult = result as FileContentResult; + Assert.Equal(signedByteArr, fileContentResult!.FileContents); + Assert.Equal(System.Net.Mime.MediaTypeNames.Application.Octet, fileContentResult.ContentType); + } + } +} diff --git a/PdfAutoSigner.LocalApi.Tests/Files/hello.pdf b/PdfAutoSigner.LocalApi.Tests/Files/hello.pdf new file mode 100644 index 0000000..ed1c344 Binary files /dev/null and b/PdfAutoSigner.LocalApi.Tests/Files/hello.pdf differ diff --git a/PdfAutoSigner.LocalApi.Tests/PdfAutoSigner.LocalApi.Tests.csproj b/PdfAutoSigner.LocalApi.Tests/PdfAutoSigner.LocalApi.Tests.csproj new file mode 100644 index 0000000..260a25c --- /dev/null +++ b/PdfAutoSigner.LocalApi.Tests/PdfAutoSigner.LocalApi.Tests.csproj @@ -0,0 +1,37 @@ + + + + net6.0 + enable + enable + + false + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + + Always + + + + diff --git a/PdfAutoSigner.LocalApi.Tests/Services/SignaturesProviderServiceTests.cs b/PdfAutoSigner.LocalApi.Tests/Services/SignaturesProviderServiceTests.cs new file mode 100644 index 0000000..dc4c5f7 --- /dev/null +++ b/PdfAutoSigner.LocalApi.Tests/Services/SignaturesProviderServiceTests.cs @@ -0,0 +1,58 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using AutoFixture; +using AutoFixture.Xunit2; +using Moq; +using Net.Pkcs11Interop.HighLevelAPI; +using PdfAutoSigner.Lib.Signatures; +using PdfAutoSigner.LocalApi.Services; + +namespace PdfAutoSigner.LocalApi.Tests.Services +{ + public class SignaturesProviderServiceTests + { + [Theory] + [AutoDomainData] + public void GetAvailableSignatures_ReturnsPkcs11AndCertSignatures([Frozen] Mock signatureFactoryMock, + SignaturesProviderService signaturesProviderService, Fixture fixture) + { + var iSlot = fixture.Create(); + var pkcs11Signatures = Enumerable.Repeat(1, 5).Select(_ => new Pkcs11Signature(iSlot)).ToList(); + var cert = X509CertificateFactory.CreateRsaCertificate("P@55w0rd"); + var certSignatures = Enumerable.Repeat(1, 3).Select(_ => new X509Certificate2Signature(cert)).ToList(); + signatureFactoryMock.Setup(f => f.GetAvailablePkcs11Signatures(It.IsAny>())).Returns(pkcs11Signatures); + signatureFactoryMock.Setup(f => f.GetAvailableX509Certificate2Signatures(It.IsAny>())).Returns(certSignatures); + + var signatures = signaturesProviderService.GetAvailableSignatures(); + + Assert.Equal(8, signatures.Count); + Assert.Contains(signatures, x => pkcs11Signatures.Contains(x)); + Assert.Contains(signatures, x => certSignatures.Contains(x)); + } + + [Theory] + [AutoDomainData] + public void GetAvailableSignatures_UsesConfigOptions([Frozen] Mock signatureFactoryMock, + [Frozen] Mock tokenConfigServiceMock, SignaturesProviderService signaturesProviderService, Fixture fixture) + { + var pkcsLibPaths = fixture.CreateMany(5).ToList(); + var certIssuerNames = fixture.CreateMany(5).ToList(); + tokenConfigServiceMock.Setup(t => t.GetPkcs11LibPathsByOS()).Returns(pkcsLibPaths); + tokenConfigServiceMock.Setup(t => t.GetIssuerNames()).Returns(certIssuerNames); + + var signatures = signaturesProviderService.GetAvailableSignatures(); + + signatureFactoryMock.Verify(f => f.GetAvailablePkcs11Signatures(pkcsLibPaths), Times.Once()); + signatureFactoryMock.Verify(f => f.GetAvailableX509Certificate2Signatures(certIssuerNames), Times.Once()); + } + } +} diff --git a/PdfAutoSigner.LocalApi.Tests/Services/SignerServiceTests.cs b/PdfAutoSigner.LocalApi.Tests/Services/SignerServiceTests.cs new file mode 100644 index 0000000..dd911cf --- /dev/null +++ b/PdfAutoSigner.LocalApi.Tests/Services/SignerServiceTests.cs @@ -0,0 +1,130 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using AutoFixture; +using AutoFixture.Xunit2; +using iText.Kernel.Pdf; +using iText.Signatures; +using Moq; +using PdfAutoSigner.Lib.Signatures; +using PdfAutoSigner.Lib.Signers; +using PdfAutoSigner.LocalApi.Services; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace PdfAutoSigner.LocalApi.Tests.Services +{ + public class SignerServiceTests + { + private const string SignatureIdentifyingName = "NewSignature"; + private const string Pin = "123456"; + + [Theory] + [AutoDomainData] + public void Sign_NoSignatureWithName_ThrowException( + Mock signatureMock, + [Frozen] Mock signaturesProviderServiceMock, + SignerService signerService, Fixture fixture) + { + signatureMock.Setup(s => s.GetSignatureIdentifyingName()).Returns("Inexistent"); + signaturesProviderServiceMock.Setup(sp => sp.GetAvailableSignatures()).Returns(new List { signatureMock.Object }); + + Action act = () => signerService.Sign(fixture.Create(), SignatureIdentifyingName, Pin); + + Assert.Throws(act); + } + + [Theory] + [AutoDomainData] + public void Sign_SelectUsesPin( + Mock signatureMock, + [Frozen] Mock signaturesProviderServiceMock, + SignerService signerService, Fixture fixture) + { + signatureMock.Setup(s => s.GetSignatureIdentifyingName()).Returns("NewSignature"); + signaturesProviderServiceMock.Setup(sp => sp.GetAvailableSignatures()).Returns(new List { signatureMock.Object }); + + signerService.Sign(fixture.Create(), SignatureIdentifyingName, Pin); + + signatureMock.Verify(s => s.Select(Pin), Times.Once()); + } + + [Theory] + [AutoDomainData] + public void Sign_SelectThrowsException_ThrowException( + Mock signatureMock, + [Frozen] Mock signaturesProviderServiceMock, + SignerService signerService, Fixture fixture) + { + signatureMock.Setup(s => s.GetSignatureIdentifyingName()).Returns(SignatureIdentifyingName); + signatureMock.Setup(s => s.Select(It.IsAny())).Throws(); + signaturesProviderServiceMock.Setup(sp => sp.GetAvailableSignatures()).Returns(new List { signatureMock.Object }); + + Action act = () => signerService.Sign(fixture.Create(), SignatureIdentifyingName, Pin); + + Assert.Throws(act); + } + + [Theory] + [AutoDomainData] + public void Sign_UsesCorrectParameters( + Mock signatureMock, + [Frozen] Mock signaturesProviderServiceMock, + [Frozen] Mock signerMock, + SignerService signerService, Fixture fixture) + { + var inputStream = fixture.Create(); + signatureMock.Setup(s => s.GetSignatureIdentifyingName()).Returns(SignatureIdentifyingName); + signatureMock.Setup(s => s.Select(Pin)).Returns(signatureMock.Object); + signaturesProviderServiceMock.Setup(sp => sp.GetAvailableSignatures()).Returns(new List { signatureMock.Object }); + + signerService.Sign(inputStream, SignatureIdentifyingName, Pin); + + signerMock.Verify(s => s.Sign(inputStream, signatureMock.Object, It.IsAny()), Times.Once()); + } + + [Theory] + [AutoDomainData] + public void Sign_SignActualPdf_ReturnsSignedStreamWithOneSignature([Frozen] Mock signaturesProviderServiceMock) + { + string? password = null; + var cert = X509CertificateFactory.CreateRsaCertificate(password!); + var certSignatures = new List { new X509Certificate2Signature(cert) }; + var signatureName = certSignatures[0].GetSignatureIdentifyingName(); + signaturesProviderServiceMock.Setup(p => p.GetAvailableSignatures()).Returns(certSignatures); + var docService = new PdfDocAutoSigner(); + var signerService = new SignerService(signaturesProviderServiceMock.Object, docService); + + using MemoryStream inputStream = new MemoryStream(); + ReadFile("hello.pdf", inputStream); + + var outputStream = signerService.Sign(inputStream, signatureName, password!); + + using var reader = new PdfReader(outputStream); + using var doc = new PdfDocument(reader); + var signUtil = new SignatureUtil(doc); + var names = signUtil.GetSignatureNames(); + + Assert.Equal(1, names.Count); + } + + private void ReadFile(string fileName, MemoryStream ms) + { + string path = Path.Combine(Environment.CurrentDirectory, @"Files", fileName); + using (var file = new FileStream(path, FileMode.Open, FileAccess.Read)) + file.CopyTo(ms); + ms.Seek(0, SeekOrigin.Begin); + } + } +} diff --git a/PdfAutoSigner.LocalApi.Tests/Services/TokenConfigServiceTests.cs b/PdfAutoSigner.LocalApi.Tests/Services/TokenConfigServiceTests.cs new file mode 100644 index 0000000..66c01c2 --- /dev/null +++ b/PdfAutoSigner.LocalApi.Tests/Services/TokenConfigServiceTests.cs @@ -0,0 +1,93 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using AutoFixture; +using AutoFixture.Xunit2; +using Microsoft.Extensions.Options; +using Moq; +using PdfAutoSigner.LocalApi.Config; +using PdfAutoSigner.LocalApi.Helpers; +using PdfAutoSigner.LocalApi.Services; +using System.Runtime.InteropServices; + +namespace PdfAutoSigner.LocalApi.Tests.Services +{ + public class TokenConfigServiceTests + { + [Theory] + [AutoDomainData] + public void GetPkcs11LibPathsByOS_UnsupportedOS_ThrowException( + [Frozen] Mock> tokenOptionsSnapshotMock, + [Frozen] Mock osHelperMock, TokenConfigService tokenConfigService, Fixture fixture) + { + tokenOptionsSnapshotMock.Setup(to => to.Value).Returns(fixture.Create()); + osHelperMock.Setup(os => os.GetOS()).Returns(null); + + Action act = () => tokenConfigService.GetPkcs11LibPathsByOS(); + + Assert.Throws(act); + } + + [Theory] + [AutoDomainData] + public void GetPkcs11LibPathsByOS_ReturnOnlyEntriesWithMatchingOSAndArchitecture( + [Frozen] Mock> tokenOptionsSnapshotMock, + [Frozen] Mock osHelperMock, TokenConfigService tokenConfigService, Fixture fixture) + { + var pkcs11LibData = fixture.CreateMany(20); + // Eliminate all the Win x64 combinations so that we know exactly how many we will have + var filteredPkcs11LibData = pkcs11LibData.Where(pld => pld.OS != SupportedOS.Windows && pld.Architecture != Architecture.X64); + // Add fixed number of win x64 entries + var win64Pkcs11LibData = fixture.Build().With(pld => pld.OS, SupportedOS.Windows) + .With(pld => pld.Architecture, Architecture.X64).CreateMany(3); + var finalPkcs11LibData = filteredPkcs11LibData.Concat(win64Pkcs11LibData); + + var tokenOptions = new TokenOptions + { + Pkcs11Devices = new List + { + new Pkcs11DeviceData { Name = "Device1", Pkcs11LibPaths = finalPkcs11LibData.ToList() } + } + }; + tokenOptionsSnapshotMock.Setup(to => to.Value).Returns(tokenOptions); + osHelperMock.Setup(os => os.GetOS()).Returns(SupportedOS.Windows); + osHelperMock.Setup(os => os.GetArchitecture()).Returns(Architecture.X64); + + var libPaths = tokenConfigService.GetPkcs11LibPathsByOS(); + + Assert.Equal(3, libPaths.Count); + var expectedPaths = win64Pkcs11LibData.Select(pld => pld.LibPath); + Assert.Equal(expectedPaths.OrderBy(p => p), libPaths.OrderBy(p => p)); + } + + [Theory] + [AutoDomainData] + public void GetIssuerNames_ReturnCertIssuerNames( + [Frozen] Mock> tokenOptionsSnapshotMock, + TokenConfigService tokenConfigService, Fixture fixture) + { + var certData1 = fixture.Build().With(c => c.CertificateIssuerName, "Issuer1").Create(); + var certData2 = fixture.Build().With(c => c.CertificateIssuerName, "Issuer2").Create(); + var certIssuerData = new List { certData1, certData2 }; + var tokenOptions = new TokenOptions + { + Certificates = certIssuerData + }; + tokenOptionsSnapshotMock.Setup(to => to.Value).Returns(tokenOptions); + + var certIssuerNames = tokenConfigService.GetIssuerNames(); + + Assert.Equal(2, certIssuerNames.Count); + Assert.Contains("Issuer1", certIssuerNames); + Assert.Contains("Issuer2", certIssuerNames); + } + } +} diff --git a/PdfAutoSigner.LocalApi.Tests/Usings.cs b/PdfAutoSigner.LocalApi.Tests/Usings.cs new file mode 100644 index 0000000..0acf1d3 --- /dev/null +++ b/PdfAutoSigner.LocalApi.Tests/Usings.cs @@ -0,0 +1,12 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +global using Xunit; \ No newline at end of file diff --git a/PdfAutoSigner.LocalApi.Tests/X509CertificateFactory.cs b/PdfAutoSigner.LocalApi.Tests/X509CertificateFactory.cs new file mode 100644 index 0000000..3615680 --- /dev/null +++ b/PdfAutoSigner.LocalApi.Tests/X509CertificateFactory.cs @@ -0,0 +1,40 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using PdfAutoSigner.Lib.Signatures; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading.Tasks; + +namespace PdfAutoSigner.LocalApi.Tests +{ + // Based on https://stackoverflow.com/questions/13806299/how-can-i-create-a-self-signed-certificate-using-c + public class X509CertificateFactory + { + public static X509Certificate2 CreateRsaCertificate(string password) + { + var rsaCng = RSACng.Create(); + + var req = new CertificateRequest("cn=testcert", rsaCng, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5)); + + // use cert2.GetECDsaPrivateKey() to get the private key + X509Certificate2 cert2 = new X509Certificate2(cert.Export(X509ContentType.Pfx, password), password, + X509KeyStorageFlags.PersistKeySet); + + return cert2; + } + } +} diff --git a/PdfAutoSigner.LocalApi/Config/CertificateData.cs b/PdfAutoSigner.LocalApi/Config/CertificateData.cs new file mode 100644 index 0000000..52fb334 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Config/CertificateData.cs @@ -0,0 +1,19 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +namespace PdfAutoSigner.LocalApi.Config +{ + public class CertificateData + { + public string? Name { get; set; } + public string? CertificateIssuerName { get; set; } + } +} diff --git a/PdfAutoSigner.LocalApi/Config/Pkcs11Device.cs b/PdfAutoSigner.LocalApi/Config/Pkcs11Device.cs new file mode 100644 index 0000000..6e68956 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Config/Pkcs11Device.cs @@ -0,0 +1,19 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +namespace PdfAutoSigner.LocalApi.Config +{ + public class Pkcs11DeviceData + { + public string? Name { get; set; } + public List Pkcs11LibPaths { get; set; } = new List(); + } +} diff --git a/PdfAutoSigner.LocalApi/Config/Pkcs11LibData.cs b/PdfAutoSigner.LocalApi/Config/Pkcs11LibData.cs new file mode 100644 index 0000000..73ac1a1 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Config/Pkcs11LibData.cs @@ -0,0 +1,28 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.Runtime.InteropServices; + +namespace PdfAutoSigner.LocalApi.Config +{ + public class Pkcs11LibPathData + { + [JsonConverter(typeof(StringEnumConverter))] + public SupportedOS OS { get; set; } + + [JsonConverter(typeof(StringEnumConverter))] + public Architecture Architecture { get; set; } + + public string? LibPath { get; set; } + } +} diff --git a/PdfAutoSigner.LocalApi/Config/SupportedOS.cs b/PdfAutoSigner.LocalApi/Config/SupportedOS.cs new file mode 100644 index 0000000..29aa364 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Config/SupportedOS.cs @@ -0,0 +1,20 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +namespace PdfAutoSigner.LocalApi.Config +{ + public enum SupportedOS + { + Windows, + MacOS, + Linux + } +} diff --git a/PdfAutoSigner.LocalApi/Config/TokenOptions.cs b/PdfAutoSigner.LocalApi/Config/TokenOptions.cs new file mode 100644 index 0000000..2da2bfd --- /dev/null +++ b/PdfAutoSigner.LocalApi/Config/TokenOptions.cs @@ -0,0 +1,23 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +namespace PdfAutoSigner.LocalApi.Config +{ + public class TokenOptions + { + public const string TokensConfigPath = "TokensConfig"; + public const string Pkcs11DevicesConfigPath = $"{TokensConfigPath}:Pkcs11Devices"; + public const string CertificatesConfigPath = $"{TokensConfigPath}:Certificates"; + + public List Pkcs11Devices { get; set; } = new List(); + public List Certificates { get; set; } = new List(); + } +} diff --git a/PdfAutoSigner.LocalApi/Controllers/SignController.cs b/PdfAutoSigner.LocalApi/Controllers/SignController.cs new file mode 100644 index 0000000..9fca4f7 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Controllers/SignController.cs @@ -0,0 +1,67 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using Microsoft.AspNetCore.Mvc; +using PdfAutoSigner.LocalApi.Models; +using PdfAutoSigner.LocalApi.Services; +using System.Text.Json; + +namespace PdfAutoSigner.LocalApi.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class SignController : ControllerBase + { + private ISignerService signerService; + private ISignaturesProviderService signaturesProviderService; + public SignController(ISignerService signerService, ISignaturesProviderService signaturesProviderService) + { + this.signerService = signerService; + this.signaturesProviderService = signaturesProviderService; + } + + [HttpGet] + public ActionResult> GetAvailableSignatures() + { + var availableSignatures = signaturesProviderService.GetAvailableSignatures(); + var signatureNames = availableSignatures.Select(s => s.GetSignatureIdentifyingName()).ToList(); + + return Ok(signatureNames); + } + + [HttpPost] + public IActionResult Sign([FromForm] IFormFile file, [FromForm] string inputDataJson) + { + var inputData = JsonSerializer.Deserialize(inputDataJson); + if (string.IsNullOrWhiteSpace(inputData?.Pin)) + { + return BadRequest("The pin must be specified."); + } + if (string.IsNullOrWhiteSpace(inputData.SignatureName)) + { + return BadRequest("A signature must be selected."); + } + + var inputMemStream = new MemoryStream(); + file.CopyTo(inputMemStream); + inputMemStream.Seek(0, SeekOrigin.Begin); + + var outputMemStream = signerService.Sign(inputMemStream, signatureIdentifyingName: inputData.SignatureName, pin: inputData.Pin); + + // Copy to a byte[] to return it to caller + byte[] buffer = new byte[file.Length]; + buffer = outputMemStream.ToArray(); + outputMemStream.Close(); + + return File(buffer, System.Net.Mime.MediaTypeNames.Application.Octet); + } + } +} diff --git a/PdfAutoSigner.LocalApi/Controllers/VersionController.cs b/PdfAutoSigner.LocalApi/Controllers/VersionController.cs new file mode 100644 index 0000000..0eb8d13 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Controllers/VersionController.cs @@ -0,0 +1,41 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using Microsoft.AspNetCore.Mvc; +using System.Reflection; + +namespace PdfAutoSigner.LocalApi.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class VersionController : ControllerBase + { + [HttpGet("app-file")] + public ActionResult> GetAssemblyFileVersion() + { + var assemblyFileVersion = Assembly.GetEntryAssembly()?.GetCustomAttribute()?.Version; + + return Ok(assemblyFileVersion); + } + + /// + /// This is what is used by the Wix Installer and shown in Windows. + /// + /// + [HttpGet("app-assembly")] + public ActionResult> GetAssemblyVersion() + { + var assemblyVersion = Assembly.GetEntryAssembly()?.GetName().Version; + + return Ok(assemblyVersion); + } + } +} diff --git a/PdfAutoSigner.LocalApi/Helpers/IOSHelper.cs b/PdfAutoSigner.LocalApi/Helpers/IOSHelper.cs new file mode 100644 index 0000000..a40d5a6 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Helpers/IOSHelper.cs @@ -0,0 +1,22 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using PdfAutoSigner.LocalApi.Config; +using System.Runtime.InteropServices; + +namespace PdfAutoSigner.LocalApi.Helpers +{ + public interface IOSHelper + { + Architecture GetArchitecture(); + SupportedOS? GetOS(); + } +} \ No newline at end of file diff --git a/PdfAutoSigner.LocalApi/Helpers/OSHelper.cs b/PdfAutoSigner.LocalApi/Helpers/OSHelper.cs new file mode 100644 index 0000000..447bc8c --- /dev/null +++ b/PdfAutoSigner.LocalApi/Helpers/OSHelper.cs @@ -0,0 +1,42 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using PdfAutoSigner.LocalApi.Config; +using System.Runtime.InteropServices; + +namespace PdfAutoSigner.LocalApi.Helpers +{ + public class OSHelper : IOSHelper + { + public SupportedOS? GetOS() + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return SupportedOS.Windows; + } + if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + return SupportedOS.MacOS; + } + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return SupportedOS.Linux; + } + + return null; + } + + public Architecture GetArchitecture() + { + return RuntimeInformation.OSArchitecture; + } + } +} diff --git a/PdfAutoSigner.LocalApi/Middlewares/ExceptionHandlingMiddleware.cs b/PdfAutoSigner.LocalApi/Middlewares/ExceptionHandlingMiddleware.cs new file mode 100644 index 0000000..7a5ec36 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Middlewares/ExceptionHandlingMiddleware.cs @@ -0,0 +1,64 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using System.Net; +using System.Text.Json; + +namespace PdfAutoSigner.LocalApi.Middlewares +{ + /// + /// Based on https://jasonwatmore.com/post/2022/01/17/net-6-global-error-handler-tutorial-with-example and https://enlear.academy/global-exception-handling-in-net-6-16908fc8dc28 + /// + public class ExceptionHandlingMiddleware + { + private readonly RequestDelegate _next; + private readonly ILogger logger; + public ExceptionHandlingMiddleware(RequestDelegate next, ILogger logger) + { + _next = next; + this.logger = logger; + } + + public async Task InvokeAsync(HttpContext httpContext) + { + try + { + await _next(httpContext); + } + catch (Exception ex) + { + await HandleExceptionAsync(httpContext, ex); + } + } + private async Task HandleExceptionAsync(HttpContext context, Exception exception) + { + context.Response.ContentType = "application/json"; + var response = context.Response; + + switch (exception) + { + case ApplicationException ex: + response.StatusCode = (int)HttpStatusCode.BadRequest; + break; + case KeyNotFoundException ex: + response.StatusCode = (int)HttpStatusCode.NotFound; + break; + default: + response.StatusCode = (int)HttpStatusCode.InternalServerError; + break; + } + + logger.LogCritical(exception, "Critical exception."); + var result = JsonSerializer.Serialize(new { message = exception.Message}); + await context.Response.WriteAsync(result); + } + } +} diff --git a/PdfAutoSigner.LocalApi/Models/SignInputData.cs b/PdfAutoSigner.LocalApi/Models/SignInputData.cs new file mode 100644 index 0000000..f6ead11 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Models/SignInputData.cs @@ -0,0 +1,19 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +namespace PdfAutoSigner.LocalApi.Models +{ + public class SignInputData + { + public string? SignatureName { get; set; } + public string? Pin { get; set; } + } +} diff --git a/PdfAutoSigner.LocalApi/PdfAutoSigner.LocalApi.csproj b/PdfAutoSigner.LocalApi/PdfAutoSigner.LocalApi.csproj new file mode 100644 index 0000000..995d7a2 --- /dev/null +++ b/PdfAutoSigner.LocalApi/PdfAutoSigner.LocalApi.csproj @@ -0,0 +1,21 @@ + + + + net6.0 + enable + enable + AnyCPU + + + + + + + + + + + + + + diff --git a/PdfAutoSigner.LocalApi/Program.cs b/PdfAutoSigner.LocalApi/Program.cs new file mode 100644 index 0000000..579930d --- /dev/null +++ b/PdfAutoSigner.LocalApi/Program.cs @@ -0,0 +1,92 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using Microsoft.Extensions.Hosting.WindowsServices; +using PdfAutoSigner.Lib.Signatures; +using PdfAutoSigner.Lib.Signers; +using PdfAutoSigner.LocalApi.Config; +using PdfAutoSigner.LocalApi.Helpers; +using PdfAutoSigner.LocalApi.Middlewares; +using PdfAutoSigner.LocalApi.Services; +using System.Diagnostics; +using System.Reflection; + +//var options = new WebApplicationOptions +//{ +// Args = args, +// ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default +//}; +//var builder = WebApplication.CreateBuilder(options); +using var processModule = Process.GetCurrentProcess().MainModule; +var options = new WebApplicationOptions +{ + Args = args, + //ContentRootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + ContentRootPath = Path.GetDirectoryName(processModule?.FileName) +}; +var builder = WebApplication.CreateBuilder(options); + +// Add support to be able to run as Windows service or Linux \ Mac daemon +//builder.Host.UseWindowsService().UseSystemd(); + +// Add configuration settings +builder.Configuration.AddJsonFile("hostsettings.json", optional: true); +builder.Configuration.AddJsonFile("tokensettings.json", optional: true); + +// Enable logging to files +builder.Logging.AddLog4Net(); + +// Enable CORS +builder.Services.AddCors(options => +{ + options.AddDefaultPolicy(policy => + { + policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); + }); +}); + +// Add services to the container. +builder.Services.Configure(builder.Configuration.GetSection(TokenOptions.TokensConfigPath)); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddControllers(); + +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddHealthChecks(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +// DO NOT USE HTTPS - It will cause issues regarding missing certificates. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseAuthorization(); + +app.UseCors(); + +app.UseMiddleware(); + +app.MapControllers(); + +app.MapHealthChecks("/health"); + +app.Run(); diff --git a/PdfAutoSigner.LocalApi/Properties/launchSettings.json b/PdfAutoSigner.LocalApi/Properties/launchSettings.json new file mode 100644 index 0000000..0d1756f --- /dev/null +++ b/PdfAutoSigner.LocalApi/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:18831", + "sslPort": 0 + } + }, + "profiles": { + "PdfAutoSigner.LocalApi": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "weatherforecast", + "applicationUrl": "http://localhost:5082", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "weatherforecast", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/PdfAutoSigner.LocalApi/README.md b/PdfAutoSigner.LocalApi/README.md new file mode 100644 index 0000000..c2eab47 --- /dev/null +++ b/PdfAutoSigner.LocalApi/README.md @@ -0,0 +1,15 @@ +Publish as a self-contained app: +dotnet publish -c Release --self-contained -r win-x64 -p:PublishTrimmed=true -p:PublishSingleFile=true +dotnet publish -c Release --self-contained -r osx-x64 -p:PublishTrimmed=true -p:PublishSingleFile=true + +Run on mac: +- pkcs11 +./PdfAutoSigner.Lib.App ../hello.pdf ../hello-signed.pdf /usr/local/lib/libeTPkcs11.dylib -p [pin] +- cert +./PdfAutoSigner.Lib.App ./hello.pdf ./hello-signed.pdf certSign -p [pin] -c + +Run on win: +- pkcs11 +./PdfAutoSigner.Lib.App ./hello.pdf ./hello-signed.pdf "C:\Program Files (x86)\Gemalto\IDGo 800 PKCS#11\IDPrimePKCS1164.dll" -p [pin] +- cert +./PdfAutoSigner.Lib.App ./hello.pdf ./hello-signed.pdf certSign -p [pin] -c \ No newline at end of file diff --git a/PdfAutoSigner.LocalApi/SETTINGS.md b/PdfAutoSigner.LocalApi/SETTINGS.md new file mode 100644 index 0000000..222bde6 --- /dev/null +++ b/PdfAutoSigner.LocalApi/SETTINGS.md @@ -0,0 +1,57 @@ + +# Intro + +The PdfAutoSigner program supports PDF file signing via the following two approaches: +1. [PKCS#11](https://en.wikipedia.org/wiki/PKCS_11) (open standard that specifies an API for cryptographic devices) +2. [CryptoAPI](https://en.wikipedia.org/wiki/Microsoft_CryptoAPI) (Microsoft's proprietary cryptography subsystem) + +In order to sign a PDF file the user must choose a signature. +To help the user with selecting the correct signature, the program can list the available signatures that can be used. +To list the available signatures the program uses a json [configuration file](tokensettings.json) + +# Configuration file + +The configuration file has two sections called "Pkcs11Devices" (for the PKCS#11 mode) and "Certificates" (for the CryptoAPI mode). +The content for each of these sections is a list of entries. +Each entry will have a property called "Name" which is only used to identify the entry for the user (the Name is not used by the program). + +# PKCS#11 sction sample +```json +"Pkcs11Devices": [{ + "Name": "SafeNet", + "Pkcs11LibPaths": [{ + "OS": "Windows", + "Architecture": "X64", + "LibPath": "C:\\Program Files (x86)\\Gemalto\\IDGo 800 PKCS#11\\IDPrimePKCS1164.dll" + }] +}] +``` + +# PKCS#11 section description + +The PKCS#11 mode uses native libraries provided by the token manufacturers. +These libraries are installed on the user's system by the installer that comes with the hardware token. +The libraries and the paths where they are installed are different for combinations of OS and architecture. +For example: Windows 64 bit will have one path, while MacOS 64 bit will have another path. +The config file needs to specify the paths for all the libraries that will be used to sign PDF files. +As such the "Pkcs11Devices" will have a list of entries, one entry per device. +Each device entry will have another subsection called "Pkcs11LibPaths" containing a list of entries defining the library paths for that device on different OS - architecture combinations. +The program will use the corresponding library paths for the user's OS - architecture combination to identify the available devices that can be used to sign the PDF file. +Valid OS entries: Windows, MacOS and Linux. +Valid Architecture entries: X86 and X64. + + +# CryptoAPI section sample +```json +"Certificates": [{ + "Name": "CertSign", + "CertificateIssuerName": "certSIGN" +}] +``` + +# CryptoAPI section description + +The CryptoAPI mode uses certificates installed in the certificate store. +Due to the fact that there can be many certificates installed on user's machine the program uses the certificate issuer name to filter certificates that can be used to sign documents. +The "Certificates" section will have a list of entries and each entry has a "CertificateIssuerName" property. +Only the certificates that contain in their issuer name one of the specified certificate issuer names will be displayed to the user. \ No newline at end of file diff --git a/PdfAutoSigner.LocalApi/Services/ISignaturesProviderService.cs b/PdfAutoSigner.LocalApi/Services/ISignaturesProviderService.cs new file mode 100644 index 0000000..d990be9 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Services/ISignaturesProviderService.cs @@ -0,0 +1,20 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using PdfAutoSigner.Lib.Signatures; + +namespace PdfAutoSigner.LocalApi.Services +{ + public interface ISignaturesProviderService + { + List GetAvailableSignatures(); + } +} \ No newline at end of file diff --git a/PdfAutoSigner.LocalApi/Services/ISignerService.cs b/PdfAutoSigner.LocalApi/Services/ISignerService.cs new file mode 100644 index 0000000..e19d877 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Services/ISignerService.cs @@ -0,0 +1,20 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using PdfAutoSigner.Lib.Signatures; + +namespace PdfAutoSigner.LocalApi.Services +{ + public interface ISignerService + { + MemoryStream Sign(Stream inputStream, string signatureIdentifyingName, string pin); + } +} \ No newline at end of file diff --git a/PdfAutoSigner.LocalApi/Services/ITokenConfigService.cs b/PdfAutoSigner.LocalApi/Services/ITokenConfigService.cs new file mode 100644 index 0000000..143f158 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Services/ITokenConfigService.cs @@ -0,0 +1,19 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +namespace PdfAutoSigner.LocalApi.Services +{ + public interface ITokenConfigService + { + List GetIssuerNames(); + List GetPkcs11LibPathsByOS(); + } +} \ No newline at end of file diff --git a/PdfAutoSigner.LocalApi/Services/SignaturesProviderService.cs b/PdfAutoSigner.LocalApi/Services/SignaturesProviderService.cs new file mode 100644 index 0000000..df3cb71 --- /dev/null +++ b/PdfAutoSigner.LocalApi/Services/SignaturesProviderService.cs @@ -0,0 +1,42 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using PdfAutoSigner.Lib.Signatures; + +namespace PdfAutoSigner.LocalApi.Services +{ + public class SignaturesProviderService : ISignaturesProviderService + { + private ITokenConfigService tokenConfigService; + private ISignatureFactory signatureFactory; + + public SignaturesProviderService(ITokenConfigService tokenConfigService, ISignatureFactory signatureFactory) + { + this.tokenConfigService = tokenConfigService; + this.signatureFactory = signatureFactory; + } + + public List GetAvailableSignatures() + { + var availableSignatures = new List(); + + var pkcs11LibPaths = tokenConfigService.GetPkcs11LibPathsByOS(); + var availablePkcs11Signatures = signatureFactory.GetAvailablePkcs11Signatures(pkcs11LibPaths); + availableSignatures.AddRange(availablePkcs11Signatures); + + var certIssuerNames = tokenConfigService.GetIssuerNames(); + var availableCertSignatures = signatureFactory.GetAvailableX509Certificate2Signatures(certIssuerNames); + availableSignatures.AddRange(availableCertSignatures); + + return availableSignatures; + } + } +} diff --git a/PdfAutoSigner.LocalApi/Services/SignerService.cs b/PdfAutoSigner.LocalApi/Services/SignerService.cs new file mode 100644 index 0000000..1c40d1b --- /dev/null +++ b/PdfAutoSigner.LocalApi/Services/SignerService.cs @@ -0,0 +1,67 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using iText.Kernel.Geom; +using PdfAutoSigner.Lib.Signatures; +using PdfAutoSigner.Lib.Signers; + +namespace PdfAutoSigner.LocalApi.Services +{ + public class SignerService : ISignerService + { + private ISignaturesProviderService signaturesProviderService; + private IDocAutoSigner signer; + + public SignerService(ISignaturesProviderService signaturesProviderService, IDocAutoSigner signer) + { + this.signaturesProviderService = signaturesProviderService; + this.signer = signer; + } + + public MemoryStream Sign(Stream inputStream, string signatureIdentifyingName, string pin) + { + var availableSignatures = signaturesProviderService.GetAvailableSignatures(); + + var signature = availableSignatures.Find(s => s.GetSignatureIdentifyingName() == signatureIdentifyingName); + if (signature == null) + { + throw new ApplicationException($"Could not find a signature with identifying name {signatureIdentifyingName}."); + } + + try + { + signature = signature.Select(pin); + } + catch (Exception ex) + { + throw new ApplicationException($"Error accessing the signature {signature.GetSignatureIdentifyingName()} with the given pin.", ex); + } + + var signatureAppearance = CreateSignatureAppearanceDetails(); + var signedData = signer.Sign(inputStream, signature, signatureAppearance); + return signedData; + } + + private SignatureAppearanceDetails CreateSignatureAppearanceDetails() + { + var signatureApperance = new SignatureAppearanceDetails + { + Contact = "", + Reason = "", + Location = "", + PageNumber = 1, + Rectangle = new Rectangle(360, 60, 100, 40) + }; + + return signatureApperance; + } + } +} diff --git a/PdfAutoSigner.LocalApi/Services/TokenConfigService.cs b/PdfAutoSigner.LocalApi/Services/TokenConfigService.cs new file mode 100644 index 0000000..ec4f93a --- /dev/null +++ b/PdfAutoSigner.LocalApi/Services/TokenConfigService.cs @@ -0,0 +1,71 @@ +// PdfAutoSigner signs PDF files automatically using a hardware security module. +// Copyright (C) Plant An App +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY + +using Microsoft.Extensions.Options; +using PdfAutoSigner.LocalApi.Config; +using PdfAutoSigner.LocalApi.Helpers; +using System.Runtime.InteropServices; +using System.Text.Json; + +namespace PdfAutoSigner.LocalApi.Services +{ + public class TokenConfigService : ITokenConfigService + { + private readonly IOptionsSnapshot tokenOptionsSnapshot; + private readonly IOSHelper osHelper; + private readonly ILogger logger; + + public TokenConfigService(IOptionsSnapshot tokenOptionsSnapshot, IOSHelper osHelper, ILogger logger) + { + this.tokenOptionsSnapshot = tokenOptionsSnapshot; + this.osHelper = osHelper; + this.logger = logger; + } + + public List GetPkcs11LibPathsByOS() + { + var deviceDataList = tokenOptionsSnapshot.Value.Pkcs11Devices; + logger.LogInformation($"Found {deviceDataList.Count} pkcs11 devices in config file."); + + var os = osHelper.GetOS(); + if (os == null) + { + throw new SystemException("OS is not supported."); + } + + var architecture = osHelper.GetArchitecture(); + + var libPaths = + from device in deviceDataList + from osLibPath in device.Pkcs11LibPaths + where osLibPath.OS == os && osLibPath.Architecture == architecture + select osLibPath.LibPath; + + logger.LogInformation($"Found following library paths for current os and architecture in the config file: {string.Join("", libPaths)}"); + + return libPaths.ToList(); + } + + public List GetIssuerNames() + { + var certificateDataList = tokenOptionsSnapshot.Value.Certificates; + logger.LogInformation($"Found {certificateDataList.Count} certificates in config file."); + + var certificateIssuerNames = + from certificateData in certificateDataList + select certificateData.CertificateIssuerName; + + logger.LogInformation($"Found following certificates in the config file: {string.Join("", certificateIssuerNames)}"); + + return certificateIssuerNames.ToList(); + } + } +} diff --git a/PdfAutoSigner.LocalApi/appsettings.Development.json b/PdfAutoSigner.LocalApi/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/PdfAutoSigner.LocalApi/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/PdfAutoSigner.LocalApi/appsettings.json b/PdfAutoSigner.LocalApi/appsettings.json new file mode 100644 index 0000000..8235f40 --- /dev/null +++ b/PdfAutoSigner.LocalApi/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "AllowedOrigins": "http://localhost:9000;null;https://razvan-autosigner.apps.plantanapp.com;https://plantanapp.com" +} diff --git a/PdfAutoSigner.LocalApi/hostsettings.json b/PdfAutoSigner.LocalApi/hostsettings.json new file mode 100644 index 0000000..e5f4c1e --- /dev/null +++ b/PdfAutoSigner.LocalApi/hostsettings.json @@ -0,0 +1,3 @@ +{ + "urls": "http://localhost:7521" +} diff --git a/PdfAutoSigner.LocalApi/log4net.config b/PdfAutoSigner.LocalApi/log4net.config new file mode 100644 index 0000000..fbcab61 --- /dev/null +++ b/PdfAutoSigner.LocalApi/log4net.config @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/PdfAutoSigner.LocalApi/tokensettings.json b/PdfAutoSigner.LocalApi/tokensettings.json new file mode 100644 index 0000000..0c16829 --- /dev/null +++ b/PdfAutoSigner.LocalApi/tokensettings.json @@ -0,0 +1,37 @@ +{ + "TokensConfig": { + "Pkcs11Devices": [ + { + "Name": "SafeNet", + "Pkcs11LibPaths": [ + { + "OS": "Windows", + "Architecture": "X64", + "LibPath": "C:\\Program Files (x86)\\Gemalto\\IDGo 800 PKCS#11\\IDPrimePKCS1164.dll" + }, + { + "OS": "Windows", + "Architecture": "X86", + "LibPath": "C:\\Program Files (x86)\\Gemalto\\IDGo 800 PKCS#11\\IDPrimePKCS11.dll" + }, + { + "OS": "MacOS", + "Architecture": "X64", + "LibPath": "/usr/local/lib/libeTPkcs11.dylib" + }, + { + "OS": "MacOS", + "Architecture": "X86", + "LibPath": "/usr/local/lib/libeTPkcs11.dylib" + } + ] + } + ], + "Certificates": [ + { + "Name": "CertSign", + "CertificateIssuerName": "certSIGN" + } + ] + } +} \ No newline at end of file diff --git a/PdfAutoSigner.sln b/PdfAutoSigner.sln new file mode 100644 index 0000000..9baec83 --- /dev/null +++ b/PdfAutoSigner.sln @@ -0,0 +1,114 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32526.322 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DE864372-3EAB-4F5B-9B23-5870D5DEEB6A}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + .gitignore = .gitignore + azure-pipelines-installers.yml = azure-pipelines-installers.yml + EndProjectSection +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PdfAutoSigner.LocalApi", "PdfAutoSigner.LocalApi\PdfAutoSigner.LocalApi.csproj", "{AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PdfAutoSigner.Lib", "PdfAutoSigner.Lib\PdfAutoSigner.Lib.csproj", "{6B0A79A7-52DC-4923-BA39-B753F80744B4}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PdfAutoSigner.Lib.Tests", "PdfAutoSigner.Lib.Tests\PdfAutoSigner.Lib.Tests.csproj", "{EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PdfAutoSigner.Lib.App", "PdfAutoSigner.Lib.App\PdfAutoSigner.Lib.App.csproj", "{0ABDAD92-D6EE-4590-B71B-E6945223EDD3}" +EndProject +Project("{930C7802-8A8C-48F9-8165-68863BCCD9DD}") = "PdfAutoSigner.LocalApi.Installer", "PdfAutoSigner.LocalApi.Installer\PdfAutoSigner.LocalApi.Installer.wixproj", "{242F7161-3A21-49FB-96DF-0B0DC81A40A0}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PdfAutoSigner.LocalApi.Tests", "PdfAutoSigner.LocalApi.Tests\PdfAutoSigner.LocalApi.Tests.csproj", "{1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}.Debug|x64.ActiveCfg = Debug|Any CPU + {AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}.Debug|x64.Build.0 = Debug|Any CPU + {AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}.Debug|x86.ActiveCfg = Debug|Any CPU + {AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}.Debug|x86.Build.0 = Debug|Any CPU + {AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}.Release|Any CPU.Build.0 = Release|Any CPU + {AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}.Release|x64.ActiveCfg = Release|Any CPU + {AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}.Release|x64.Build.0 = Release|Any CPU + {AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}.Release|x86.ActiveCfg = Release|Any CPU + {AC02EDFD-EA1E-4CE5-AE0B-A51EDA689740}.Release|x86.Build.0 = Release|Any CPU + {6B0A79A7-52DC-4923-BA39-B753F80744B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6B0A79A7-52DC-4923-BA39-B753F80744B4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6B0A79A7-52DC-4923-BA39-B753F80744B4}.Debug|x64.ActiveCfg = Debug|Any CPU + {6B0A79A7-52DC-4923-BA39-B753F80744B4}.Debug|x64.Build.0 = Debug|Any CPU + {6B0A79A7-52DC-4923-BA39-B753F80744B4}.Debug|x86.ActiveCfg = Debug|Any CPU + {6B0A79A7-52DC-4923-BA39-B753F80744B4}.Debug|x86.Build.0 = Debug|Any CPU + {6B0A79A7-52DC-4923-BA39-B753F80744B4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6B0A79A7-52DC-4923-BA39-B753F80744B4}.Release|Any CPU.Build.0 = Release|Any CPU + {6B0A79A7-52DC-4923-BA39-B753F80744B4}.Release|x64.ActiveCfg = Release|Any CPU + {6B0A79A7-52DC-4923-BA39-B753F80744B4}.Release|x64.Build.0 = Release|Any CPU + {6B0A79A7-52DC-4923-BA39-B753F80744B4}.Release|x86.ActiveCfg = Release|Any CPU + {6B0A79A7-52DC-4923-BA39-B753F80744B4}.Release|x86.Build.0 = Release|Any CPU + {EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}.Debug|x64.ActiveCfg = Debug|Any CPU + {EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}.Debug|x64.Build.0 = Debug|Any CPU + {EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}.Debug|x86.ActiveCfg = Debug|Any CPU + {EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}.Debug|x86.Build.0 = Debug|Any CPU + {EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}.Release|Any CPU.Build.0 = Release|Any CPU + {EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}.Release|x64.ActiveCfg = Release|Any CPU + {EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}.Release|x64.Build.0 = Release|Any CPU + {EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}.Release|x86.ActiveCfg = Release|Any CPU + {EA7C9FBA-8A44-4ABB-8E8B-455554E2195B}.Release|x86.Build.0 = Release|Any CPU + {0ABDAD92-D6EE-4590-B71B-E6945223EDD3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0ABDAD92-D6EE-4590-B71B-E6945223EDD3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0ABDAD92-D6EE-4590-B71B-E6945223EDD3}.Debug|x64.ActiveCfg = Debug|Any CPU + {0ABDAD92-D6EE-4590-B71B-E6945223EDD3}.Debug|x64.Build.0 = Debug|Any CPU + {0ABDAD92-D6EE-4590-B71B-E6945223EDD3}.Debug|x86.ActiveCfg = Debug|Any CPU + {0ABDAD92-D6EE-4590-B71B-E6945223EDD3}.Debug|x86.Build.0 = Debug|Any CPU + {0ABDAD92-D6EE-4590-B71B-E6945223EDD3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0ABDAD92-D6EE-4590-B71B-E6945223EDD3}.Release|Any CPU.Build.0 = Release|Any CPU + {0ABDAD92-D6EE-4590-B71B-E6945223EDD3}.Release|x64.ActiveCfg = Release|Any CPU + {0ABDAD92-D6EE-4590-B71B-E6945223EDD3}.Release|x64.Build.0 = Release|Any CPU + {0ABDAD92-D6EE-4590-B71B-E6945223EDD3}.Release|x86.ActiveCfg = Release|Any CPU + {0ABDAD92-D6EE-4590-B71B-E6945223EDD3}.Release|x86.Build.0 = Release|Any CPU + {242F7161-3A21-49FB-96DF-0B0DC81A40A0}.Debug|Any CPU.ActiveCfg = Debug|x64 + {242F7161-3A21-49FB-96DF-0B0DC81A40A0}.Debug|Any CPU.Build.0 = Debug|x64 + {242F7161-3A21-49FB-96DF-0B0DC81A40A0}.Debug|x64.ActiveCfg = Debug|x64 + {242F7161-3A21-49FB-96DF-0B0DC81A40A0}.Debug|x64.Build.0 = Debug|x64 + {242F7161-3A21-49FB-96DF-0B0DC81A40A0}.Debug|x86.ActiveCfg = Debug|x86 + {242F7161-3A21-49FB-96DF-0B0DC81A40A0}.Debug|x86.Build.0 = Debug|x86 + {242F7161-3A21-49FB-96DF-0B0DC81A40A0}.Release|Any CPU.ActiveCfg = Release|x64 + {242F7161-3A21-49FB-96DF-0B0DC81A40A0}.Release|Any CPU.Build.0 = Release|x64 + {242F7161-3A21-49FB-96DF-0B0DC81A40A0}.Release|x64.ActiveCfg = Release|x64 + {242F7161-3A21-49FB-96DF-0B0DC81A40A0}.Release|x64.Build.0 = Release|x64 + {242F7161-3A21-49FB-96DF-0B0DC81A40A0}.Release|x86.ActiveCfg = Release|x86 + {242F7161-3A21-49FB-96DF-0B0DC81A40A0}.Release|x86.Build.0 = Release|x86 + {1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}.Debug|x64.ActiveCfg = Debug|Any CPU + {1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}.Debug|x64.Build.0 = Debug|Any CPU + {1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}.Debug|x86.ActiveCfg = Debug|Any CPU + {1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}.Debug|x86.Build.0 = Debug|Any CPU + {1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}.Release|Any CPU.Build.0 = Release|Any CPU + {1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}.Release|x64.ActiveCfg = Release|Any CPU + {1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}.Release|x64.Build.0 = Release|Any CPU + {1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}.Release|x86.ActiveCfg = Release|Any CPU + {1FD19FC0-D7A9-48AA-B443-A6F7C1A4AFF2}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {9C438A9C-857E-4B0D-9BD0-C3DA2E2F0A17} + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md deleted file mode 100644 index 8b13789..0000000 --- a/README.md +++ /dev/null @@ -1 +0,0 @@ - diff --git a/azure-pipelines-installers.yml b/azure-pipelines-installers.yml new file mode 100644 index 0000000..1bdca7a --- /dev/null +++ b/azure-pipelines-installers.yml @@ -0,0 +1,119 @@ +# Starter pipeline +# Start with a minimal pipeline that you can customize to build and deploy your code. +# Add steps that build, run tests, deploy, and more: +# https://aka.ms/yaml + +trigger: none + +jobs: + - job: WindowsInstallers + displayName: Creates the Windows 32 bit and 64 bit installers + pool: + vmImage: 'windows-latest' + variables: + solution: './PdfAutoSigner.sln' + winInstallerProject: './PdfAutoSigner.LocalApi.Installer/PdfAutoSigner.LocalApi.Installer.wixproj' + buildConfiguration: 'Release' + strategy: + matrix: + x86: + buildPlatform: 'x86' + x64: + buildPlatform: 'x64' + steps: + - task: NuGetToolInstaller@1 + + - task: NuGetCommand@2 + inputs: + restoreSolution: '$(solution)' + + - task: VSBuild@1 + inputs: + solution: '$(winInstallerProject)' + platform: '$(buildPlatform)' + configuration: '$(buildConfiguration)' + clean: true + + - task: DotNetCoreCLI@2 + displayName: Test + inputs: + command: test + projects: '**/*[Tt]ests/*.csproj' + arguments: '--configuration $(buildConfiguration)' + + - task: CopyFiles@2 + inputs: + sourceFolder: '$(Build.SourcesDirectory)/PdfAutoSigner.LocalApi.Installer/bin/$(buildConfiguration)' + Contents: '**\*.msi' + targetFolder: '$(Build.ArtifactStagingDirectory)' + + - task: PublishPipelineArtifact@1 + inputs: + targetPath: '$(Build.ArtifactStagingDirectory)' + artifact: 'PdfAutoSigner-$(buildConfiguration)-win-$(buildPlatform)' + publishLocation: 'pipeline' + + - job: MacOSPackage + displayName: Creates the MacOS 64 bit installer + pool: + vmImage: 'macOS-latest' + variables: + solution: './PdfAutoSigner.sln' + buildProject: './PdfAutoSigner.LocalApi/PdfAutoSigner.LocalApi.csproj' + buildConfiguration: 'Release' + buildPlatform: 'x64' + steps: + - task: UseDotNet@2 + displayName: Install .NET Core 6 + inputs: + packageType: 'sdk' + version: '6.0.300' + + - task: NuGetToolInstaller@1 + + - task: NuGetCommand@2 + inputs: + restoreSolution: '$(buildProject)' + + - task: DotNetCoreCLI@2 + displayName: 'Build project' + inputs: + command: 'publish' + projects: '$(buildProject)' + arguments: '-c $(buildConfiguration) -r osx-$(buildPlatform) --self-contained -p:PublishSingleFile=true' + zipAfterPublish: false + + - task: DotNetCoreCLI@2 + displayName: Test + inputs: + command: test + projects: '**/*[Tt]ests/*.csproj' + arguments: '--configuration $(buildConfiguration)' + + - task: CopyFiles@2 + displayName: 'Copy the publish folder' + inputs: + sourceFolder: '$(Build.SourcesDirectory)/PdfAutoSigner.LocalApi/bin/$(buildConfiguration)' + Contents: '**/publish/*' + targetFolder: '$(Build.SourcesDirectory)/osx_package/publish' + CleanTargetFolder: true + OverWrite: true + flattenFolders: true + + - task: ShellScript@2 + displayName: 'Build osx package' + inputs: + scriptPath: '$(Build.SourcesDirectory)/osx_package/build.sh' + + - task: CopyFiles@2 + displayName: 'Copy the osx package to the staging directory' + inputs: + sourceFolder: '$(Build.SourcesDirectory)/osx_package' + Contents: '**/PdfAutoSigner.pkg' + targetFolder: '$(Build.ArtifactStagingDirectory)' + + - task: PublishPipelineArtifact@1 + inputs: + targetPath: '$(Build.ArtifactStagingDirectory)' + artifact: 'PdfAutoSigner-$(buildConfiguration)-osx-$(buildPlatform)' + publishLocation: 'pipeline' \ No newline at end of file diff --git a/azure-pipelines.yml b/azure-pipelines.yml new file mode 100644 index 0000000..e763f2b --- /dev/null +++ b/azure-pipelines.yml @@ -0,0 +1,41 @@ +# ASP.NET + +# Build and test ASP.NET projects. +# Add steps that publish symbols, save build artifacts, deploy, and more: +# https://docs.microsoft.com/azure/devops/pipelines/apps/aspnet/build-aspnet-4 + +trigger: +- main + +pool: + vmImage: 'windows-latest' + +variables: + solution: '**/*.sln' + buildPlatform: 'Any CPU' + buildConfiguration: 'Release' + +steps: +- task: NuGetToolInstaller@1 + +- task: NuGetCommand@2 + inputs: + restoreSolution: '$(solution)' + +- task: VSBuild@1 + inputs: + solution: '$(solution)' + msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"' + platform: '$(buildPlatform)' + configuration: '$(buildConfiguration)' + +- task: VSTest@2 + inputs: + platform: '$(buildPlatform)' + configuration: '$(buildConfiguration)' + +- task: PublishBuildArtifacts@1 + inputs: + PathtoPublish: '$(Build.ArtifactStagingDirectory)' + ArtifactName: 'drop' + publishLocation: 'Container' \ No newline at end of file diff --git a/license.rtf b/license.rtf new file mode 100644 index 0000000..5a720fc --- /dev/null +++ b/license.rtf @@ -0,0 +1,663 @@ +{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}} +{\colortbl ;\red0\green0\blue255;} +{\*\generator Riched20 10.0.19041}\viewkind4\uc1 +\pard\sl240\slmult1\b\f0\fs28\lang9 AGPL licensing:\b0\fs22\par +This program is free software: you can redistribute it and/or modify\par +it under the terms of the GNU Affero General Public License as published by\par +the Free Software Foundation, either version 3 of the License, or\par +(at your option) any later version.\par +\par +This program is distributed in the hope that it will be useful,\par +but WITHOUT ANY WARRANTY; without even the implied warranty of\par +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\par +GNU Affero General Public License for more details.\par +\par +You should have received a copy of the GNU Affero General Public License\par +along with this program. If not, see <{{\field{\*\fldinst{HYPERLINK "https://www.gnu.org/licenses/"}}{\fldrslt{https://www.gnu.org/licenses/\ul0\cf0}}}}\f0\fs22 >.\par +\par +\par +\b\fs28 Source code:\b0\fs22\par +The source code for this program is available at \par +{{\field{\*\fldinst{HYPERLINK https://github.com/dnnsharp/PlantAnApp.PdfAutoSigner }}{\fldrslt{https://github.com/dnnsharp/PlantAnApp.PdfAutoSigner\ul0\cf0}}}}\f0\fs22\par +or\par +{{\field{\*\fldinst{HYPERLINK https://github.com/razvanionapp/PlantAnApp.PdfAutoSigner }}{\fldrslt{https://github.com/razvanionapp/PlantAnApp.PdfAutoSigner\ul0\cf0}}}}\f0\fs22\par +\par +\par +\b\fs28 Third party content:\b0\fs22\par +This program includes items that have been sourced from third parties as set out below:\par +\par +\b\fs24 iText\par +\b0\fs22 We are using iText library to manipulate pdf files. This library was released by iText under a commercial and under an AGPL license. We are using the library under the AGPL license.\par +For more details see:\par +{{\field{\*\fldinst{HYPERLINK https://itextpdf.com/en/how-buy/agpl-license }}{\fldrslt{https://itextpdf.com/en/how-buy/agpl-license\ul0\cf0}}}}\f0\fs22\par +{{\field{\*\fldinst{HYPERLINK https://itextpdf.com/en/how-buy/legal/copyright-intellectual-property#:~:text=Copyright%20and%20IP%20Statement,signing%20a%20Contributor%20License%20Agreement }}{\fldrslt{https://itextpdf.com/en/how-buy/legal/copyright-intellectual-property#:~:text=Copyright%20and%20IP%20Statement,signing%20a%20Contributor%20License%20Agreement\ul0\cf0}}}}\f0\fs22\par +\par +\b\fs24 Wix toolset\b0\fs22\par +We are using Wix toolset to create the Windows installers. The Wix toolset is released under the Microsoft Reciprocal License (MS-RL).\par +For more details see:\par +{{\field{\*\fldinst{HYPERLINK https://wixtoolset.org/about/license/ }}{\fldrslt{https://wixtoolset.org/about/license/\ul0\cf0}}}}\b\f0\fs28\par +\par +\par +Full text of GNU Affero General Public License:\b0\fs22\par +\par + GNU AFFERO GENERAL PUBLIC LICENSE\par + Version 3, 19 November 2007\par +\par + Copyright (C) 2007 Free Software Foundation, Inc. <{{\field{\*\fldinst{HYPERLINK "https://fsf.org/"}}{\fldrslt{https://fsf.org/\ul0\cf0}}}}\f0\fs22 >\par + Everyone is permitted to copy and distribute verbatim copies\par + of this license document, but changing it is not allowed.\par +\par + Preamble\par +\par + The GNU Affero General Public License is a free, copyleft license for\par +software and other kinds of works, specifically designed to ensure\par +cooperation with the community in the case of network server software.\par +\par + The licenses for most software and other practical works are designed\par +to take away your freedom to share and change the works. By contrast,\par +our General Public Licenses are intended to guarantee your freedom to\par +share and change all versions of a program--to make sure it remains free\par +software for all its users.\par +\par + When we speak of free software, we are referring to freedom, not\par +price. Our General Public Licenses are designed to make sure that you\par +have the freedom to distribute copies of free software (and charge for\par +them if you wish), that you receive source code or can get it if you\par +want it, that you can change the software or use pieces of it in new\par +free programs, and that you know you can do these things.\par +\par + Developers that use our General Public Licenses protect your rights\par +with two steps: (1) assert copyright on the software, and (2) offer\par +you this License which gives you legal permission to copy, distribute\par +and/or modify the software.\par +\par + A secondary benefit of defending all users' freedom is that\par +improvements made in alternate versions of the program, if they\par +receive widespread use, become available for other developers to\par +incorporate. Many developers of free software are heartened and\par +encouraged by the resulting cooperation. However, in the case of\par +software used on network servers, this result may fail to come about.\par +The GNU General Public License permits making a modified version and\par +letting the public access it on a server without ever releasing its\par +source code to the public.\par +\par + The GNU Affero General Public License is designed specifically to\par +ensure that, in such cases, the modified source code becomes available\par +to the community. It requires the operator of a network server to\par +provide the source code of the modified version running there to the\par +users of that server. Therefore, public use of a modified version, on\par +a publicly accessible server, gives the public access to the source\par +code of the modified version.\par +\par + An older license, called the Affero General Public License and\par +published by Affero, was designed to accomplish similar goals. This is\par +a different license, not a version of the Affero GPL, but Affero has\par +released a new version of the Affero GPL which permits relicensing under\par +this license.\par +\par + The precise terms and conditions for copying, distribution and\par +modification follow.\par +\par + TERMS AND CONDITIONS\par +\par + 0. Definitions.\par +\par + "This License" refers to version 3 of the GNU Affero General Public License.\par +\par + "Copyright" also means copyright-like laws that apply to other kinds of\par +works, such as semiconductor masks.\par +\par + "The Program" refers to any copyrightable work licensed under this\par +License. Each licensee is addressed as "you". "Licensees" and\par +"recipients" may be individuals or organizations.\par +\par + To "modify" a work means to copy from or adapt all or part of the work\par +in a fashion requiring copyright permission, other than the making of an\par +exact copy. The resulting work is called a "modified version" of the\par +earlier work or a work "based on" the earlier work.\par +\par + A "covered work" means either the unmodified Program or a work based\par +on the Program.\par +\par + To "propagate" a work means to do anything with it that, without\par +permission, would make you directly or secondarily liable for\par +infringement under applicable copyright law, except executing it on a\par +computer or modifying a private copy. Propagation includes copying,\par +distribution (with or without modification), making available to the\par +public, and in some countries other activities as well.\par +\par + To "convey" a work means any kind of propagation that enables other\par +parties to make or receive copies. Mere interaction with a user through\par +a computer network, with no transfer of a copy, is not conveying.\par +\par + An interactive user interface displays "Appropriate Legal Notices"\par +to the extent that it includes a convenient and prominently visible\par +feature that (1) displays an appropriate copyright notice, and (2)\par +tells the user that there is no warranty for the work (except to the\par +extent that warranties are provided), that licensees may convey the\par +work under this License, and how to view a copy of this License. If\par +the interface presents a list of user commands or options, such as a\par +menu, a prominent item in the list meets this criterion.\par +\par + 1. Source Code.\par +\par + The "source code" for a work means the preferred form of the work\par +for making modifications to it. "Object code" means any non-source\par +form of a work.\par +\par + A "Standard Interface" means an interface that either is an official\par +standard defined by a recognized standards body, or, in the case of\par +interfaces specified for a particular programming language, one that\par +is widely used among developers working in that language.\par +\par + The "System Libraries" of an executable work include anything, other\par +than the work as a whole, that (a) is included in the normal form of\par +packaging a Major Component, but which is not part of that Major\par +Component, and (b) serves only to enable use of the work with that\par +Major Component, or to implement a Standard Interface for which an\par +implementation is available to the public in source code form. A\par +"Major Component", in this context, means a major essential component\par +(kernel, window system, and so on) of the specific operating system\par +(if any) on which the executable work runs, or a compiler used to\par +produce the work, or an object code interpreter used to run it.\par +\par + The "Corresponding Source" for a work in object code form means all\par +the source code needed to generate, install, and (for an executable\par +work) run the object code and to modify the work, including scripts to\par +control those activities. However, it does not include the work's\par +System Libraries, or general-purpose tools or generally available free\par +programs which are used unmodified in performing those activities but\par +which are not part of the work. For example, Corresponding Source\par +includes interface definition files associated with source files for\par +the work, and the source code for shared libraries and dynamically\par +linked subprograms that the work is specifically designed to require,\par +such as by intimate data communication or control flow between those\par +subprograms and other parts of the work.\par +\par + The Corresponding Source need not include anything that users\par +can regenerate automatically from other parts of the Corresponding\par +Source.\par +\par + The Corresponding Source for a work in source code form is that\par +same work.\par +\par + 2. Basic Permissions.\par +\par + All rights granted under this License are granted for the term of\par +copyright on the Program, and are irrevocable provided the stated\par +conditions are met. This License explicitly affirms your unlimited\par +permission to run the unmodified Program. The output from running a\par +covered work is covered by this License only if the output, given its\par +content, constitutes a covered work. This License acknowledges your\par +rights of fair use or other equivalent, as provided by copyright law.\par +\par + You may make, run and propagate covered works that you do not\par +convey, without conditions so long as your license otherwise remains\par +in force. You may convey covered works to others for the sole purpose\par +of having them make modifications exclusively for you, or provide you\par +with facilities for running those works, provided that you comply with\par +the terms of this License in conveying all material for which you do\par +not control copyright. Those thus making or running the covered works\par +for you must do so exclusively on your behalf, under your direction\par +and control, on terms that prohibit them from making any copies of\par +your copyrighted material outside their relationship with you.\par +\par + Conveying under any other circumstances is permitted solely under\par +the conditions stated below. Sublicensing is not allowed; section 10\par +makes it unnecessary.\par +\par + 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\par +\par + No covered work shall be deemed part of an effective technological\par +measure under any applicable law fulfilling obligations under article\par +11 of the WIPO copyright treaty adopted on 20 December 1996, or\par +similar laws prohibiting or restricting circumvention of such\par +measures.\par +\par + When you convey a covered work, you waive any legal power to forbid\par +circumvention of technological measures to the extent such circumvention\par +is effected by exercising rights under this License with respect to\par +the covered work, and you disclaim any intention to limit operation or\par +modification of the work as a means of enforcing, against the work's\par +users, your or third parties' legal rights to forbid circumvention of\par +technological measures.\par +\par + 4. Conveying Verbatim Copies.\par +\par + You may convey verbatim copies of the Program's source code as you\par +receive it, in any medium, provided that you conspicuously and\par +appropriately publish on each copy an appropriate copyright notice;\par +keep intact all notices stating that this License and any\par +non-permissive terms added in accord with section 7 apply to the code;\par +keep intact all notices of the absence of any warranty; and give all\par +recipients a copy of this License along with the Program.\par +\par + You may charge any price or no price for each copy that you convey,\par +and you may offer support or warranty protection for a fee.\par +\par + 5. Conveying Modified Source Versions.\par +\par + You may convey a work based on the Program, or the modifications to\par +produce it from the Program, in the form of source code under the\par +terms of section 4, provided that you also meet all of these conditions:\par +\par + a) The work must carry prominent notices stating that you modified\par + it, and giving a relevant date.\par +\par + b) The work must carry prominent notices stating that it is\par + released under this License and any conditions added under section\par + 7. This requirement modifies the requirement in section 4 to\par + "keep intact all notices".\par +\par + c) You must license the entire work, as a whole, under this\par + License to anyone who comes into possession of a copy. This\par + License will therefore apply, along with any applicable section 7\par + additional terms, to the whole of the work, and all its parts,\par + regardless of how they are packaged. This License gives no\par + permission to license the work in any other way, but it does not\par + invalidate such permission if you have separately received it.\par +\par + d) If the work has interactive user interfaces, each must display\par + Appropriate Legal Notices; however, if the Program has interactive\par + interfaces that do not display Appropriate Legal Notices, your\par + work need not make them do so.\par +\par + A compilation of a covered work with other separate and independent\par +works, which are not by their nature extensions of the covered work,\par +and which are not combined with it such as to form a larger program,\par +in or on a volume of a storage or distribution medium, is called an\par +"aggregate" if the compilation and its resulting copyright are not\par +used to limit the access or legal rights of the compilation's users\par +beyond what the individual works permit. Inclusion of a covered work\par +in an aggregate does not cause this License to apply to the other\par +parts of the aggregate.\par +\par + 6. Conveying Non-Source Forms.\par +\par + You may convey a covered work in object code form under the terms\par +of sections 4 and 5, provided that you also convey the\par +machine-readable Corresponding Source under the terms of this License,\par +in one of these ways:\par +\par + a) Convey the object code in, or embodied in, a physical product\par + (including a physical distribution medium), accompanied by the\par + Corresponding Source fixed on a durable physical medium\par + customarily used for software interchange.\par +\par + b) Convey the object code in, or embodied in, a physical product\par + (including a physical distribution medium), accompanied by a\par + written offer, valid for at least three years and valid for as\par + long as you offer spare parts or customer support for that product\par + model, to give anyone who possesses the object code either (1) a\par + copy of the Corresponding Source for all the software in the\par + product that is covered by this License, on a durable physical\par + medium customarily used for software interchange, for a price no\par + more than your reasonable cost of physically performing this\par + conveying of source, or (2) access to copy the\par + Corresponding Source from a network server at no charge.\par +\par + c) Convey individual copies of the object code with a copy of the\par + written offer to provide the Corresponding Source. This\par + alternative is allowed only occasionally and noncommercially, and\par + only if you received the object code with such an offer, in accord\par + with subsection 6b.\par +\par + d) Convey the object code by offering access from a designated\par + place (gratis or for a charge), and offer equivalent access to the\par + Corresponding Source in the same way through the same place at no\par + further charge. You need not require recipients to copy the\par + Corresponding Source along with the object code. If the place to\par + copy the object code is a network server, the Corresponding Source\par + may be on a different server (operated by you or a third party)\par + that supports equivalent copying facilities, provided you maintain\par + clear directions next to the object code saying where to find the\par + Corresponding Source. Regardless of what server hosts the\par + Corresponding Source, you remain obligated to ensure that it is\par + available for as long as needed to satisfy these requirements.\par +\par + e) Convey the object code using peer-to-peer transmission, provided\par + you inform other peers where the object code and Corresponding\par + Source of the work are being offered to the general public at no\par + charge under subsection 6d.\par +\par + A separable portion of the object code, whose source code is excluded\par +from the Corresponding Source as a System Library, need not be\par +included in conveying the object code work.\par +\par + A "User Product" is either (1) a "consumer product", which means any\par +tangible personal property which is normally used for personal, family,\par +or household purposes, or (2) anything designed or sold for incorporation\par +into a dwelling. In determining whether a product is a consumer product,\par +doubtful cases shall be resolved in favor of coverage. For a particular\par +product received by a particular user, "normally used" refers to a\par +typical or common use of that class of product, regardless of the status\par +of the particular user or of the way in which the particular user\par +actually uses, or expects or is expected to use, the product. A product\par +is a consumer product regardless of whether the product has substantial\par +commercial, industrial or non-consumer uses, unless such uses represent\par +the only significant mode of use of the product.\par +\par + "Installation Information" for a User Product means any methods,\par +procedures, authorization keys, or other information required to install\par +and execute modified versions of a covered work in that User Product from\par +a modified version of its Corresponding Source. The information must\par +suffice to ensure that the continued functioning of the modified object\par +code is in no case prevented or interfered with solely because\par +modification has been made.\par +\par + If you convey an object code work under this section in, or with, or\par +specifically for use in, a User Product, and the conveying occurs as\par +part of a transaction in which the right of possession and use of the\par +User Product is transferred to the recipient in perpetuity or for a\par +fixed term (regardless of how the transaction is characterized), the\par +Corresponding Source conveyed under this section must be accompanied\par +by the Installation Information. But this requirement does not apply\par +if neither you nor any third party retains the ability to install\par +modified object code on the User Product (for example, the work has\par +been installed in ROM).\par +\par + The requirement to provide Installation Information does not include a\par +requirement to continue to provide support service, warranty, or updates\par +for a work that has been modified or installed by the recipient, or for\par +the User Product in which it has been modified or installed. Access to a\par +network may be denied when the modification itself materially and\par +adversely affects the operation of the network or violates the rules and\par +protocols for communication across the network.\par +\par + Corresponding Source conveyed, and Installation Information provided,\par +in accord with this section must be in a format that is publicly\par +documented (and with an implementation available to the public in\par +source code form), and must require no special password or key for\par +unpacking, reading or copying.\par +\par + 7. Additional Terms.\par +\par + "Additional permissions" are terms that supplement the terms of this\par +License by making exceptions from one or more of its conditions.\par +Additional permissions that are applicable to the entire Program shall\par +be treated as though they were included in this License, to the extent\par +that they are valid under applicable law. If additional permissions\par +apply only to part of the Program, that part may be used separately\par +under those permissions, but the entire Program remains governed by\par +this License without regard to the additional permissions.\par +\par + When you convey a copy of a covered work, you may at your option\par +remove any additional permissions from that copy, or from any part of\par +it. (Additional permissions may be written to require their own\par +removal in certain cases when you modify the work.) You may place\par +additional permissions on material, added by you to a covered work,\par +for which you have or can give appropriate copyright permission.\par +\par + Notwithstanding any other provision of this License, for material you\par +add to a covered work, you may (if authorized by the copyright holders of\par +that material) supplement the terms of this License with terms:\par +\par + a) Disclaiming warranty or limiting liability differently from the\par + terms of sections 15 and 16 of this License; or\par +\par + b) Requiring preservation of specified reasonable legal notices or\par + author attributions in that material or in the Appropriate Legal\par + Notices displayed by works containing it; or\par +\par + c) Prohibiting misrepresentation of the origin of that material, or\par + requiring that modified versions of such material be marked in\par + reasonable ways as different from the original version; or\par +\par + d) Limiting the use for publicity purposes of names of licensors or\par + authors of the material; or\par +\par + e) Declining to grant rights under trademark law for use of some\par + trade names, trademarks, or service marks; or\par +\par + f) Requiring indemnification of licensors and authors of that\par + material by anyone who conveys the material (or modified versions of\par + it) with contractual assumptions of liability to the recipient, for\par + any liability that these contractual assumptions directly impose on\par + those licensors and authors.\par +\par + All other non-permissive additional terms are considered "further\par +restrictions" within the meaning of section 10. If the Program as you\par +received it, or any part of it, contains a notice stating that it is\par +governed by this License along with a term that is a further\par +restriction, you may remove that term. If a license document contains\par +a further restriction but permits relicensing or conveying under this\par +License, you may add to a covered work material governed by the terms\par +of that license document, provided that the further restriction does\par +not survive such relicensing or conveying.\par +\par + If you add terms to a covered work in accord with this section, you\par +must place, in the relevant source files, a statement of the\par +additional terms that apply to those files, or a notice indicating\par +where to find the applicable terms.\par +\par + Additional terms, permissive or non-permissive, may be stated in the\par +form of a separately written license, or stated as exceptions;\par +the above requirements apply either way.\par +\par + 8. Termination.\par +\par + You may not propagate or modify a covered work except as expressly\par +provided under this License. Any attempt otherwise to propagate or\par +modify it is void, and will automatically terminate your rights under\par +this License (including any patent licenses granted under the third\par +paragraph of section 11).\par +\par + However, if you cease all violation of this License, then your\par +license from a particular copyright holder is reinstated (a)\par +provisionally, unless and until the copyright holder explicitly and\par +finally terminates your license, and (b) permanently, if the copyright\par +holder fails to notify you of the violation by some reasonable means\par +prior to 60 days after the cessation.\par +\par + Moreover, your license from a particular copyright holder is\par +reinstated permanently if the copyright holder notifies you of the\par +violation by some reasonable means, this is the first time you have\par +received notice of violation of this License (for any work) from that\par +copyright holder, and you cure the violation prior to 30 days after\par +your receipt of the notice.\par +\par + Termination of your rights under this section does not terminate the\par +licenses of parties who have received copies or rights from you under\par +this License. If your rights have been terminated and not permanently\par +reinstated, you do not qualify to receive new licenses for the same\par +material under section 10.\par +\par + 9. Acceptance Not Required for Having Copies.\par +\par + You are not required to accept this License in order to receive or\par +run a copy of the Program. Ancillary propagation of a covered work\par +occurring solely as a consequence of using peer-to-peer transmission\par +to receive a copy likewise does not require acceptance. However,\par +nothing other than this License grants you permission to propagate or\par +modify any covered work. These actions infringe copyright if you do\par +not accept this License. Therefore, by modifying or propagating a\par +covered work, you indicate your acceptance of this License to do so.\par +\par + 10. Automatic Licensing of Downstream Recipients.\par +\par + Each time you convey a covered work, the recipient automatically\par +receives a license from the original licensors, to run, modify and\par +propagate that work, subject to this License. You are not responsible\par +for enforcing compliance by third parties with this License.\par +\par + An "entity transaction" is a transaction transferring control of an\par +organization, or substantially all assets of one, or subdividing an\par +organization, or merging organizations. If propagation of a covered\par +work results from an entity transaction, each party to that\par +transaction who receives a copy of the work also receives whatever\par +licenses to the work the party's predecessor in interest had or could\par +give under the previous paragraph, plus a right to possession of the\par +Corresponding Source of the work from the predecessor in interest, if\par +the predecessor has it or can get it with reasonable efforts.\par +\par + You may not impose any further restrictions on the exercise of the\par +rights granted or affirmed under this License. For example, you may\par +not impose a license fee, royalty, or other charge for exercise of\par +rights granted under this License, and you may not initiate litigation\par +(including a cross-claim or counterclaim in a lawsuit) alleging that\par +any patent claim is infringed by making, using, selling, offering for\par +sale, or importing the Program or any portion of it.\par +\par + 11. Patents.\par +\par + A "contributor" is a copyright holder who authorizes use under this\par +License of the Program or a work on which the Program is based. The\par +work thus licensed is called the contributor's "contributor version".\par +\par + A contributor's "essential patent claims" are all patent claims\par +owned or controlled by the contributor, whether already acquired or\par +hereafter acquired, that would be infringed by some manner, permitted\par +by this License, of making, using, or selling its contributor version,\par +but do not include claims that would be infringed only as a\par +consequence of further modification of the contributor version. For\par +purposes of this definition, "control" includes the right to grant\par +patent sublicenses in a manner consistent with the requirements of\par +this License.\par +\par + Each contributor grants you a non-exclusive, worldwide, royalty-free\par +patent license under the contributor's essential patent claims, to\par +make, use, sell, offer for sale, import and otherwise run, modify and\par +propagate the contents of its contributor version.\par +\par + In the following three paragraphs, a "patent license" is any express\par +agreement or commitment, however denominated, not to enforce a patent\par +(such as an express permission to practice a patent or covenant not to\par +sue for patent infringement). To "grant" such a patent license to a\par +party means to make such an agreement or commitment not to enforce a\par +patent against the party.\par +\par + If you convey a covered work, knowingly relying on a patent license,\par +and the Corresponding Source of the work is not available for anyone\par +to copy, free of charge and under the terms of this License, through a\par +publicly available network server or other readily accessible means,\par +then you must either (1) cause the Corresponding Source to be so\par +available, or (2) arrange to deprive yourself of the benefit of the\par +patent license for this particular work, or (3) arrange, in a manner\par +consistent with the requirements of this License, to extend the patent\par +license to downstream recipients. "Knowingly relying" means you have\par +actual knowledge that, but for the patent license, your conveying the\par +covered work in a country, or your recipient's use of the covered work\par +in a country, would infringe one or more identifiable patents in that\par +country that you have reason to believe are valid.\par +\par + If, pursuant to or in connection with a single transaction or\par +arrangement, you convey, or propagate by procuring conveyance of, a\par +covered work, and grant a patent license to some of the parties\par +receiving the covered work authorizing them to use, propagate, modify\par +or convey a specific copy of the covered work, then the patent license\par +you grant is automatically extended to all recipients of the covered\par +work and works based on it.\par +\par + A patent license is "discriminatory" if it does not include within\par +the scope of its coverage, prohibits the exercise of, or is\par +conditioned on the non-exercise of one or more of the rights that are\par +specifically granted under this License. You may not convey a covered\par +work if you are a party to an arrangement with a third party that is\par +in the business of distributing software, under which you make payment\par +to the third party based on the extent of your activity of conveying\par +the work, and under which the third party grants, to any of the\par +parties who would receive the covered work from you, a discriminatory\par +patent license (a) in connection with copies of the covered work\par +conveyed by you (or copies made from those copies), or (b) primarily\par +for and in connection with specific products or compilations that\par +contain the covered work, unless you entered into that arrangement,\par +or that patent license was granted, prior to 28 March 2007.\par +\par + Nothing in this License shall be construed as excluding or limiting\par +any implied license or other defenses to infringement that may\par +otherwise be available to you under applicable patent law.\par +\par + 12. No Surrender of Others' Freedom.\par +\par + If conditions are imposed on you (whether by court order, agreement or\par +otherwise) that contradict the conditions of this License, they do not\par +excuse you from the conditions of this License. If you cannot convey a\par +covered work so as to satisfy simultaneously your obligations under this\par +License and any other pertinent obligations, then as a consequence you may\par +not convey it at all. For example, if you agree to terms that obligate you\par +to collect a royalty for further conveying from those to whom you convey\par +the Program, the only way you could satisfy both those terms and this\par +License would be to refrain entirely from conveying the Program.\par +\par + 13. Remote Network Interaction; Use with the GNU General Public License.\par +\par + Notwithstanding any other provision of this License, if you modify the\par +Program, your modified version must prominently offer all users\par +interacting with it remotely through a computer network (if your version\par +supports such interaction) an opportunity to receive the Corresponding\par +Source of your version by providing access to the Corresponding Source\par +from a network server at no charge, through some standard or customary\par +means of facilitating copying of software. This Corresponding Source\par +shall include the Corresponding Source for any work covered by version 3\par +of the GNU General Public License that is incorporated pursuant to the\par +following paragraph.\par +\par + Notwithstanding any other provision of this License, you have\par +permission to link or combine any covered work with a work licensed\par +under version 3 of the GNU General Public License into a single\par +combined work, and to convey the resulting work. The terms of this\par +License will continue to apply to the part which is the covered work,\par +but the work with which it is combined will remain governed by version\par +3 of the GNU General Public License.\par +\par + 14. Revised Versions of this License.\par +\par + The Free Software Foundation may publish revised and/or new versions of\par +the GNU Affero General Public License from time to time. Such new versions\par +will be similar in spirit to the present version, but may differ in detail to\par +address new problems or concerns.\par +\par + Each version is given a distinguishing version number. If the\par +Program specifies that a certain numbered version of the GNU Affero General\par +Public License "or any later version" applies to it, you have the\par +option of following the terms and conditions either of that numbered\par +version or of any later version published by the Free Software\par +Foundation. If the Program does not specify a version number of the\par +GNU Affero General Public License, you may choose any version ever published\par +by the Free Software Foundation.\par +\par + If the Program specifies that a proxy can decide which future\par +versions of the GNU Affero General Public License can be used, that proxy's\par +public statement of acceptance of a version permanently authorizes you\par +to choose that version for the Program.\par +\par + Later license versions may give you additional or different\par +permissions. However, no additional obligations are imposed on any\par +author or copyright holder as a result of your choosing to follow a\par +later version.\par +\par + 15. Disclaimer of Warranty.\par +\par + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\par +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\par +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY\par +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\par +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\par +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\par +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\par +ALL NECESSARY SERVICING, REPAIR OR CORRECTION.\par +\par + 16. Limitation of Liability.\par +\par + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\par +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\par +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\par +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\par +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\par +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\par +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\par +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\par +SUCH DAMAGES.\par +\par + 17. Interpretation of Sections 15 and 16.\par +\par + If the disclaimer of warranty and limitation of liability provided\par +above cannot be given local legal effect according to their terms,\par +reviewing courts shall apply local law that most closely approximates\par +an absolute waiver of all civil liability in connection with the\par +Program, unless a warranty or assumption of liability accompanies a\par +copy of the Program in return for a fee.\par +\par + END OF TERMS AND CONDITIONS\par +} + \ No newline at end of file diff --git a/osx_package/build.sh b/osx_package/build.sh new file mode 100644 index 0000000..7d81a7c --- /dev/null +++ b/osx_package/build.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +# Copy the license text in the resources folder +mkdir -p ./resources + +/bin/cp -rf ../license.rtf ./resources + +pkgbuild --root ./publish --identifier com.plantanapp.pdfautosigner --version 1.0.0.0 --ownership recommended --scripts ./scripts ./output.pkg + +productbuild --distribution ./distribution.xml --resources ./resources --package-path ./ --version 1.0.0.0 ./PdfAutoSigner.pkg \ No newline at end of file diff --git a/osx_package/distribution.xml b/osx_package/distribution.xml new file mode 100644 index 0000000..f6e395b --- /dev/null +++ b/osx_package/distribution.xml @@ -0,0 +1,28 @@ + + + PdfAutoSigner + com.plantanapp.pdfautosigner + + + + + + output.pkg + + + + + + + + + + \ No newline at end of file diff --git a/osx_package/scripts/com.plantanapp.pdfautosigner.plist b/osx_package/scripts/com.plantanapp.pdfautosigner.plist new file mode 100644 index 0000000..a80ecda --- /dev/null +++ b/osx_package/scripts/com.plantanapp.pdfautosigner.plist @@ -0,0 +1,17 @@ + + + + + Label + com.plantanapp.pdfautosigner + Program + /Applications/PlantAnApp/PdfAutoSigner/PdfAutoSigner.LocalApi + ServiceDescription + PdfAutoSigner.LocalApi + RunAtLoad + + KeepAlive + + + \ No newline at end of file diff --git a/osx_package/scripts/postinstall b/osx_package/scripts/postinstall new file mode 100644 index 0000000..6eb802d --- /dev/null +++ b/osx_package/scripts/postinstall @@ -0,0 +1,15 @@ +#!/bin/bash + +# Edit the plist to contain the actual installation folder +# Uses variables passed by the pkg builder to this script: +# $0 = path to the script +# $1 = path to the package +# $2 = target location +# $3 = target volume +plutil -replace Program -string "$2/PdfAutoSigner.LocalApi" com.plantanapp.pdfautosigner.plist + +# Copy the plist file in the daemons folder +sudo cp com.plantanapp.pdfautosigner.plist /Library/LaunchDaemons/ + +# -w flag permanently adds the plist to the Launch Daemon +sudo launchctl load -w /Library/LaunchDaemons/com.plantanapp.pdfautosigner.plist \ No newline at end of file diff --git a/osx_package/scripts/preinstall b/osx_package/scripts/preinstall new file mode 100644 index 0000000..ef195d8 --- /dev/null +++ b/osx_package/scripts/preinstall @@ -0,0 +1,5 @@ +#!/bin/bash + +if /bin/launchctl list "com.plantanapp.pdfautosigner" &> /dev/null; then + /bin/launchctl unload "/Library/LaunchDaemons/com.plantanapp.pdfautosigner" +fi \ No newline at end of file