licensing: HWID diagnosability, matcher widening, delete-condition fix

- hwid.cpp: BitStream3 buffer 125 -> 160 bits (writes totalled 147 bits
  and overflowed the old allocation; encoded HWID bytes unchanged).
  Log component availability (uuid/cpu/mac/hdd) once per distinct HWID,
  and warn when WMI yields no components at all.
- Matcher widened only, generation untouched: exact-string match
  short-circuits, UUID match accepts any WMI list entry (generator
  hashes the last valid one), fuzzy-match point breakdown is logged so
  field status-12 rejections are diagnosable.
- ANSLicense.cpp: fix inverted delete condition (!p != NULL) at 6 sites;
  detect the shared "empty fingerprint" HWID of WMI-broken PCs and warn
  with repair steps; mask activation keys in error strings.
- licensingclient.h: explain SetKey/validation/NTP failures on stderr.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-17 13:11:16 +10:00
co-authored by Claude Opus 4.8
parent d2479b9b07
commit 60a8b39d24
4 changed files with 171 additions and 54 deletions
+31 -17
View File
@@ -98,6 +98,16 @@ namespace {
return s.substr(0, 4) + std::string(s.size() - 8, '*') + s.substr(s.size() - 4);
}
// The HWID emitted when WMI returns no hardware components at all (every
// hash field is the "absent" marker). Every PC with broken WMI produces
// this exact string, so it identifies "WMI broken" in customer logs.
constexpr const char* kEmptyFingerprintHWID = "ESWJJ-LEEFC-CCTBB-JSSWJ-JLEEF";
constexpr const char* kEmptyFingerprintWarning =
"Hardware fingerprint is EMPTY - WMI returned no hardware components on this PC. "
"Licensing proceeds but the license is weakly bound to this machine. "
"Repair WMI: run 'winmgmt /verifyrepository' (then 'winmgmt /salvagerepository' if inconsistent).";
// SDK identifier passed to ANSLSHelper for licensing-service auth. Despite
// the variable name "privateKey" used at call sites, this is an 11-byte
// SDK token that identifies the ANSCENTER product to the licensing
@@ -2166,7 +2176,7 @@ namespace ANSCENTER
}
void ANSLSHelper::LoadLicense(std::string licenseKey) {
if (!this->_license != NULL) delete this->_license;
if (this->_license != NULL) delete this->_license;
this->_license = new License();
std::string licenseFileName = Dash2Underscore(licenseKey)+".json";
std::string licenseFolder = GetLicenseDir();
@@ -2812,6 +2822,9 @@ namespace ANSCENTER
std::wstring _registrationName = String2WString(registrationName);
std::wstring hardwareId = KeyHelper::GetCurrentHardwareId();
std::string _hardwareId = WString2String(hardwareId);
if (_hardwareId == kEmptyFingerprintHWID) {
this->_logger.LogWarn("ANSLSHelper::ValidateLicenseKey", kEmptyFingerprintWarning, __FILE__, __LINE__);
}
bool _overrideLicenseFile = false;
if (activationKey.empty()) {
if (this->_license != NULL) {// get it from there
@@ -2888,14 +2901,13 @@ namespace ANSCENTER
case STATUS_INVALID_HARDWARE_ID:
_licenseKeyStatus = INVALID_HARDWARE_ID;
activationStatusStr = "Hardware id does not match this computer. current HWID is " + _hardwareId +
"; client HWID is " + WString2String(licensingClient.GetHardwareId()) +
"; Current activation key is " + WString2String(_activationKey) +
"; client Activation key is " + WString2String(licensingClient.GetActivationKey()) +
"; URL is " + WString2String(this->_licenseServiceURL.c_str())+
activationStatusStr = "Local hardware fingerprint check rejected this computer (hardware changed, or WMI returned no components). Current HWID is " + _hardwareId +
"; stored activation key is " + mask_secret(WString2String(_activationKey)) +
"; server activation key is " + mask_secret(WString2String(licensingClient.GetActivationKey())) +
"; URL is " + WString2String(this->_licenseServiceURL.c_str())+
"; ProductId is " + WString2String(wProductId) +
"; RegistrationName is " + WString2String(_registrationName) +
"; Status is" + std::to_string(activationStatus);
"; Status is " + std::to_string(activationStatus);
break;
case STATUS_LICENSE_EXPIRED:
@@ -2969,7 +2981,7 @@ namespace ANSCENTER
if (_overrideLicenseFile) {
this->_logger.LogDebug("ANSLSHelper::ValidateLicenseKey", "Override license key.", __FILE__, __LINE__);
if (!this->_license != NULL) delete this->_license;
if (this->_license != NULL) delete this->_license;
this->_license = new License();
this->_license->SetLicenseKey(_licenseKey.c_str());
this->_license->SetLicenseKeyValidationData(validationData, validationDataLen);
@@ -2996,7 +3008,7 @@ namespace ANSCENTER
if (_overrideLicenseFile) {
// Save license
this->_logger.LogDebug("ANSLSHelper::ValidateLicenseKey", "Override license key.", __FILE__, __LINE__);
if (!this->_license != NULL) delete this->_license;
if (this->_license != NULL) delete this->_license;
this->_license = new License();
this->_license->SetLicenseKey(_licenseKey.c_str());
this->_license->SetLicenseKeyValidationData(validationData, validationDataLen);
@@ -3026,6 +3038,9 @@ namespace ANSCENTER
std::wstring _registrationName = String2WString(registrationName);
std::string _hardwareId = customHWID;
std::wstring hardwareId = String2WString(customHWID);
if (_hardwareId == kEmptyFingerprintHWID) {
this->_logger.LogWarn("ANSLSHelper::ValidateLicenseWithCustomHWID", kEmptyFingerprintWarning, __FILE__, __LINE__);
}
bool _overrideLicenseFile = false;
if (activationKey.empty()) {
if (this->_license != NULL) {// get it from there
@@ -3102,14 +3117,13 @@ namespace ANSCENTER
case STATUS_INVALID_HARDWARE_ID:
_licenseKeyStatus = INVALID_HARDWARE_ID;
activationStatusStr = "Hardware id does not match this computer. current HWID is " + _hardwareId +
"; client HWID is " + WString2String(licensingClient.GetHardwareId()) +
"; Current activation key is " + WString2String(_activationKey) +
"; client Activation key is " + WString2String(licensingClient.GetActivationKey()) +
activationStatusStr = "Local hardware fingerprint check rejected this computer (hardware changed, or WMI returned no components). Current HWID is " + _hardwareId +
"; stored activation key is " + mask_secret(WString2String(_activationKey)) +
"; server activation key is " + mask_secret(WString2String(licensingClient.GetActivationKey())) +
"; URL is " + WString2String(this->_licenseServiceURL.c_str()) +
"; ProductId is " + WString2String(wProductId) +
"; RegistrationName is " + WString2String(_registrationName) +
"; Status is" + std::to_string(activationStatus);
"; Status is " + std::to_string(activationStatus);
break;
case STATUS_LICENSE_EXPIRED:
@@ -3183,7 +3197,7 @@ namespace ANSCENTER
if (_overrideLicenseFile) {
this->_logger.LogDebug("ANSLSHelper::ValidateLicenseKey", "Override license key.", __FILE__, __LINE__);
if (!this->_license != NULL) delete this->_license;
if (this->_license != NULL) delete this->_license;
this->_license = new License();
this->_license->SetLicenseKey(_licenseKey.c_str());
this->_license->SetLicenseKeyValidationData(validationData, validationDataLen);
@@ -3210,7 +3224,7 @@ namespace ANSCENTER
if (_overrideLicenseFile) {
// Save license
this->_logger.LogDebug("ANSLSHelper::ValidateLicenseKey", "Override license key.", __FILE__, __LINE__);
if (!this->_license != NULL) delete this->_license;
if (this->_license != NULL) delete this->_license;
this->_license = new License();
this->_license->SetLicenseKey(_licenseKey.c_str());
this->_license->SetLicenseKeyValidationData(validationData, validationDataLen);
@@ -3496,7 +3510,7 @@ namespace ANSCENTER
return 0; // invalid
}
else {
if (!this->_license != NULL) delete this->_license;
if (this->_license != NULL) delete this->_license;
this->_license = new License();
this->_license->SetLicenseKey(_licenseKey.c_str());
this->_license->SetLicenseKeyValidationData(validationData, validationDataLen);
+61 -5
View File
@@ -220,7 +220,11 @@ const char* HardwareId::GetCurrentHardwareId()
WmiHelper wmi;
#endif
BitStream3 bits(125);
// 3 version bits + 9 x 16-bit hashes = 147 bits are written below, but only
// the first 16 bytes are base32-encoded into the HWID (the HDD fields are
// truncated by the 25-char format). The stream buffer must still hold every
// write: 125 bits (16 bytes) overflowed the allocation by 3 bytes.
BitStream3 bits(160);
list<string> propList;
unsigned char version = 1;
unsigned short hash1, hash2, hash3, hash4;
@@ -256,6 +260,8 @@ const char* HardwareId::GetCurrentHardwareId()
bits.WriteUInt16(hash1);
bool uuidFound = (hash1 != h0);
// CPU IDs - get up to 4 for better resilience
propList.clear();
@@ -270,6 +276,8 @@ const char* HardwareId::GetCurrentHardwareId()
cpu = NormalizeHardwareString(cpu);
}
int cpuCount = (int)propList.size();
hash1 = (propList.size() > 0) ? HashString(propList.front().c_str()) : h0;
hash2 = (propList.size() > 1) ? HashString(propList.back().c_str()) : h0;
@@ -298,6 +306,8 @@ const char* HardwareId::GetCurrentHardwareId()
}
propList.sort();
int macCount = (int)propList.size();
// Store up to 4 MAC hashes
auto macIter = propList.begin();
hash1 = (propList.size() > 0 && macIter != propList.end()) ? HashString((macIter++)->c_str()) : h0;
@@ -325,6 +335,8 @@ const char* HardwareId::GetCurrentHardwareId()
}
propList.sort();
int hddCount = (int)propList.size();
auto hddIter = propList.begin();
hash1 = (propList.size() > 0 && hddIter != propList.end()) ? HashString((hddIter++)->c_str()) : h0;
hash2 = (propList.size() > 1 && hddIter != propList.end()) ? HashString((hddIter++)->c_str()) : h0;
@@ -351,11 +363,34 @@ const char* HardwareId::GetCurrentHardwareId()
insertPos += 6;
}
// Field-diagnosability: log the component availability once per distinct
// result so support can tell a weak fingerprint from a healthy one
static string lastLoggedHwid;
if (hardwareId != lastLoggedHwid)
{
lastLoggedHwid = hardwareId;
fprintf(stderr, "[anslicensing] hardware id %s (components: uuid=%s cpu=%d mac=%d hdd=%d)\n",
hardwareId.c_str(), uuidFound ? "ok" : "none", cpuCount, macCount, hddCount);
if (!uuidFound && cpuCount == 0 && macCount == 0)
fprintf(stderr, "[anslicensing] WARNING: no hardware components readable via WMI - hardware id is NOT machine-specific. "
"Check WMI health: winmgmt /verifyrepository (then winmgmt /salvagerepository if inconsistent)\n");
}
return hardwareId.c_str();
}
bool HardwareId::MatchCurrentHardwareId(const char* hwid)
{
// An HWID identical to the one this machine generates right now is by
// definition this computer. The points-based matching below can score
// under REQUIRED_POINTS on machines with an invalid SMBIOS UUID and few
// fingerprintable components (no PCI NIC, no readable disk serial), which
// would reject even a freshly generated local HWID.
const char* currentHwid = GetCurrentHardwareId();
if (currentHwid != NULL && strcmp(hwid, currentHwid) == 0)
return true;
#ifdef _WIN32
WmiHelper wmi;
#endif
@@ -383,8 +418,14 @@ bool HardwareId::MatchCurrentHardwareId(const char* hwid)
auto buf = base32.decode(hardwareId.c_str(), hardwareId.length(), &bufLen);
// The field layout is 147 bits but the HWID only encodes 16 bytes; zero-pad
// the buffer so reading the trailing (truncated) HDD fields stays in bounds
// and yields deterministic values instead of an out-of-bounds read.
if (buf.size() < 20)
buf.resize(20, 0);
BitStream3 bits;
bits.Attach(buf.data(), 125);
bits.Attach(buf.data(), 160);
unsigned char version = 0;
bits.Read(&version, 3);
@@ -398,6 +439,7 @@ bool HardwareId::MatchCurrentHardwareId(const char* hwid)
// Use a points-based matching system for resilience
int matchPoints = 0;
bool uuidMatched = false;
const int REQUIRED_POINTS = 2; // Need at least 2 components to match
// Read UUID hash
@@ -430,6 +472,7 @@ bool HardwareId::MatchCurrentHardwareId(const char* hwid)
}
}
matchPoints += 2; // UUID/Memory match gives 2 points
uuidMatched = true;
}
else
{
@@ -437,9 +480,11 @@ bool HardwareId::MatchCurrentHardwareId(const char* hwid)
#ifdef _WIN32
wmi.GetPropertyList("SELECT * FROM Win32_ComputerSystemProduct", "UUID", &propList);
#endif
if (propList.size() > 0)
// The generator hashes the last valid UUID entry, so accept a match
// against any entry rather than only the first one
for (list<string>::iterator iter = propList.begin(); iter != propList.end(); iter++)
{
string s = NormalizeHardwareString(propList.front());
string s = NormalizeHardwareString(*iter);
if ((s.length() > 1)
&& (s != "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")
@@ -448,6 +493,8 @@ bool HardwareId::MatchCurrentHardwareId(const char* hwid)
if (hash1 != h0 && hash1 == HashString(s.c_str()))
{
matchPoints += 2; // UUID match is worth 2 points (most stable)
uuidMatched = true;
break;
}
}
}
@@ -558,5 +605,14 @@ bool HardwareId::MatchCurrentHardwareId(const char* hwid)
// - UUID (2) + MAC (1) = 3 points ✓
// - UUID (2) + HDD (1) = 3 points ✓
// - CPU (1) + MAC (1) + HDD (1) = 3 points ✓ (if UUID changed but hardware same)
return matchPoints >= REQUIRED_POINTS;
bool accepted = (matchPoints >= REQUIRED_POINTS);
// Only reached when the exact-string precheck missed, i.e. the stored HWID
// differs from the one this machine generates now. Log the breakdown so a
// status-12 rejection in the field is diagnosable from the console output.
fprintf(stderr, "[anslicensing] hardware id fuzzy match for %s: uuid=%s cpuMatches=%d macMatches=%d hddMatches=%d -> %d point(s), %d required -> %s\n",
hwid, uuidMatched ? "match" : "no-match", cpuMatches, macMatches, hddMatches,
matchPoints, REQUIRED_POINTS, accepted ? "accepted" : "REJECTED");
return accepted;
}
+33 -8
View File
@@ -2,6 +2,7 @@
#include <memory>
#include <vector>
#include <cstdio>
#include "except.h"
#include "template.h"
@@ -172,13 +173,15 @@ public:
if (!licenseKeyValidationData.empty())
validator.SetValidationData("LicenseKeyValidationData", licenseKeyValidationData.data(), (activationTemplate->GetValidationDataSize() + 7) >> 3);
try
try
{
validator.SetKey(activationKey.c_str());
}
catch (Exception * ex)
{
ex->Destroy();
fprintf(stderr, "[anslicensing] activation key is %s (SetKey failed) - product needs (re)activation\n",
activationKey.empty() ? "empty" : "malformed");
activationStatus = STATUS_INVALID_ACTIVATION_KEY;
if (ownActivationTemplate) delete activationTemplate;
return false;
@@ -186,6 +189,7 @@ public:
if (!validator.IsKeyValid())
{
fprintf(stderr, "[anslicensing] activation key does not validate against this license key + hardware id\n");
activationStatus = STATUS_INVALID_ACTIVATION_KEY;
if (ownActivationTemplate) delete activationTemplate;
return false;
@@ -222,6 +226,7 @@ public:
{
if (timeValidationMethod == USE_INTERNET_TIME) // internet time was mandatory
{
fprintf(stderr, "[anslicensing] could not obtain internet time (NTP) and internet time is mandatory - check network/firewall\n");
activationStatus = STATUS_NET_ERROR;
if (ownActivationTemplate) delete activationTemplate;
return false;
@@ -239,14 +244,18 @@ public:
if (diffSeconds < 0)
{
m_licenseValidityDays = licenseTemplate->GetLicenseGracePeriod() - (int)(((time_t)(-diffSeconds) + 86400 - 1) / 86400);
if (m_licenseValidityDays < 0)
m_licenseValidityDays = 0;
fprintf(stderr, "[anslicensing] license expired on %04d-%02d-%02d (grace days remaining: %d)\n",
1900 + licenseExpirationTime.tm_year, 1 + licenseExpirationTime.tm_mon, licenseExpirationTime.tm_mday,
m_licenseValidityDays);
activationStatus = STATUS_LICENSE_EXPIRED;
if (ownActivationTemplate) delete activationTemplate;
return false;
} else
m_licenseValidityDays = licenseTemplate->GetLicenseGracePeriod() + (int)(((time_t)diffSeconds + 86400 - 1) / 86400);
@@ -465,6 +474,9 @@ public:
generator.SetValidationData("LicenseKeyValidationData", licenseKeyValidationData.data(), licenseKeyValidationDataLen * 8);
}
fprintf(stderr, "[anslicensing] requesting activation key from licensing service: %s (hwid %s)\n",
activationTemplate->GetLicensingServiceUrl(), hardwareId.c_str());
try {
activationKey = generator.GenerateKey();
}
@@ -472,19 +484,29 @@ public:
{
if ((ex->GetCode() == STATUS_NET_ERROR) && (generator.GetSigningServiceStatusCode() == 406))
{
fprintf(stderr, "[anslicensing] licensing service returned HTTP 406 - payment required\n");
m_licenseValidationResult.SetPaymentRequired(true);
ex->Destroy();
}
else
{
fprintf(stderr, "[anslicensing] activation request failed (service HTTP status %d) - check network access to the licensing service\n",
generator.GetSigningServiceStatusCode());
throw;
}
}
if (ValidateActivationKey(activationTemplate.get(), false))
{
fprintf(stderr, "[anslicensing] activation key acquired and validated (service HTTP status %d)\n",
generator.GetSigningServiceStatusCode());
activationStatus = STATUS_SUCCESS;
}
else
{
fprintf(stderr, "[anslicensing] licensing service returned an activation key that does not validate for this hardware id\n");
throw new LicensingException(STATUS_GENERIC_ERROR, "internal error - invalid returned activation key");
}
m_licenseValidationResult.m_license = std::make_unique<LicenseImpl>();
@@ -531,10 +553,12 @@ public:
const char * GetCurrentHardwareIdCallback()
{
if (parentUsesWideChar)
if (parentUsesWideChar)
{
static string hwid = w2s(GetCurrentHardwareIdW(parentLicensingClient));
return hwid.c_str();
// per-instance storage: a function-local static would freeze the
// first client's HWID for the lifetime of the process
currentHwidCache = w2s(GetCurrentHardwareIdW(parentLicensingClient));
return currentHwidCache.c_str();
}
else
{
@@ -587,6 +611,7 @@ private:
string licenseKey;
string activationKey;
string hardwareId;
string currentHwidCache;
string licensingServiceUrl;
vector<unsigned char> licenseKeyValidationData;
+46 -24
View File
@@ -2,6 +2,7 @@
#define _WIN32_DCOM
#include <iostream>
#include <cstdio>
#include <comdef.h>
#include <Wbemidl.h>
#include <list>
@@ -45,17 +46,19 @@ public:
);
hres = CoCreateInstance(
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
CLSID_WbemLocator,
0,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator, (LPVOID *) &wbemLocator);
if (FAILED(hres))
{
if (ownCoInitialize)
CoUninitialize();
throw new exception("failed to create IWbemLocator", hres);
// Fail soft: leave wbemServices NULL so queries return empty results.
// Throwing here would escape callers (e.g. hardware id generation)
// that have no exception handling and crash the host application.
ReportFailure("CoCreateInstance(IWbemLocator)", hres);
wbemLocator = NULL;
return;
}
// Connect to the root\cimv2 namespace with the
@@ -76,12 +79,11 @@ public:
if (FAILED(hres))
{
ReportFailure("ConnectServer(ROOT\\CIMV2)", hres);
wbemLocator->Release();
if (ownCoInitialize)
CoUninitialize();
throw new exception("could not connect to WMI", hres);
wbemLocator = NULL;
wbemServices = NULL;
return;
}
// Set the IWbemServices proxy so that impersonation
@@ -99,10 +101,12 @@ public:
if (FAILED(hres))
{
wbemServices->Release();
wbemLocator->Release();
if (ownCoInitialize) CoUninitialize();
throw new exception("could not connecto to WMI", hres);
ReportFailure("CoSetProxyBlanket", hres);
wbemServices->Release();
wbemLocator->Release();
wbemServices = NULL;
wbemLocator = NULL;
return;
}
}
@@ -115,32 +119,44 @@ public:
void GetPropertyList(const char * wqlQuery, const char * propertyName, list<string> * propList, int maxElements = 0x7FFFFFFF)
{
if (wbemServices == NULL)
return; // WMI unavailable; already reported by the constructor
HRESULT hres;
// For example, query for all the running processes
IEnumWbemClassObject* pEnumerator = NULL;
hres = wbemServices->ExecQuery(
bstr_t("WQL"),
bstr_t("WQL"),
bstr_t(wqlQuery),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
if (FAILED(hres))
{
throw new exception("WMI query failed");
ReportFailure(wqlQuery, hres);
return;
}
else
{
{
IWbemClassObject *pclsObj;
ULONG uReturn = 0;
int numElements = 0;
while (1)
{
hres = pEnumerator->Next(WBEM_INFINITE, 1,
hres = pEnumerator->Next(WBEM_INFINITE, 1,
&pclsObj, &uReturn);
if (FAILED(hres))
{
// An enumeration error is not "no more rows" — report it,
// otherwise a broken WMI silently yields an empty fingerprint
ReportFailure(wqlQuery, hres);
break;
}
if(0 == uReturn)
{
break;
@@ -203,6 +219,12 @@ public:
}
private:
static void ReportFailure(const char * what, HRESULT hres)
{
fprintf(stderr, "[anslicensing] WMI failure (hr=0x%08lX): %s — hardware fingerprint will be degraded\n",
(unsigned long)hres, what);
}
bool ownCoInitialize;
IWbemServices * wbemServices;
IWbemLocator * wbemLocator;