diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2021-02-06 14:47:10 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2021-02-06 14:47:10 -0600 |
| commit | 07d221c14889d2db99276a9a03c0e067f8365155 (patch) | |
| tree | 33a2393ddc09db546c29190831fabdad5de12dab /src | |
| parent | e59d78b700150c838209c4fac8a42945dc7dd49a (diff) | |
| parent | 7ef25c8f92b319d8df8436d589848fbb0f90efb0 (diff) | |
| download | slskd-07d221c14889d2db99276a9a03c0e067f8365155.tar.gz | |
Merge pull request #35 from slskd/ssl
Add HTTPS with auto-generated or user-supplied certificates
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Common/Cryptography/PBKDF2.cs (renamed from src/slskd/Security/PBKDF2.cs) | 8 | ||||
| -rw-r--r-- | src/slskd/Common/Cryptography/X509.cs | 44 | ||||
| -rw-r--r-- | src/slskd/Common/Validation/FileExistsAttribute.cs | 20 | ||||
| -rw-r--r-- | src/slskd/Common/Validation/ValidationExtensions.cs | 15 | ||||
| -rw-r--r-- | src/slskd/Options.cs (renamed from src/slskd/Common/Configuration/Options.cs) | 49 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 69 | ||||
| -rw-r--r-- | src/slskd/slskd.yml | 3 |
7 files changed, 179 insertions, 29 deletions
diff --git a/src/slskd/Security/PBKDF2.cs b/src/slskd/Common/Cryptography/PBKDF2.cs index 4a857135..4b8b83e4 100644 --- a/src/slskd/Security/PBKDF2.cs +++ b/src/slskd/Common/Cryptography/PBKDF2.cs @@ -18,11 +18,9 @@ byte[] salt = new byte[16]; int iterations = 1000; - using (var rng = RandomNumberGenerator.Create()) - { - rng.GetBytes(salt); - return KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, iterations, 32); - } + using var rng = RandomNumberGenerator.Create(); + rng.GetBytes(salt); + return KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, iterations, 32); } } } diff --git a/src/slskd/Common/Cryptography/X509.cs b/src/slskd/Common/Cryptography/X509.cs new file mode 100644 index 00000000..19b1c4ba --- /dev/null +++ b/src/slskd/Common/Cryptography/X509.cs @@ -0,0 +1,44 @@ +namespace slskd.Common.Cryptography +{ + using System; + using System.Security.Cryptography; + using System.Security.Cryptography.X509Certificates; + + public class X509 + { + public static X509Certificate2 Generate(string subject, string password = null, X509KeyStorageFlags x509KeyStorageFlags = X509KeyStorageFlags.MachineKeySet) + { + password ??= Guid.NewGuid().ToString(); + + using RSA rsa = RSA.Create(2048); + + var request = new CertificateRequest( + new X500DistinguishedName($"CN={subject}"), + rsa, + HashAlgorithmName.SHA256, + RSASignaturePadding.Pkcs1); + + var certificate = request.CreateSelfSigned( + new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), + new DateTimeOffset(DateTime.UtcNow.AddDays(36500))); + + return new X509Certificate2(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags); + } + + public static bool TryValidate(string fileName, string password, out string result) + { + result = null; + + try + { + _ = new X509Certificate2(fileName, password); + return true; + } + catch (Exception ex) + { + result = ex.Message; + return false; + } + } + } +} diff --git a/src/slskd/Common/Validation/FileExistsAttribute.cs b/src/slskd/Common/Validation/FileExistsAttribute.cs new file mode 100644 index 00000000..5453c0ba --- /dev/null +++ b/src/slskd/Common/Validation/FileExistsAttribute.cs @@ -0,0 +1,20 @@ +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + using System.IO; + + public class FileExistsAttribute : ValidationAttribute + { + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + var file = Path.GetFullPath(value.ToString()); + + if (!string.IsNullOrEmpty(file) && !File.Exists(file)) + { + return new ValidationResult($"The {validationContext.DisplayName} field specifies a non-existent file '{file}'."); + } + + return ValidationResult.Success; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Validation/ValidationExtensions.cs b/src/slskd/Common/Validation/ValidationExtensions.cs index f0186e76..11cdca62 100644 --- a/src/slskd/Common/Validation/ValidationExtensions.cs +++ b/src/slskd/Common/Validation/ValidationExtensions.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; - using slskd.Configuration; public static class ValidationExtensions { @@ -39,19 +38,5 @@ return new[] { indent + result }; } } - - public static bool TryValidate(this Options options, out CompositeValidationResult result) - { - result = null; - var results = new List<ValidationResult>(); - - if (!Validator.TryValidateObject(options, new ValidationContext(options), results, true)) - { - result = new CompositeValidationResult("Invalid configuration", results); - return false; - } - - return true; - } } } diff --git a/src/slskd/Common/Configuration/Options.cs b/src/slskd/Options.cs index f10bd5a3..c8fb197e 100644 --- a/src/slskd/Common/Configuration/Options.cs +++ b/src/slskd/Options.cs @@ -1,4 +1,4 @@ -namespace slskd.Configuration +namespace slskd { using slskd.Validation; using Soulseek.Diagnostics; @@ -128,9 +128,32 @@ [Range(1, 65535)] public int Port { get; private set; } = 5001; public bool Force { get; private set; } = false; + [Validate] + public CertificateOptions Certificate { get; private set; } = new CertificateOptions(); + + public class CertificateOptions + { + [FileExists] + public string Pfx { get; private set; } + public string Password { get; private set; } + } } } + public bool TryValidate(out CompositeValidationResult result) + { + result = null; + var results = new List<ValidationResult>(); + + if (!Validator.TryValidateObject(this, new ValidationContext(this), results, true)) + { + result = new CompositeValidationResult("Invalid configuration", results); + return false; + } + + return true; + } + public static IEnumerable<Option> Map => new Option[] { new( @@ -158,6 +181,14 @@ Default: false, Description: "display environment variables"), new( + ShortName: 'g', + LongName: "generate-cert", + EnvironmentVariable: null, + Key: null, + Type: typeof(bool), + Default: false, + Description: "generate X509 certificate and password for HTTPs"), + new( ShortName: 'd', LongName: "debug", EnvironmentVariable: "DEBUG", @@ -223,6 +254,22 @@ Description: "redirect HTTP to HTTPS"), new( ShortName: default, + LongName: "https-cert-pfx", + EnvironmentVariable: "HTTPS_CERT_PFX", + Key: "slskd:web:https:certificate:pfx", + Type: typeof(string), + Default: null, + Description: "path to X509 certificate .pfx"), + new( + ShortName: default, + LongName: "https-cert-password", + EnvironmentVariable: "HTTPS_CERT_PASSWORD", + Key: "slskd:web:https:certificate:password", + Type: typeof(string), + Default: null, + Description: "X509 certificate password"), + new( + ShortName: default, LongName: "url-base", EnvironmentVariable: "URL_BASE", Key: "slskd:web:urlbase", diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b6a47572..373cad67 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -7,14 +7,17 @@ using Serilog; using Serilog.Events; using Serilog.Sinks.Grafana.Loki; + using slskd.Common.Cryptography; using slskd.Configuration; using slskd.Validation; using System; using System.Collections.Generic; using System.IO; using System.Linq; + using System.Net; using System.Reflection; - + using System.Security.Cryptography.X509Certificates; + public static class ProgramExtensions { public static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile) @@ -37,8 +40,9 @@ public class Program { - private static readonly string ConfigurationFile = "slskd.yml"; - private static readonly string EnvironmentVariablePrefix = "SLSKD_"; + private static readonly string AppName = "slskd"; + private static readonly string ConfigurationFile = $"{AppName}.yml"; + private static readonly string EnvironmentVariablePrefix = $"{AppName.ToUpperInvariant()}_"; public static Guid InvocationId { get; } = Guid.NewGuid(); public static int ProcessId { get; } = Environment.ProcessId; @@ -58,6 +62,9 @@ [CommandLineArgument('v', "version", "display version information")] private static bool ShowVersion { get; set; } + [CommandLineArgument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] + private static bool GenerateCertificate { get; set; } + private static Options Options { get; } = new Options(); private static IConfigurationRoot Configuration { get; set; } @@ -79,6 +86,12 @@ return; } + if (GenerateCertificate) + { + GenerateX509Certificate(password: Guid.NewGuid().ToString(), filename: $"{AppName}.pfx"); + return; + } + try { Configuration = new ConfigurationBuilder() @@ -93,6 +106,14 @@ Console.WriteLine(result.GetResultView("Invalid configuration:")); return; } + + var cert = Options.Web.Https.Certificate; + + if (!string.IsNullOrEmpty(cert.Pfx) && !X509.TryValidate(cert.Pfx, cert.Password, out var certResult)) + { + Console.WriteLine($"Invalid HTTPs certificate: {certResult}"); + return; + } } catch (Exception ex) { @@ -178,17 +199,37 @@ } WebHost.CreateDefaultBuilder(args) + .SuppressStatusMessages(true) .ConfigureAppConfiguration((hostingContext, builder) => { builder.Sources.Clear(); builder.AddConfigurationProviders(EnvironmentVariablePrefix, ConfigurationFile); }) .UseSerilog() + .UseUrls() + .UseKestrel(options => + { + logger.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{Options.Web.Port}/"); + options.Listen(IPAddress.Any, Options.Web.Port); + + logger.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{Options.Web.Https.Port}/"); + options.Listen(IPAddress.Any, Options.Web.Https.Port, listenOptions => + { + var cert = Options.Web.Https.Certificate; + + if (!string.IsNullOrEmpty(cert.Pfx)) + { + logger.Information($"Using certificate from {cert.Pfx}"); + listenOptions.UseHttps(cert.Pfx, cert.Password); + } + else + { + logger.Information($"Using randomly generated self-signed certificate"); + listenOptions.UseHttps(X509.Generate(subject: AppName)); + } + }); + }) .UseStartup<Startup>() - //.UseUrls( - // $"http://+:{options.Web.Port}", - // $"https://+:{options.Web.Https.Port}") - .UseUrls($"http://+:{Options.Web.Port}") .Build() .Run(); } @@ -202,6 +243,18 @@ } } + public static void GenerateX509Certificate(string password, string filename) + { + Console.WriteLine("Generating X509 certificate..."); + filename = Path.Combine(AppContext.BaseDirectory, filename); + + var cert = X509.Generate(subject: AppName, password, X509KeyStorageFlags.Exportable); + File.WriteAllBytes(filename, cert.Export(X509ContentType.Pkcs12, password)); + + Console.WriteLine($"Password: {password}"); + Console.WriteLine($"Certificate exported to {filename}"); + } + public static void PrintCommandLineArguments(IEnumerable<Option> map) { static string GetLongName(string longName, Type type) @@ -233,7 +286,7 @@ var longestName = map.Select(a => GetName(a.EnvironmentVariable, a.Type)).Max(n => n.Length); - Console.WriteLine("\nenvironment variables (arguments and config.yml have precedence):\n"); + Console.WriteLine("\nenvironment variables (arguments and config file have precedence):\n"); foreach (Option item in map) { diff --git a/src/slskd/slskd.yml b/src/slskd/slskd.yml index 4bf36e56..d5519b65 100644 --- a/src/slskd/slskd.yml +++ b/src/slskd/slskd.yml @@ -7,6 +7,9 @@ # https: # port: 5001 # force: false +# certificate: +# pfx: ~ +# password: ~ # url_base: / # content_path: wwwroot # authentication: |
