// Khaemhat.LicenseTool: key pair, issuing and verification of .khl licences and module activation codes (SPEC §8.2). // The private key (.khkey, PKCS#8 PEM) stays outside the repository: .gitignore excludes *.khkey and *.pem. using System.Globalization; using System.Security.Cryptography; using Khaemhat.Infrastructure.Licensing; const string Usage = """ Khaemhat.LicenseTool keygen --out Creates a key pair: writes the private key and prints the public key to put in LicenseVerifier.ProductPublicKey. issue --key --licensee --modules CORE,ACCT,... --users --companies [--expires yyyy-mm-dd] [--grace ] [--instance ] [--id ] --out Signs an instance licence. code --key --module --expires yyyy-mm [--instance ] Signs an activation code for one module. verify [--public-key ] Checks a licence or a code with the product public key (or the one given). """; if (args.Length == 0 || args[0] is "-h" or "--help" or "help") { Console.WriteLine(Usage); return args.Length == 0 ? 1 : 0; } try { var options = Options.Parse(args.Skip(1)); return args[0] switch { "keygen" => KeyGen(options), "issue" => Issue(options), "code" => Code(options), "verify" => Verify(options), _ => Fail($"Unknown command '{args[0]}'.\n\n{Usage}"), }; } catch (Exception ex) when (ex is ArgumentException or FormatException or IOException or CryptographicException or UnauthorizedAccessException) { return Fail(ex.Message); } static int KeyGen(Options options) { var path = options.Required("out"); if (File.Exists(path)) { return Fail($"{path} exists: the tool never overwrites a key."); } var (privateKey, publicKey) = LicenseSigner.CreateKeyPair(); File.WriteAllText(path, privateKey); Console.WriteLine($"Private key written to {path}. Keep it outside the repository and back it up."); Console.WriteLine("Public key (LicenseVerifier.ProductPublicKey):"); Console.WriteLine(publicKey); return 0; } static int Issue(Options options) { using var key = LoadKey(options.Required("key")); var document = new LicenseDocument { Id = options.Optional("id") ?? "KHL-" + DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture), Licensee = options.Required("licensee"), InstanceId = options.Optional("instance"), IssuedAt = DateTime.UtcNow, ExpiresAt = options.Optional("expires") is { } expires ? DateTime.SpecifyKind(DateTime.ParseExact(expires, "yyyy-MM-dd", CultureInfo.InvariantCulture).AddDays(1).AddSeconds(-1), DateTimeKind.Utc) : null, MaxConcurrentUsers = int.Parse(options.Required("users"), CultureInfo.InvariantCulture), MaxCompanies = int.Parse(options.Required("companies"), CultureInfo.InvariantCulture), Modules = [.. options.Required("modules").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)], GracePeriodDays = int.Parse(options.Optional("grace") ?? "30", CultureInfo.InvariantCulture), }; var path = options.Required("out"); File.WriteAllText(path, LicenseSigner.Sign(document, key)); Console.WriteLine($"Licence {document.Id} for {document.Licensee} written to {path}."); return 0; } static int Code(Options options) { using var key = LoadKey(options.Required("key")); var month = DateOnly.ParseExact(options.Required("expires") + "-01", "yyyy-MM-dd", CultureInfo.InvariantCulture); Console.WriteLine(LicenseSigner.SignActivationCode(options.Required("module"), month, options.Optional("instance"), key)); return 0; } static int Verify(Options options) { var input = options.Positional ?? throw new ArgumentException("Give a .khl file or an activation code."); var verifier = options.Optional("public-key") is { } publicKey ? new LicenseVerifier(publicKey) : LicenseVerifier.Product; if (File.Exists(input)) { var result = verifier.Verify(File.ReadAllText(input)); if (!result.IsValid) { return Fail($"Not valid: {result.Error}."); } var d = result.Document!; Console.WriteLine($"Valid licence {d.Id} for {d.Licensee}: modules {string.Join(',', d.Modules)}, {d.MaxConcurrentUsers} users, " + $"{d.MaxCompanies} companies, expires {d.ExpiresAt?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) ?? "never"}, grace {d.GracePeriodDays} days."); return 0; } var (code, error) = verifier.VerifyActivationCode(input); if (code is null) { return Fail($"Not valid: {error}."); } Console.WriteLine($"Valid activation code for {code.Module} until {code.ExpiresAt:yyyy-MM-dd}."); return 0; } static ECDsa LoadKey(string path) { var key = ECDsa.Create(); key.ImportFromPem(File.ReadAllText(path)); return key; } static int Fail(string message) { Console.Error.WriteLine(message); return 1; } /// Command-line options: --name value pairs and one positional argument. internal sealed class Options { private readonly Dictionary _values = new(StringComparer.Ordinal); /// The positional argument. public string? Positional { get; private set; } /// Parses the arguments after the command. /// The arguments. /// The options. public static Options Parse(IEnumerable args) { var options = new Options(); using var e = args.GetEnumerator(); while (e.MoveNext()) { if (e.Current.StartsWith("--", StringComparison.Ordinal)) { var name = e.Current[2..]; options._values[name] = e.MoveNext() ? e.Current : throw new ArgumentException($"--{name} needs a value."); } else { options.Positional = e.Current; } } return options; } /// A required option. /// The name. /// The value. public string Required(string name) => _values.TryGetValue(name, out var value) ? value : throw new ArgumentException($"--{name} is required."); /// An optional option. /// The name. /// The value, or . public string? Optional(string name) => _values.GetValueOrDefault(name); }