NeuroAgent

How to Create a License Verification Server in Python/C++

Complete guide to creating a license verification server for Python/C++ programs. Learn about services, alternatives, security issues, and protection improvements.

Question

How to create a server for license verification of a Python/C++ program?

I am developing a program in Python with C++ elements and looking for ways to protect against cracking. The protection method includes:

• Encrypting most program files using a password
• Activating the program through a one-time activation key that is sent to the server
• The server creating an encrypted permanent access key after activation
• Verifying the permanent key on each program launch
• Temporarily decrypting files only during program execution
• Additional measures to protect against copying and running on other PCs

Questions:

  1. What services allow creating a license verification server with the specified requirements?
  2. Besides AWS, Azure, and Google Cloud, are there alternative solutions?
  3. Could cloud services have security issues for my protection scheme?
  4. What recommendations are there for improving my program protection method?
NeuroAgent

Creating a server for verifying program licenses in Python/C++ requires a comprehensive approach to the security and reliability of your application. To protect against cracking with the specified requirements, you should use cloud services or specialized license management platforms that provide authentication, data encryption, and secure storage of activation keys.

Contents


Main Services for License Verification

Several specialized platforms are suitable for creating a license verification server with your requirements:

1. Flexera Software Licensing

Flexera offers powerful solutions for license management, including:

  • Application Manager - for application license management
  • InstallShield with licensing capabilities
  • AdminStudio for deployment and license management

Advantages:

  • Flexible license management
  • Support for various licensing models
  • Integration with cloud services

2. Reprise License Manager

Reprise Software provides a cloud platform for license management:

  • Automated license management
  • Usage tracking
  • API integration for your server

3. Keygen

Keygen - a modern license management platform:

  • RESTful API for integration
  • Support for Python and C++ via SDK
  • Cloud license storage
  • Tools for creating activation keys

Alternative Cloud Solutions

Besides AWS, Azure, and Google Cloud, the following alternatives exist:

1. DigitalOcean

DigitalOcean offers:

  • Budget VPS servers
  • Easy setup
  • Documented API
  • Docker support for containerization

2. Linode

Linode provides:

  • High-performance servers
  • Optimized for development
  • Flexible pricing plans
  • Good documentation

3. Hetzner

Hetzner is known for:

  • Low prices
  • High-quality equipment
  • Reliable services
  • Support for various operating systems

4. Vultr

Vultr offers:

  • Instant server deployment
  • Global network of data centers
  • Integrated services
  • API for automation

Security Issues with Cloud Services

Potential vulnerabilities in your scheme:

1. Traffic interception risk

  • Problem: Man-in-the-middle (MITM) attacks when transmitting keys
  • Solution: Using TLS 1.3 for connection encryption
  • Recommendation: Two-factor authentication for the server

2. Cloud infrastructure vulnerabilities

  • Problem: Vulnerabilities in hypervisors and management systems
  • Solution: Regular system updates
  • Recommendation: Server isolation in a separate network

3. Backup issues

  • Problem: Need for encryption of backup copies of keys
  • Solution: Client-side encryption before sending
  • Recommendation: Using Hardware Security Modules (HSM)

4. Database server attacks

  • Problem: Gaining access to stored activation keys
  • Solution: Database-level data encryption
  • Recommendation: Regular access auditing

Recommendations for Improving Protection

1. Improving Protection Architecture

Multi-factor authentication

python
# Example of multi-factor verification
def verify_license(user_token, device_fingerprint):
    # User token verification
    if not validate_token(user_token):
        return False
    
    # Device fingerprint verification
    if not validate_device(device_fingerprint):
        return False
    
    # Temporary key verification
    if not validate_temp_key():
        return False
    
    return True

Using Hardware Security Modules

Integration with HSM for:

  • Secure key storage
  • Hardware encryption
  • Protection against key extraction

2. Protection Against Program Copying

Hardware binding

cpp
// Example of hardware binding
#include <iostream>
#include <string>
#include <sstream>

std::string getHardwareFingerprint() {
    std::stringstream ss;
    // Collecting unique hardware identifiers
    ss << "CPU_ID:" << getCPUId() << "|";
    ss << "MOTHERBOARD:" << getMotherboardId() << "|";
    ss << "DISK:" << getDiskId();
    return ss.str();
}

Code obfuscation

Using obfuscation tools:

3. Protection Against Debugging and Analysis

