To implement a hardware ID (HWID)–based licensing system, you'll need to integrate HWID generation and verification into both the license creation and validation processes. This ensures that each product key is uniquely tied to a specific machine, preventing unauthorized distribution and use.
Here's a comprehensive guide to modifying your existing code to include HWID-based product key generation and validation:
1. Overview of the Required Changes
-
HWID Generation:
- Generate a unique HWID for each target machine using the provided HWID generation code.
-
License Creation:
- Incorporate the HWID into the product key during license generation.
-
License Validation:
- On the protected script's execution, generate the current machine's HWID and verify it against the HWID embedded in the product key.
-
User Interface Adjustments:
- Update the GUI to handle HWID inputs or automate HWID collection from target machines.
2. Integrate HWID Generation into License Creation
a. Modify the LicenseMaker to Include HWID
We'll adjust the createProductKey function to accept an HWID parameter and include it in the data that's signed and encoded into the product key.
# LicenseMaker.py (continued)
def createProductKey(
signingPrivateKey,
licenseId,
productId,
expirationTime,
hwid,
groupsLength,
licenseIdSize,
productIdSize,
expirationTimeSize,
hashSize
):
logger.info(f"Creating product key with License ID: {licenseId}, Product ID: {productId}, "
f"Expiration Time: {expirationTime}, HWID: {hwid}.")
# Validate HWID length (assuming HWID is a hexadecimal string of 64 characters)
if len(hwid) != 64:
logger.error('HWID must be a 64-character hexadecimal string.')
raise ValueError('HWID must be a 64-character hexadecimal string.')
# Convert HWID from hex to binary
hwid_int = int(hwid, 16)
hwid_bits = format(hwid_int, '064b') # 64 bits for HWID
# Ensure IDs and expiration times fit within their allocated bit sizes
if licenseId >= 2 ** licenseIdSize:
logger.error('License ID is too big for its field size.')
raise ValueError('License ID is too big for its field size.')
if productId >= 2 ** productIdSize:
logger.error('Product ID is too big for its field size.')
raise ValueError('Product ID is too big for its field size.')
if expirationTime >= 2 ** expirationTimeSize:
logger.error('Expiration time is too big for its field size.')
raise ValueError('Expiration time is too big for its field size.')
# Convert IDs and expiration time to binary
licenseId_bits = format(licenseId, f'0{licenseIdSize}b')
productId_bits = format(productId, f'0{productIdSize}b')
expirationTime_bits = format(expirationTime, f'0{expirationTimeSize}b')
# Combine all bits: LicenseID + ProductID + ExpirationTime + HWID
combined_bits = licenseId_bits + productId_bits + expirationTime_bits + hwid_bits
logger.debug(f"Combined bits before hashing: {combined_bits}")
# Hash the combined bits
hash_obj = SHA256.new(long_to_bytes(int(combined_bits, 2)))
logger.debug(f"SHA256 Hash of combined bits: {hash_obj.hexdigest()}")
# Sign the hash
try:
private_key = RSA.import_key(signingPrivateKey)
signature = pkcs1_15.new(private_key).sign(hash_obj)
logger.debug(f"Generated signature: {signature.hex()}")
except (ValueError, TypeError) as e:
logger.exception("Failed to sign the product key data.")
raise
# Convert signature to bits and append to combined bits
signature_bits = ''.join(f'{byte:08b}' for byte in signature)[:hashSize * 8]
final_bits = combined_bits + signature_bits
logger.debug(f"Final bits with signature: {final_bits}")
# Convert final bits to integer, then to bytes
final_int = int(final_bits, 2)
final_bytes = long_to_bytes(final_int)
# Encode to Base32 for readability
product_key_b32 = b32encode(final_bytes).decode('utf-8').strip('=')
logger.debug(f"Product key in Base32: {product_key_b32}")
# Format product key with hyphens if groupsLength is specified
if groupsLength:
groups = textwrap.wrap(product_key_b32, groupsLength)
formatted_product_key = '-'.join(groups[:4]) # Limit to 4 groups
else:
formatted_product_key = product_key_b32
logger.debug(f"Formatted product key: {formatted_product_key}")
return formatted_product_key
b. Update the LicenseMaker GUI to Collect HWID
Integrate functionality into your GUI to obtain the HWID from the target machine. This can be done by:
- Option A: Allowing manual input of the HWID.
- Option B: Running the HWID generation code directly if LicenseMaker is deployed on target machines.
For this example, we'll implement Option A for flexibility.
# LicenseMaker.py (continued)
import tkinter.simpledialog as simpledialog
class LicenseMakerGUI:
# ... [existing code] ...
def create_widgets(self):
# ... [existing widgets] ...
# Add HWID input section
hwid_frame = tk.LabelFrame(self.master, text="Target Machine HWID", bg='#000000', fg=label_fg)
hwid_frame.pack(fill="x", **padding)
hwid_label = tk.Label(hwid_frame, text="HWID:", bg='#000000', fg=label_fg)
hwid_label.pack(side="left", padx=10, pady=10)
self.hwid_entry = tk.Entry(hwid_frame, width=50, bg=entry_bg, fg=entry_fg, insertbackground='white')
self.hwid_entry.pack(side="left", fill="x", expand=True, padx=(10, 0), pady=10)
hwid_button = tk.Button(hwid_frame, text="Generate HWID", command=self.generate_hwid, bg=button_bg, fg=button_fg)
hwid_button.pack(side="left", padx=10, pady=10)
# ... [rest of the widgets] ...
def generate_hwid(self):
# Run the HWID generator and populate the HWID entry
try:
hwid = generate_unique_hwid()
self.hwid_entry.delete(0, tk.END)
self.hwid_entry.insert(0, hwid)
logger.info(f"Generated HWID: {hwid}")
except Exception as e:
logger.exception("Failed to generate HWID.")
messagebox.showerror("Error", f"Failed to generate HWID: {str(e)}")
Implement the generate_unique_hwid Function:
Ensure that the HWID generation function is accessible within the GUI class.
# LicenseMaker.py (continued)
def generate_unique_hwid():
DWORD = ctypes.c_ulong
WORD = ctypes.c_ushort
LPVOID = ctypes.c_void_p
DWORD_PTR = ctypes.POINTER(DWORD)
class SYSTEM_INFO(ctypes.Structure):
_fields_ = [
("dwOemId", DWORD),
("dwPageSize", DWORD),
("lpMinimumApplicationAddress", LPVOID),
("lpMaximumApplicationAddress", LPVOID),
("dwActiveProcessorMask", DWORD_PTR),
("dwNumberOfProcessors", DWORD),
("dwProcessorType", DWORD),
("dwAllocationGranularity", DWORD),
("wProcessorLevel", WORD),
("wProcessorRevision", WORD)
]
kernel32 = ctypes.windll.kernel32
GetSystemInfo = kernel32.GetSystemInfo
@lru_cache(maxsize=1)
def get_processor_info():
system_info = SYSTEM_INFO()
GetSystemInfo(ctypes.byref(system_info))
return system_info.dwNumberOfProcessors, system_info.wProcessorLevel, system_info.wProcessorRevision, system_info.dwProcessorType
@lru_cache(maxsize=1)
def get_total_memory():
return psutil.virtual_memory().total
def get_total_hash_hwid():
physical_memory = get_total_memory()
num_procs, proc_level, proc_rev, proc_type = get_processor_info()
mod = (physical_memory / max(proc_rev, 1)) % 1
mod_to_int = round(mod, 3) * 1000
calc_hwid = round((proc_level * (proc_rev * physical_memory)) / num_procs, 0)
return f"HW{int(calc_hwid) ^ int(mod_to_int * proc_type)}ID"
@lru_cache(maxsize=1)
def get_computer_name():
buf = ctypes.create_string_buffer(256)
size = ctypes.c_ulong(256)
ctypes.windll.kernel32.GetComputerNameA(buf, ctypes.byref(size))
return buf.value.decode('utf-8')
@lru_cache(maxsize=1)
def get_system_drive_serial_key():
system_drive = os.getenv("SystemDrive", "C:") + "\\"
return system_drive, win32api.GetVolumeInformation(system_drive)[1]
@lru_cache(maxsize=1)
def get_motherboard_serial():
return subprocess.check_output("wmic baseboard get serialnumber", shell=True).decode().split("\n")[1].strip()
@lru_cache(maxsize=1)
def get_bios_serial():
return subprocess.check_output("wmic bios get serialnumber", shell=True).decode().split("\n")[1].strip()
# Generate the unique HWID
hwid_sha256 = hashlib.sha256(
f"{get_total_hash_hwid()}-{get_computer_name()}-{get_system_drive_serial_key()[0]}" +
f"-{get_system_drive_serial_key()[1]}-{get_motherboard_serial()}-{get_bios_serial()}".encode()
).hexdigest()
return hwid_sha256
c. Update the License Generation Process to Include HWID
Modify the generate_all method to collect the HWID and pass it to the createProductKey function.
# LicenseMaker.py (continued)
def generate_all(self):
if not self.selected_file:
messagebox.showerror("Error", "Please select a Python file to protect.")
logger.error("Generate operation aborted: No file selected.")
return
try:
# Retrieve HWID from the HWID entry
hwid = self.hwid_entry.get().strip()
if not hwid:
messagebox.showerror("Error", "Please generate or enter the HWID.")
logger.error("Generate operation aborted: No HWID provided.")
return
if len(hwid) != 64 or not all(c in string.hexdigits for c in hwid):
messagebox.showerror("Error", "HWID must be a 64-character hexadecimal string.")
logger.error("Generate operation aborted: Invalid HWID format.")
return
self.passphrase_value = self.default_passphrase
logger.info("Generating RSA signing keys.")
private_key, public_key = generateSigningKeys()
self.generated_private_key = private_key
self.generated_public_key = public_key
logger.info("Generating AES encrypting key.")
encrypting_key = generateEncryptingKey()
self.generated_encrypting_key = encrypting_key
duration = self.license_duration.get()
logger.info(f"Calculating expiration time for duration: {duration}")
expiration_time = self.calculate_expiration_time(duration)
license_id = 1 # Customize as needed
product_id = 10 # Customize as needed
logger.info(
f"Creating product key with License ID: {license_id}, Product ID: {product_id}, "
f"Expiration Time: {expiration_time}, HWID: {hwid}"
)
product_key = createProductKey(
signingPrivateKey=private_key,
licenseId=license_id,
productId=product_id,
expirationTime=expiration_time,
hwid=hwid,
groupsLength=5,
productIdSize=16,
expirationTimeSize=40,
hashSize=6
)
self.generated_product_key = product_key
with open('product_license.key', 'w') as license_file:
license_file.write(product_key)
logger.info("Product license key saved to 'product_license.key'.")
logger.info("Configuring license computation.")
configuration = configureLicenseComputation(
verifyingPublicKey=public_key,
encryptingKey=encrypting_key,
expectedProductIds=product_id,
licenseIdSize=24,
productIdSize=16,
expirationTimeSize=40,
hashSize=6
)
logger.info("Encrypting the selected Python file and creating the protected script.")
encrypted_content, iv = encrypt_file(self.selected_file, encrypting_key)
encrypted_content_b64 = base64.b64encode(encrypted_content).decode('utf-8')
iv_b64 = base64.b64encode(iv).decode('utf-8')
encrypted_private_key_b64 = encrypt_private_key(private_key, self.passphrase_value)
with open('private_key_encrypted.b64', 'w') as key_file:
key_file.write(encrypted_private_key_b64)
logger.info("Encrypted RSA private key saved to 'private_key_encrypted.b64'.")
with open('public_key.pem', 'wb') as pub_key_file:
pub_key_file.write(public_key)
logger.info("RSA public key saved to 'public_key.pem'.")
with open('encrypting_key.b64', 'w') as key_file:
key_file.write(base64.b64encode(encrypting_key).decode('utf-8'))
logger.info("AES encrypting key saved to 'encrypting_key.b64'.")
# Create the protected script
protected_script_name = f"protected_{os.path.basename(self.selected_file)}"
create_protected_script(encrypted_content_b64, iv_b64, output_file=protected_script_name)
# Embed the license setup into the original script
self.embed_license_in_script(protected_script_name)
self.display_output(public_key, product_key, expiration_time, protected_script_name)
logger.info("Keys and License generated and protected script created successfully.")
messagebox.showinfo("Success", "Keys and License generated successfully!\nProtected script created.")
except Exception as e:
logger.exception("An error occurred during key and license generation.")
messagebox.showerror("Error", f"An error occurred: {str(e)}")
3. Modify the Validation Process to Check HWID
Update the readProductKey function and the validate function in runtime.py to extract and verify the HWID from the product key.
a. Update readProductKey to Extract HWID
# utils.py (continued)
def readProductKey(
verifyingPublicKeyInstance,
licenseIdSize,
productIdSize,
expirationTimeSize,
hashSize,
hwidSize,
productKey
):
try:
productKey = productKey.strip().replace('-', '').replace(' ', '')
productKeyBytes = b32decode((productKey + '=' * (-len(productKey) % 8)).encode('utf-8'))
productKeyLong = bytes_to_long(productKeyBytes)
decrypted_long = verifyingPublicKeyInstance._encrypt(productKeyLong)
bitString = ('{:0' + str(licenseIdSize + productIdSize + expirationTimeSize + hwidSize + hashSize * 8) + 'b}').format(
decrypted_long
)
# Extract fields based on bit sizes
licenseId = int(bitString[:licenseIdSize], 2)
productId = int(bitString[licenseIdSize:licenseIdSize + productIdSize], 2)
expirationTime = int(
bitString[licenseIdSize + productIdSize:licenseIdSize + productIdSize + expirationTimeSize], 2
)
hwid_int = int(bitString[licenseIdSize + productIdSize + expirationTimeSize:
licenseIdSize + productIdSize + expirationTimeSize + hwidSize], 2)
hwid = format(hwid_int, '064x') # Convert back to hex string
computedHash = int(bitString[-hashSize * 8:], 2)
# Generate current HWID
current_hwid = generate_unique_hwid()
if hwid.lower() != current_hwid.lower():
raise InvalidProductKey("HWID does not match.")
# Verify hash
shake = SHAKE256.new()
shake.update(bitString[:licenseIdSize + productIdSize + expirationTimeSize + hwidSize].encode('utf-8'))
if computedHash != bytes_to_long(shake.read(hashSize)):
raise InvalidProductKey()
return {
'licenseId': licenseId,
'productId': productId,
'expirationTime': expirationTime,
'hwid': hwid
}
except Exception as e:
logger.exception("Failed to read or validate the product key.")
raise InvalidProductKey()
b. Update the validate Function in runtime.py
Ensure that the validate function leverages the updated readProductKey to perform HWID verification.
# runtime.py (continued)
from utils2 import readProductKey # Ensure this import is correct
import logging
logger = logging.getLogger(__name__)
class InvalidProductKey(Exception):
def __init__(self, message='Invalid product key.'):
super().__init__(message)
class ExpiredLicense(Exception):
def __init__(self, message='License has expired.'):
super().__init__(message)
def validate():
try:
license_key = readProductKey(
verifyingPublicKeyInstance=_verifyingPublicKey,
licenseIdSize=_licenseIdSize,
productIdSize=_productIdSize,
expirationTimeSize=_expirationTimeSize,
hashSize=_hashSize,
hwidSize=64, # 64 bits for HWID
productKey=readProductKey(self.productKey) # Adjust as needed
)
current_time = int(time.time())
if current_time > license_key['expirationTime']:
raise ExpiredLicense()
logger.info(f"License validated successfully for HWID: {license_key['hwid']}")
return license_key
except InvalidProductKey as e:
logger.error(str(e))
raise
except ExpiredLicense as e:
logger.error(str(e))
raise
except Exception as e:
logger.exception("An unexpected error occurred during license validation.")
raise InvalidProductKey()
4. Update the Protected Script to Validate HWID
Ensure that the protected script performs HWID validation before decrypting and executing the original code.
# protector.py (continued)
def validate_license():
try:
license_info = validate()
expiration_date = time.strftime(
'%Y-%m-%d %H:%M:%S',
time.localtime(license_info['expirationTime'])
)
logger.info(f"License is valid. Expires on {expiration_date}. HWID: {license_info['hwid']}")
return True
except ExpiredLicense as e:
logger.error(str(e))
messagebox.showerror("License Expired", str(e))
except InvalidProductKey as e:
logger.error(str(e))
messagebox.showerror("Invalid License", str(e))
except Exception as e:
logger.exception("An unexpected error occurred during license validation.")
messagebox.showerror("Error", "An unexpected error occurred during license validation.")
return False
def main():
license_key = input("Enter your license key: ").strip()
logger.info("License key entered.")
if not validate_license():
print("License validation failed.")
return
try:
with open('public_key.pem', 'rb') as f:
public_key = f.read()
with open('encrypting_key.b64', 'r') as f:
encrypting_key_b64 = f.read().strip()
configure(
productKey=license_key,
verifyingPublicKey=public_key,
encryptingKey=base64.b64decode(encrypting_key_b64),
expectedProductIds=10,
licenseIdSize=24,
productIdSize=16,
expirationTimeSize=40,
hashSize=6
)
logger.info("Runtime configured successfully.")
except Exception as e:
logger.exception("Failed to configure runtime.")
print(f"Runtime configuration failed: {str(e)}")
return
try:
decrypted_content = decrypt_content(encrypted_content_b64, iv_b64, encrypting_key_b64)
exec(decrypted_content, globals())
except Exception as e:
logger.exception("Failed to decrypt or execute the original script.")
print(f"Failed to execute the script: {str(e)}")
5. Updating the HWID Generation Code
Ensure that the HWID generation code is reliable and consistent across both license creation and validation. Here's a refined version of your HWID generator:
# LicenseMaker.py or a separate module (e.g., hwid.py)
import hashlib
import psutil
import ctypes
import win32api
import os
import subprocess
from functools import lru_cache
def generate_unique_hwid():
DWORD = ctypes.c_ulong
WORD = ctypes.c_ushort
LPVOID = ctypes.c_void_p
DWORD_PTR = ctypes.POINTER(DWORD)
class SYSTEM_INFO(ctypes.Structure):
_fields_ = [
("dwOemId", DWORD),
("dwPageSize", DWORD),
("lpMinimumApplicationAddress", LPVOID),
("lpMaximumApplicationAddress", LPVOID),
("dwActiveProcessorMask", DWORD_PTR),
("dwNumberOfProcessors", DWORD),
("dwProcessorType", DWORD),
("dwAllocationGranularity", DWORD),
("wProcessorLevel", WORD),
("wProcessorRevision", WORD)
]
kernel32 = ctypes.windll.kernel32
GetSystemInfo = kernel32.GetSystemInfo
@lru_cache(maxsize=1)
def get_processor_info():
system_info = SYSTEM_INFO()
GetSystemInfo(ctypes.byref(system_info))
return system_info.dwNumberOfProcessors, system_info.wProcessorLevel, system_info.wProcessorRevision, system_info.dwProcessorType
@lru_cache(maxsize=1)
def get_total_memory():
return psutil.virtual_memory().total
@lru_cache(maxsize=1)
def get_computer_name():
buf = ctypes.create_string_buffer(256)
size = ctypes.c_ulong(256)
ctypes.windll.kernel32.GetComputerNameA(buf, ctypes.byref(size))
return buf.value.decode('utf-8')
@lru_cache(maxsize=1)
def get_system_drive_serial_key():
system_drive = os.getenv("SystemDrive", "C:") + "\\"
return system_drive, win32api.GetVolumeInformation(system_drive)[1]
@lru_cache(maxsize=1)
def get_motherboard_serial():
return subprocess.check_output("wmic baseboard get serialnumber", shell=True).decode().split("\n")[1].strip()
@lru_cache(maxsize=1)
def get_bios_serial():
return subprocess.check_output("wmic bios get serialnumber", shell=True).decode().split("\n")[1].strip()
# Generate intermediate HWID components
num_procs, proc_level, proc_rev, proc_type = get_processor_info()
physical_memory = get_total_memory()
mod = (physical_memory / max(proc_rev, 1)) % 1
mod_to_int = round(mod, 3) * 1000
calc_hwid = round((proc_level * (proc_rev * physical_memory)) / num_procs, 0)
hwid = f"HW{int(calc_hwid) ^ int(mod_to_int * proc_type)}ID"
# Gather system identifiers
name = get_computer_name()
mb_serial = get_motherboard_serial()
bios_serial = get_bios_serial()
drive, drive_serial = get_system_drive_serial_key()
# Combine all identifiers
combined = f"{hwid}-{name}-{drive}-{drive_serial}-{mb_serial}-{bios_serial}"
# Generate SHA256 hash of the combined string
hwid_sha256 = hashlib.sha256(combined.encode()).hexdigest()
logger.debug(f"Generated HWID: {hwid_sha256}")
return hwid_sha256
Usage:
-
License Creation: Run generate_unique_hwid() on the target machine to obtain its HWID and use it when generating the product key.
-
License Validation: The protected script will automatically generate the current machine's HWID and verify it against the HWID embedded in the product key.
6. Security Considerations
-
Protect Private Keys:
- Ensure the RSA private key is securely stored and never exposed. Consider using secure storage mechanisms or obfuscation techniques.
-
Obfuscate Validation Logic:
- To prevent reverse engineering, obfuscate the license validation code within the protected script. Tools like PyArmor can help with this.
-
Secure HWID Generation:
- Ensure the HWID generation method is robust and not easily spoofed. Avoid relying solely on easily accessible hardware identifiers.
-
Handle Edge Cases:
- Consider scenarios like hardware upgrades that might change HWID and implement a grace period or a reactivation mechanism.
-
Error Handling:
- Provide clear error messages for invalid or expired licenses without revealing sensitive information.
7. Final Steps
-
Testing:
- Thoroughly test the entire flow on multiple machines to ensure that HWID generation, license creation, and validation work seamlessly.
-
Documentation:
- Document the process for generating HWIDs on target machines and guide users on how to obtain and use their licenses.
-
Deployment:
- Package the LicenseMaker tool and the HWID generator for ease of use. Ensure that dependencies like
pywin32 are handled appropriately.
By following these steps, you will successfully integrate HWID-based licensing into your Python application, ensuring that each product key is uniquely tied to a specific machine. This enhances the security of your software and minimizes unauthorized distribution.
If you encounter any issues or need further assistance with specific code segments, feel free to ask!