using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Infrastructure.Licensing;
///
/// An instance licence (SPEC §8.2). It travels as a .khl file: a JSON object with the licence and an ECDSA
/// P-256 signature over its canonical form ().
///
public sealed record LicenseDocument
{
/// The licence identifier.
public string Id { get; init; } = string.Empty;
/// The licence holder.
public string Licensee { get; init; } = string.Empty;
/// The instance the licence is bound to; for any instance.
public string? InstanceId { get; init; }
/// When it was issued (UTC).
public DateTime IssuedAt { get; init; }
/// When it expires (UTC); for no expiry.
public DateTime? ExpiresAt { get; init; }
/// Concurrent users across all companies.
public int MaxConcurrentUsers { get; init; }
/// Companies on the instance.
public int MaxCompanies { get; init; }
/// The module codes.
public IReadOnlyList Modules { get; init; } = [];
/// Days of full use after the expiry, before read-only.
public int GracePeriodDays { get; init; }
///
/// The bytes that are signed: compact JSON with the properties in declaration order, modules upper-case and sorted,
/// times in ISO 8601 UTC to the second. Two equal licences always give the same bytes.
///
/// The UTF-8 bytes.
public byte[] CanonicalBytes()
{
var canonical = new Canonical(
Id,
Licensee,
InstanceId,
Format(IssuedAt),
ExpiresAt is { } expires ? Format(expires) : null,
MaxConcurrentUsers,
MaxCompanies,
[.. Modules.Select(m => m.Trim().ToUpperInvariant()).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal)],
GracePeriodDays);
return JsonSerializer.SerializeToUtf8Bytes(canonical, LicenseJson.Options);
}
private static string Format(DateTime value) =>
DateTime.SpecifyKind(value, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
private sealed record Canonical(
string Id, string Licensee, string? InstanceId, string IssuedAt, string? ExpiresAt,
int MaxConcurrentUsers, int MaxCompanies, string[] Modules, int GracePeriodDays);
}
/// The JSON settings of licence files.
internal static class LicenseJson
{
public static JsonSerializerOptions Options { get; } = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
WriteIndented = false,
};
public static JsonSerializerOptions Indented { get; } = new(Options) { WriteIndented = true };
}
/// The outcome of a licence check. is format_invalid or signature_invalid.
/// The licence, when valid.
/// The error code otherwise.
public sealed record LicenseVerification(LicenseDocument? Document, string? Error)
{
/// Whether the licence is authentic.
public bool IsValid => Document is not null;
}
/// Signs licences and activation codes. Used only by tools/Khaemhat.LicenseTool, with the private key.
public static class LicenseSigner
{
/// The format marker of .khl files.
public const string Format = "khl1";
/// Creates a key pair.
/// The private key (PKCS#8 PEM) and the public key (SubjectPublicKeyInfo, base64).
public static (string PrivateKeyPem, string PublicKeyBase64) CreateKeyPair()
{
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
return (key.ExportPkcs8PrivateKeyPem(), Convert.ToBase64String(key.ExportSubjectPublicKeyInfo()));
}
/// Signs a licence.
/// The licence.
/// The private key.
/// The .khl text.
public static string Sign(LicenseDocument document, ECDsa privateKey)
{
ArgumentNullException.ThrowIfNull(document);
ArgumentNullException.ThrowIfNull(privateKey);
var signature = privateKey.SignData(document.CanonicalBytes(), HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
var file = new LicenseFile(Format, document, Convert.ToBase64String(signature));
return JsonSerializer.Serialize(file, LicenseJson.Indented);
}
/// Creates a signed activation code for one module (see ).
/// The module code.
/// The last month of validity.
/// The instance it is bound to, or for any instance.
/// The private key.
/// The code.
public static string SignActivationCode(string module, DateOnly expiresMonth, string? instanceId, ECDsa privateKey)
{
ArgumentException.ThrowIfNullOrWhiteSpace(module);
ArgumentNullException.ThrowIfNull(privateKey);
var payload = new byte[10];
RandomNumberGenerator.Fill(payload.AsSpan(0, 5));
ModuleActivationCode.InstanceTag(instanceId).CopyTo(payload.AsSpan(5));
var body = ModuleActivationCode.Body(module.Trim().ToUpperInvariant(), expiresMonth, Base32.Encode(payload));
var signature = privateKey.SignData(Encoding.ASCII.GetBytes(body), HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
return body + "-" + Base32.Encode(signature);
}
internal sealed record LicenseFile(string Format, LicenseDocument License, string Signature);
}
/// Checks licences and activation codes with the public key built into the product (SPEC §8.2).
public sealed class LicenseVerifier
{
///
/// The public key of the BalboSoft licences (SubjectPublicKeyInfo, base64). The private key never enters the repository.
///
public const string ProductPublicKey =
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEE4ybLR3rfbtmjS7vRBg8WQOz6qNOPG8itlFy9MufvWrT/qoOfxCLwehR9DnKE77GXvqD2J+ZM0Fs6ccS84YBDw==";
private readonly byte[] _publicKey;
/// Creates a verifier.
/// The public key (SubjectPublicKeyInfo, base64).
public LicenseVerifier(string publicKeyBase64)
{
ArgumentException.ThrowIfNullOrWhiteSpace(publicKeyBase64);
_publicKey = Convert.FromBase64String(publicKeyBase64);
}
/// A verifier with .
public static LicenseVerifier Product { get; } = new(ProductPublicKey);
/// Checks a .khl file.
/// The file content.
/// The licence when the signature is valid.
public LicenseVerification Verify(string text)
{
LicenseSigner.LicenseFile? file;
try
{
file = JsonSerializer.Deserialize(text ?? string.Empty, LicenseJson.Options);
}
catch (JsonException)
{
return new LicenseVerification(null, LicenseErrors.FormatInvalid);
}
if (file is not { Format: LicenseSigner.Format, License: not null, Signature: not null })
{
return new LicenseVerification(null, LicenseErrors.FormatInvalid);
}
byte[] signature;
try
{
signature = Convert.FromBase64String(file.Signature);
}
catch (FormatException)
{
return new LicenseVerification(null, LicenseErrors.FormatInvalid);
}
return VerifySignature(file.License.CanonicalBytes(), signature)
? new LicenseVerification(file.License, null)
: new LicenseVerification(null, LicenseErrors.SignatureInvalid);
}
/// Checks a module activation code.
/// The code.
/// The parsed code when the signature is valid, or the error code.
public (ModuleActivationCode? Code, string? Error) VerifyActivationCode(string code)
{
if (!ModuleActivationCode.TryParse(code, out var parsed, out var signature))
{
return (null, LicenseErrors.FormatInvalid);
}
return VerifySignature(Encoding.ASCII.GetBytes(parsed.SignedBody), signature)
? (parsed, null)
: (null, LicenseErrors.SignatureInvalid);
}
private bool VerifySignature(byte[] data, byte[] signature)
{
try
{
using var key = ECDsa.Create();
key.ImportSubjectPublicKeyInfo(_publicKey, out _);
return key.VerifyData(data, signature, HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
}
catch (CryptographicException)
{
return false;
}
}
}
///
/// An activation code for one module: KH1-<MODULE>-<YYYYMM>-<payload base32>-<signature base32>
/// (SPEC §8.2). The payload holds a serial and a tag of the instance (zeros for any instance); the module stays active
/// until the end of the month YYYYMM.
///
public sealed record ModuleActivationCode(string Module, DateOnly ExpiresMonth, string Payload)
{
/// The format version.
public const string Prefix = "KH1";
/// The text that is signed (everything before the signature).
public string SignedBody => Body(Module, ExpiresMonth, Payload);
/// The last moment of validity: the end of (UTC).
public DateTime ExpiresAt => new DateTime(ExpiresMonth.Year, ExpiresMonth.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(1).AddTicks(-10);
/// Whether the code works on an instance.
/// The instance identifier.
/// if the code is for any instance or for this one.
public bool IsFor(string instanceId)
{
var tag = Base32.Decode(Payload).AsSpan(5);
return tag.IndexOfAnyExcept((byte)0) < 0 || tag.SequenceEqual(InstanceTag(instanceId));
}
internal static string Body(string module, DateOnly expiresMonth, string payload) =>
string.Create(CultureInfo.InvariantCulture, $"{Prefix}-{module}-{expiresMonth.Year:D4}{expiresMonth.Month:D2}-{payload}");
internal static byte[] InstanceTag(string? instanceId) =>
instanceId is null ? new byte[5] : SHA256.HashData(Encoding.UTF8.GetBytes(instanceId.Trim().ToUpperInvariant()))[..5];
internal static bool TryParse(string? text, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out ModuleActivationCode? code, out byte[] signature)
{
code = null;
signature = [];
var parts = text?.Trim().ToUpperInvariant().Split('-');
if (parts is not { Length: 5 } || parts[0] != Prefix || parts[1].Length is < 2 or > 10 || parts[2].Length != 6
|| !int.TryParse(parts[2][..4], NumberStyles.None, CultureInfo.InvariantCulture, out var year)
|| !int.TryParse(parts[2][4..], NumberStyles.None, CultureInfo.InvariantCulture, out var month)
|| year < 2000 || month is < 1 or > 12)
{
return false;
}
try
{
if (Base32.Decode(parts[3]).Length != 10)
{
return false;
}
signature = Base32.Decode(parts[4]);
}
catch (FormatException)
{
return false;
}
code = new ModuleActivationCode(parts[1], new DateOnly(year, month, 1), parts[3]);
return true;
}
}
/// The error codes of licences.
public static class LicenseErrors
{
/// The text is not a licence or a code.
public const string FormatInvalid = "format_invalid";
/// The signature does not match: changed or not issued by BalboSoft.
public const string SignatureInvalid = "signature_invalid";
/// A fictitious code outside test mode (SPEC §8.3).
public const string TestOnly = "license_test_only";
/// The licence or code has expired.
public const string Expired = "license_expired";
/// The licence or code belongs to another instance.
public const string WrongInstance = "license_wrong_instance";
/// The module code is unknown.
public const string UnknownModule = "module_unknown";
}