Anti-debugging mechanisms

python
# Example of debugger detection
import ctypes
import sys

def is_debugger_present():
    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
    return kernel32.IsDebuggerPresent() != 0

if is_debugger_present():
    # Actions when debugger is detected
    sys.exit(1)

Memory protection

  • Memory section encryption
  • Protection against memory dumping
  • Using ASLR and DEP

Technical Implementation of the Server

License Verification Server Architecture

Server operation diagram

Client (Python/C++) → License ServerDatabase
     ↑                    ↓              ↓
 User Interface → Verification Logic → Key Storage

Technology stack for the server

Backend options:

  • Python: Flask/Django + SQLAlchemy
  • Node.js: Express + MongoDB
  • C++: FastCGI + PostgreSQL

Databases:

  • PostgreSQL with encryption
  • MongoDB with auditing
  • Redis for caching

Example of basic server structure in Python

python
from flask import Flask, request, jsonify
import sqlite3
import hashlib
import secrets

app = Flask(__name__)

def get_db_connection():
    conn = sqlite3.connect('licenses.db')
    conn.row_factory = sqlite3.Row
    return conn

@app.route('/activate', methods=['POST'])
def activate_license():
    data = request.json
    activation_key = data.get('activation_key')
    hardware_id = data.get('hardware_id')
    
    # Activation key verification
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute('SELECT * FROM activation_keys WHERE key = ?', (activation_key,))
    key_data = cursor.fetchone()
    
    if not key_data or key_data['used']:
        return jsonify({'error': 'Invalid activation key'}), 400
    
    # Permanent key generation
    permanent_key = secrets.token_hex(32)
    encrypted_key = encrypt_key(permanent_key, hardware_id)
    
    # Key storage
    cursor.execute(
        'INSERT INTO permanent_keys (user_id, hardware_id, key) VALUES (?, ?, ?)',
        (key_data['user_id'], hardware_id, encrypted_key)
    )
    
    # Mark key as used
    cursor.execute(
        'UPDATE activation_keys SET used = 1 WHERE key = ?',
        (activation_key,)
    )
    
    conn.commit()
    conn.close()
    
    return jsonify({'permanent_key': permanent_key})

@app.route('/verify', methods=['POST'])
def verify_license():
    data = request.json
    permanent_key = data.get('permanent_key')
    hardware_id = data.get('hardware_id')
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    cursor.execute(
        'SELECT * FROM permanent_keys WHERE key = ? AND hardware_id = ?',
        (permanent_key, hardware_id)
    )
    
    license_data = cursor.fetchone()
    conn.close()
    
    if license_data:
        return jsonify({'valid': True})
    else:
        return jsonify({'valid': False}), 401

if __name__ == '__main__':
    app.run(ssl_context='adhoc')  # Run with SSL

Code Examples for License Verification

Client-side in Python

python
import requests
import hashlib
import json
import os
from cryptography.fernet import Fernet

class LicenseManager:
    def __init__(self, server_url):
        self.server_url = server_url
        self.license_file = 'license.dat'
        self.temp_files = []
        
    def activate(self, activation_key):
        """Program activation using activation key"""
        hardware_id = self.get_hardware_id()
        
        response = requests.post(
            f'{self.server_url}/activate',
            json={
                'activation_key': activation_key,
                'hardware_id': hardware_id
            },
            verify=True  # SSL certificate verification
        )
        
        if response.status_code == 200:
            data = response.json()
            self.save_license(data['permanent_key'])
            return True
        return False
    
    def verify_license(self):
        """License verification on startup"""
        if not os.path.exists(self.license_file):
            return False
        
        with open(self.license_file, 'r') as f:
            permanent_key = f.read().strip()
        
        hardware_id = self.get_hardware_id()
        
        response = requests.post(
            f'{self.server_url}/verify',
            json={
                'permanent_key': permanent_key,
                'hardware_id': hardware_id
            },
            verify=True
        )
        
        return response.json().get('valid', False)
    
    def decrypt_files(self):
        """File decryption during program execution"""
        if not self.verify_license():
            raise LicenseError("Invalid license")
        
        # Load license key
        with open(self.license_file, 'r') as f:
            license_key = f.read().strip()
        
        # Generate encryption key from license key
        encryption_key = self.derive_encryption_key(license_key)
        cipher = Fernet(encryption_key)
        
        # Decrypt files
        encrypted_files = ['module1.pyc', 'config.json', 'assets.bin']
        
        for file in encrypted_files:
            if os.path.exists(file):
                self.decrypt_file(file, cipher)
                self.temp_files.append(file)
    
    def encrypt_file(self, filename, cipher):
        """File encryption"""
        with open(filename, 'rb') as f:
            data = f.read()
        
        encrypted_data = cipher.encrypt(data)
        
        with open(filename + '.enc', 'wb') as f:
            f.write(encrypted_data)
        
        os.remove(filename)
    
    def decrypt_file(self, filename, cipher):
        """File decryption"""
        with open(filename + '.enc', 'rb') as f:
            encrypted_data = f.read()
        
        decrypted_data = cipher.decrypt(encrypted_data)
        
        with open(filename, 'wb') as f:
            f.write(decrypted_data)
    
    def get_hardware_id(self):
        """Get unique hardware identifier"""
        try:
            import platform
            import uuid
            
            # Collect system information
            system_info = {
                'machine': platform.machine(),
                'node': platform.node(),
                'processor': platform.processor(),
            }
            
            # Generate hash from system information
            system_string = json.dumps(system_info, sort_keys=True)
            hardware_id = hashlib.sha256(system_string.encode()).hexdigest()
            
            return hardware_id
        except Exception as e:
            print(f"Error getting hardware ID: {e}")
            return hashlib.sha256(b'unknown').hexdigest()
    
    def save_license(self, license_key):
        """Save license key"""
        with open(self.license_file, 'w') as f:
            f.write(license_key)
    
    def derive_encryption_key(self, license_key):
        """Derived encryption key from license key"""
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
        
        password = license_key.encode()
        salt = b'salt'  # In a real application, use a random salt
        
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32,
            salt=salt,
            iterations=100000,
        )
        
        key = kdf.derive(password)
        return Fernet(base64.urlsafe_b64encode(key))

Using LicenseManager

python
# Example of use in the program
if __name__ == "__main__":
    license_manager = LicenseManager('https://your-license-server.com')
    
    # License verification on startup
    if not license_manager.verify_license():
        print("Program not activated")
        activation_key = input("Enter activation key: ")
        
        if license_manager.activate(activation_key):
            print("Program successfully activated")
        else:
            print("Invalid activation key")
            exit(1)
    
    # Decrypt files during execution
    try:
        license_manager.decrypt_files()
        
        # Main program code
        print("Program running")
        
    except LicenseError as e:
        print(f"License error: {e}")
        exit(1)
    finally:
        # Clean up temporary files
        for file in license_manager.temp_files:
            if os.path.exists(file + '.enc'):
                os.remove(file + '.enc')

Conclusion

Key takeaways:

  1. For creating a license verification server with your requirements, specialized platforms like Keygen, Flexera, or Reprise License Manager, as well as alternative cloud services DigitalOcean and Linode, are the best options.

  2. Cloud service security requires additional protection - use TLS 1.3 encryption, server isolation, regular system updates, and two-factor authentication.

  3. Program protection improvement includes multi-factor authentication, hardware binding, code obfuscation, and anti-debugging mechanisms.

  4. Technical implementation should include a RESTful API, client-side data encryption, secure key storage, and regular security auditing.

Practical recommendations:

  • Start with a Python/Flask prototype for concept validation
  • Use DigitalOcean cloud service to save costs
  • Integrate Hardware Security Modules for key protection
  • Implement regular encrypted backups
  • Conduct penetration testing before production launch

Answers to additional questions:

  • Alternatives to AWS/Azure/GCP: DigitalOcean, Linode, Hetzner, Vultr
  • Security: Requires additional protection measures due to vulnerability risks
  • Improvements: Multi-factor authentication, hardware binding, code obfuscation

For further study of the topic, it is recommended to study the documentation of the chosen cloud service and specifications of cryptographic algorithms used in your protection system.

Sources

  1. Flexera Software Licensing Solutions
  2. Reprise License Manager Platform
  3. Keygen Licensing Service
  4. DigitalOcean Cloud Platform
  5. Linode Cloud Hosting
  6. Hetzner Cloud Services
  7. Vultr Cloud Infrastructure
  8. PyArmor Python Obfuscation
  9. ConfuserEx .NET Obfuscation
  10. LLVM Compiler Infrastructure