Hosting KVMs as a Business with Python Code

Author: JJustis | Published: 2025-09-25 13:17:25
Article Image 1

Complete Guide: Installing KVM with PayPal IPN Integration and HMAC Token Verification

This comprehensive guide walks through setting up a Kernel-based Virtual Machine (KVM) environment integrated with PayPal's Instant Payment Notification (IPN) system, implementing secure token verification using HMAC signatures, and creating a robust storage system for purchase receipts and access control. This solution is ideal for businesses offering virtualized services or software access through automated payment processing.

The integration creates a seamless workflow where customer purchases trigger automated provisioning of KVM resources while maintaining security through cryptographic verification and comprehensive audit trails. This approach ensures both payment integrity and resource allocation accuracy, essential for commercial virtualization services.

Prerequisites and System Requirements

Before beginning the installation process, ensure your system meets the necessary requirements and you have administrative access to configure both server components and PayPal merchant settings. The implementation requires careful attention to security considerations, as it handles both financial transactions and system resource allocation.

Component Minimum Requirements Recommended Specifications
Operating System Ubuntu 20.04 LTS or CentOS 8 Ubuntu 22.04 LTS with latest security updates
RAM 8GB for host system 32GB+ for multiple VM instances
CPU Intel VT-x or AMD-V support Multi-core processor with hardware virtualization
Storage 100GB SSD for system and VMs 1TB+ NVMe SSD with backup storage
Network Static IP address Redundant network connections with SSL certificates

Phase 1: KVM Installation and Configuration

The first phase involves installing and configuring KVM on your host system, establishing the virtualization foundation that will later integrate with the payment processing system. This installation must be performed with security considerations in mind, as the system will eventually handle automated resource provisioning based on financial transactions.

Step 1: Install KVM and Required Packages

Begin by updating your system packages and installing the KVM hypervisor along with management tools. The installation process varies slightly depending on your Linux distribution, but the core components remain consistent across platforms.

Distribution Installation Commands
Ubuntu/Debian sudo apt update && sudo apt install qemu-kvm libvirt-daemon-system libvirt-clients bridge-utils
CentOS/RHEL sudo dnf install qemu-kvm libvirt libvirt-python3 libguestfs-tools virt-install
Fedora sudo dnf install @virtualization

Step 2: Configure User Permissions and Groups

Add your user account to the appropriate groups to manage KVM without requiring root privileges for every operation. This configuration is crucial for the automated provisioning system that will be triggered by PayPal IPN notifications.

Step 3: Verify KVM Installation

Test your KVM installation to ensure hardware virtualization is properly enabled and accessible. Use the command virsh list --all to verify that the libvirt service is running correctly and can manage virtual machines.

Phase 2: PayPal IPN Integration Setup

The second phase involves configuring PayPal's Instant Payment Notification system to communicate with your server when payments are completed. This integration forms the bridge between customer purchases and automated resource provisioning, requiring careful attention to security and reliability.

PayPal IPN sends HTTP POST notifications to your server whenever payment-related events occur, including successful payments, refunds, and subscription changes. Your server must respond appropriately to these notifications while verifying their authenticity to prevent fraudulent requests from triggering resource allocation.

IPN Configuration Element Required Setting Security Consideration
Notification URL https://yourdomain.com/paypal-ipn Must use HTTPS with valid SSL certificate
Character Encoding UTF-8 Prevents encoding-based security vulnerabilities
Response Timeout 30 seconds maximum PayPal expects timely acknowledgment
Verification Method POST back to PayPal Always verify notification authenticity

Configuring PayPal Merchant Account

Log into your PayPal business account and navigate to the IPN settings section. Enable IPN notifications and specify the URL where your server will receive payment notifications. This URL must be publicly accessible and capable of handling POST requests with payment data.

Setting Up IPN Handler Script

Create a server-side script that receives IPN notifications, verifies their authenticity by posting back to PayPal, and processes confirmed payments. This script serves as the critical link between payment completion and VM provisioning, making its reliability and security paramount.

Phase 3: HMAC Token Verification Implementation

The third phase implements Hash-based Message Authentication Code (HMAC) verification to ensure the integrity and authenticity of all payment-related communications. This cryptographic approach provides an additional security layer beyond PayPal's standard IPN verification, protecting against sophisticated attack vectors.

HMAC verification involves generating cryptographic signatures using a shared secret key, allowing your system to verify that incoming requests originate from legitimate sources and have not been tampered with during transmission. This approach is particularly important when automating resource allocation based on payment notifications.

HMAC Component Implementation Details
Hash Algorithm SHA-256 (recommended) or SHA-512 for enhanced security
Secret Key Management Store in environment variables or secure configuration files
Token Generation Include timestamp, payment ID, and amount in signature
Verification Process Compare received signature with locally generated signature
Key Rotation Implement periodic key updates for enhanced security

Generating Secure HMAC Tokens

Implement a token generation system that creates unique HMAC signatures for each transaction, incorporating relevant payment data and timestamp information. These tokens serve as unforgeable proof of payment authorization, enabling your system to confidently provision resources based on verified payment notifications.

Token Validation Workflow

Design a validation workflow that checks incoming HMAC tokens against locally generated signatures using the same input data and secret key. Failed validation should result in request rejection and security logging, while successful validation triggers the automated provisioning process.

Phase 4: HMAC Folder Structure and Receipt Storage

The fourth phase establishes a secure file system structure for storing purchase receipts, transaction records, and access control information. This system must maintain data integrity while providing efficient access for both automated processes and administrative oversight.

The folder structure organizes data hierarchically, with separate directories for different types of information and access levels. This organization facilitates both automated processing and manual auditing while maintaining clear separation between different data categories.

Directory Structure Purpose Access Permissions
/var/lib/kvm-payments/receipts/ Store individual purchase receipts and transaction details Read-write for payment processor, read-only for web server
/var/lib/kvm-payments/hmac-tokens/ Archive validated HMAC tokens for audit purposes Write-only for payment processor, admin access only
/var/lib/kvm-payments/user-access/ Maintain user access rights and VM assignment records Read-write for provisioning system, read for monitoring
/var/lib/kvm-payments/logs/ Security logs and transaction processing records Append-only for applications, admin read access

Receipt Storage Format

Implement a standardized format for storing purchase receipts that includes all relevant transaction information, customer details, and provisioned resource specifications. This format should support both automated processing and human readability for customer service purposes.

Access Control Implementation

Configure file system permissions and access controls to ensure that sensitive payment information remains secure while allowing necessary system components to function correctly. Use principles of least privilege to minimize security exposure while maintaining operational functionality.

Phase 5: Automated VM Provisioning Integration

The fifth phase connects the payment verification system with KVM management, enabling automated virtual machine provisioning based on confirmed payments. This integration must handle various payment scenarios while maintaining system security and resource allocation accuracy.

The provisioning system monitors the payment processing pipeline and automatically creates, configures, and starts virtual machines based on purchase specifications. This automation reduces manual overhead while ensuring consistent resource delivery to customers.

Provisioning Step Process Details Error Handling
Payment Verification Validate IPN notification and HMAC token authenticity Log failures and alert administrators
Resource Allocation Create VM with specifications matching purchase package Rollback on failure, notify customer of delay
Network Configuration Assign IP addresses and configure virtual networking Clean up partial configurations on failure
Access Credentials Generate secure login credentials and delivery method Regenerate credentials if delivery fails
Customer Notification Send confirmation email with access instructions Queue notifications for retry on delivery failure

Integration Script Development

Develop scripts that bridge the payment verification system with KVM management tools, handling the complete workflow from payment confirmation to resource delivery. These scripts must be robust enough to handle edge cases and failures gracefully while maintaining audit trails for all operations.

Phase 6: Security Hardening and Monitoring

The final phase implements comprehensive security measures and monitoring systems to protect both the payment processing infrastructure and virtual machine resources. This security layer is essential for maintaining customer trust and regulatory compliance in commercial environments.

Security hardening involves multiple layers of protection, from network-level filtering to application-level validation, ensuring that the system remains secure against both automated attacks and sophisticated threats. Regular security auditing and monitoring enable proactive threat detection and response.

Security Measure Implementation Approach Monitoring Requirements
Firewall Configuration Restrict access to essential ports and services only Log all connection attempts and unusual traffic patterns
SSL/TLS Implementation Use strong ciphers and regularly update certificates Monitor certificate expiration and connection security
Input Validation Sanitize all external input before processing Log validation failures and potential attack attempts
Access Logging Record all payment processing and VM management activities Real-time alerting for suspicious access patterns

Backup and Recovery Planning

Implement comprehensive backup strategies for both payment records and virtual machine data, ensuring business continuity in case of system failures. Regular testing of recovery procedures validates backup integrity and restoration processes.

Compliance Considerations

Ensure that the implemented system meets relevant compliance requirements for payment processing and data protection, including PCI DSS standards for payment card information and local data protection regulations. Regular compliance audits help maintain certification and customer trust.

Troubleshooting Common Issues

During implementation and operation, several common issues may arise that require systematic troubleshooting approaches. Understanding these potential problems and their solutions helps maintain system reliability and customer satisfaction.

Common Issue Symptoms Resolution Steps
IPN Verification Failures PayPal notifications marked as invalid Check SSL certificates, verify POST-back URL, review character encoding
HMAC Token Mismatches Valid payments rejected due to signature verification failure Verify secret key consistency, check timestamp synchronization, review token generation algorithm
VM Provisioning Failures Payments processed but virtual machines not created Check KVM service status, verify resource availability, review provisioning script logs
Storage Permission Issues Receipt storage failures or access denied errors Review file system permissions, check directory ownership, verify SELinux/AppArmor policies

Maintaining detailed logs throughout all system components enables effective troubleshooting when issues arise. Regular system monitoring and proactive maintenance help prevent many common problems before they impact customers.

Additional Resources and Documentation:

# ================================================================= # PAYWALL SITE WITH KVM ALLOCATION SYSTEM # Complete implementation with PayPal IPN and HMAC verification # ================================================================= import os import json import hmac import hashlib import time import uuid import subprocess import urllib.request import urllib.parse from datetime import datetime, timedelta from flask import Flask, request, render_template, redirect, url_for, jsonify, session from werkzeug.security import generate_password_hash, check_password_hash import sqlite3 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # ================================================================= # CONFIGURATION AND SETUP # ================================================================= app = Flask(__name__) app.secret_key = os.environ.get('SECRET_KEY', 'your-secret-key-here') # PayPal Configuration PAYPAL_CLIENT_ID = os.environ.get('PAYPAL_CLIENT_ID') PAYPAL_CLIENT_SECRET = os.environ.get('PAYPAL_CLIENT_SECRET') PAYPAL_SANDBOX = os.environ.get('PAYPAL_SANDBOX', 'true').lower() == 'true' PAYPAL_IPN_URL = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr' if PAYPAL_SANDBOX else 'https://ipnpb.paypal.com/cgi-bin/webscr' # HMAC Configuration HMAC_SECRET_KEY = os.environ.get('HMAC_SECRET_KEY', 'your-hmac-secret-key') # KVM Configuration KVM_BASE_PATH = '/var/lib/libvirt/images/' KVM_NETWORK_BRIDGE = 'virbr0' # Storage Paths RECEIPT_STORAGE_PATH = '/var/lib/kvm-payments/receipts/' HMAC_TOKEN_PATH = '/var/lib/kvm-payments/hmac-tokens/' USER_ACCESS_PATH = '/var/lib/kvm-payments/user-access/' LOGS_PATH = '/var/lib/kvm-payments/logs/' # VM Plans Configuration VM_PLANS = { 'basic': { 'name': 'Basic VM', 'price': 9.99, 'ram': '1GB', 'cpu': 1, 'storage': '20GB', 'description': 'Perfect for development and testing' }, 'standard': { 'name': 'Standard VM', 'price': 19.99, 'ram': '2GB', 'cpu': 2, 'storage': '40GB', 'description': 'Ideal for small applications' }, 'premium': { 'name': 'Premium VM', 'price': 39.99, 'ram': '4GB', 'cpu': 4, 'storage': '80GB', 'description': 'High performance for demanding workloads' } } # ================================================================= # DATABASE SETUP # ================================================================= def init_database(): """Initialize SQLite database for user and transaction management""" conn = sqlite3.connect('paywall_kvm.db') cursor = conn.cursor() # Users table cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, active BOOLEAN DEFAULT TRUE ) ''') # Transactions table cursor.execute(''' CREATE TABLE IF NOT EXISTS transactions ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, paypal_txn_id TEXT UNIQUE NOT NULL, amount REAL NOT NULL, plan_type TEXT NOT NULL, status TEXT DEFAULT 'pending', vm_id TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, verified_at TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users (id) ) ''') # VM Instances table cursor.execute(''' CREATE TABLE IF NOT EXISTS vm_instances ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, transaction_id INTEGER, vm_name TEXT UNIQUE NOT NULL, vm_id TEXT UNIQUE NOT NULL, plan_type TEXT NOT NULL, ip_address TEXT, status TEXT DEFAULT 'creating', access_credentials TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, expires_at TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users (id), FOREIGN KEY (transaction_id) REFERENCES transactions (id) ) ''') conn.commit() conn.close() # ================================================================= # UTILITY FUNCTIONS # ================================================================= def generate_hmac_token(data_dict): """Generate HMAC token for transaction verification""" # Create sorted string from data dictionary data_string = '&'.join([f"{k}={v}" for k, v in sorted(data_dict.items())]) signature = hmac.new( HMAC_SECRET_KEY.encode(), data_string.encode(), hashlib.sha256 ).hexdigest() return signature def verify_hmac_token(data_dict, received_signature): """Verify HMAC token authenticity""" expected_signature = generate_hmac_token(data_dict) return hmac.compare_digest(expected_signature, received_signature) def log_security_event(event_type, details, ip_address=None): """Log security events for monitoring""" timestamp = datetime.now().isoformat() log_entry = { 'timestamp': timestamp, 'event_type': event_type, 'details': details, 'ip_address': ip_address } log_file = os.path.join(LOGS_PATH, f"security_{datetime.now().strftime('%Y%m%d')}.log") os.makedirs(LOGS_PATH, exist_ok=True) with open(log_file, 'a') as f: f.write(json.dumps(log_entry) + '\n') def store_receipt(transaction_data): """Store transaction receipt in secure folder structure""" receipt_id = str(uuid.uuid4()) receipt_file = os.path.join(RECEIPT_STORAGE_PATH, f"{receipt_id}.json") os.makedirs(RECEIPT_STORAGE_PATH, exist_ok=True) receipt_data = { 'receipt_id': receipt_id, 'timestamp': datetime.now().isoformat(), 'transaction': transaction_data } with open(receipt_file, 'w') as f: json.dump(receipt_data, f, indent=2) return receipt_id def store_hmac_token(token_data): """Archive HMAC token for audit purposes""" token_file = os.path.join(HMAC_TOKEN_PATH, f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}.json") os.makedirs(HMAC_TOKEN_PATH, exist_ok=True) with open(token_file, 'w') as f: json.dump(token_data, f, indent=2) # ================================================================= # KVM MANAGEMENT FUNCTIONS # ================================================================= class KVMManager: """Manage KVM virtual machines for automated provisioning""" def __init__(self): self.base_path = KVM_BASE_PATH def create_vm(self, vm_name, plan_type, user_email): """Create and configure new VM based on plan specifications""" try: plan = VM_PLANS.get(plan_type) if not plan: raise ValueError(f"Invalid plan type: {plan_type}") # Generate unique VM identifier vm_id = f"vm_{user_email.split('@')[0]}_{int(time.time())}" # Create VM disk image disk_path = os.path.join(self.base_path, f"{vm_id}.qcow2") disk_size = plan['storage'].replace('GB', 'G') subprocess.run([ 'qemu-img', 'create', '-f', 'qcow2', disk_path, disk_size ], check=True) # Install base OS (Ubuntu 22.04 LTS) iso_path = '/var/lib/libvirt/images/ubuntu-22.04-server.iso' vm_config = f''' {vm_id} {int(plan["ram"].replace("GB", "")) * 1024 * 1024} {plan["cpu"]} hvm ''' # Create VM from XML configuration config_file = f"/tmp/{vm_id}_config.xml" with open(config_file, 'w') as f: f.write(vm_config) subprocess.run(['virsh', 'define', config_file], check=True) subprocess.run(['virsh', 'start', vm_id], check=True) # Generate access credentials vm_password = self.generate_secure_password() # Get assigned IP address (simplified - in production, use DHCP reservation) ip_address = self.get_vm_ip_address(vm_id) os.remove(config_file) # Clean up temporary config file return { 'vm_id': vm_id, 'vm_name': vm_name, 'ip_address': ip_address, 'username': 'ubuntu', 'password': vm_password, 'status': 'running' } except subprocess.CalledProcessError as e: log_security_event('vm_creation_failed', {'error': str(e), 'vm_name': vm_name}) raise Exception(f"Failed to create VM: {str(e)}") def get_vm_ip_address(self, vm_id): """Get IP address assigned to VM (simplified implementation)""" try: # In production, use proper DHCP lease parsing or libvirt network APIs result = subprocess.run(['virsh', 'domifaddr', vm_id], capture_output=True, text=True, check=True) # Parse output to extract IP (implementation depends on network setup) return "192.168.122.100" # Placeholder - implement proper IP detection except: return "IP_PENDING" def generate_secure_password(self): """Generate secure random password for VM access""" import secrets import string alphabet = string.ascii_letters + string.digits + "!@#$%^&*" return ''.join(secrets.choice(alphabet) for _ in range(16)) def delete_vm(self, vm_id): """Delete VM and associated resources""" try: subprocess.run(['virsh', 'destroy', vm_id], check=True) subprocess.run(['virsh', 'undefine', vm_id, '--remove-all-storage'], check=True) return True except subprocess.CalledProcessError: return False # ================================================================= # WEB ROUTES - PAYWALL FRONTEND # ================================================================= @app.route('/') def index(): """Main paywall landing page""" return render_template('index.html', plans=VM_PLANS) @app.route('/register', methods=['GET', 'POST']) def register(): """User registration page""" if request.method == 'POST': email = request.form.get('email') password = request.form.get('password') if not email or not password: return render_template('register.html', error='Email and password required') conn = sqlite3.connect('paywall_kvm.db') cursor = conn.cursor() # Check if user already exists cursor.execute('SELECT id FROM users WHERE email = ?', (email,)) if cursor.fetchone(): conn.close() return render_template('register.html', error='Email already registered') # Create new user password_hash = generate_password_hash(password) cursor.execute('INSERT INTO users (email, password_hash) VALUES (?, ?)', (email, password_hash)) conn.commit() conn.close() session['user_email'] = email return redirect(url_for('dashboard')) return render_template('register.html') @app.route('/login', methods=['GET', 'POST']) def login(): """User login page""" if request.method == 'POST': email = request.form.get('email') password = request.form.get('password') conn = sqlite3.connect('paywall_kvm.db') cursor = conn.cursor() cursor.execute('SELECT password_hash FROM users WHERE email = ?', (email,)) user = cursor.fetchone() conn.close() if user and check_password_hash(user[0], password): session['user_email'] = email return redirect(url_for('dashboard')) return render_template('login.html', error='Invalid credentials') return render_template('login.html') @app.route('/dashboard') def dashboard(): """User dashboard showing VMs and purchase options""" if 'user_email' not in session: return redirect(url_for('login')) conn = sqlite3.connect('paywall_kvm.db') cursor = conn.cursor() # Get user VMs cursor.execute(''' SELECT vm_name, ip_address, status, plan_type, created_at, expires_at FROM vm_instances vi JOIN users u ON vi.user_id = u.id WHERE u.email = ? ORDER BY created_at DESC ''', (session['user_email'],)) user_vms = cursor.fetchall() conn.close() return render_template('dashboard.html', vms=user_vms, plans=VM_PLANS) @app.route('/purchase/') def purchase(plan_type): """Purchase page with PayPal integration""" if 'user_email' not in session: return redirect(url_for('login')) if plan_type not in VM_PLANS: return redirect(url_for('dashboard')) plan = VM_PLANS[plan_type] # Generate HMAC token for this purchase purchase_data = { 'user_email': session['user_email'], 'plan_type': plan_type, 'amount': str(plan['price']), 'timestamp': str(int(time.time())) } hmac_token = generate_hmac_token(purchase_data) return render_template('purchase.html', plan=plan, plan_type=plan_type, hmac_token=hmac_token, purchase_data=purchase_data, paypal_client_id=PAYPAL_CLIENT_ID) # ================================================================= # PAYPAL IPN HANDLER # ================================================================= @app.route('/paypal-ipn', methods=['POST']) def handle_paypal_ipn(): """Handle PayPal Instant Payment Notifications""" try: # Log IPN receipt log_security_event('ipn_received', { 'content_length': request.content_length, 'content_type': request.content_type }, request.remote_addr) # Get IPN data ipn_data = request.form.to_dict() # Verify IPN with PayPal verify_data = 'cmd=_notify-validate&' + '&'.join([f'{k}={v}' for k, v in ipn_data.items()]) req = urllib.request.Request(PAYPAL_IPN_URL, verify_data.encode()) req.add_header('Content-Type', 'application/x-www-form-urlencoded') response = urllib.request.urlopen(req) verification_result = response.read().decode() if verification_result != 'VERIFIED': log_security_event('ipn_verification_failed', { 'verification_result': verification_result, 'ipn_data': ipn_data }, request.remote_addr) return 'INVALID', 400 # Extract and verify HMAC token from custom field custom_data = json.loads(ipn_data.get('custom', '{}')) received_hmac = custom_data.get('hmac_token') # Reconstruct original purchase data for HMAC verification purchase_data = { 'user_email': custom_data.get('user_email'), 'plan_type': custom_data.get('plan_type'), 'amount': ipn_data.get('mc_gross'), 'timestamp': custom_data.get('timestamp') } if not verify_hmac_token(purchase_data, received_hmac): log_security_event('hmac_verification_failed', { 'purchase_data': purchase_data, 'received_hmac': received_hmac }, request.remote_addr) return 'INVALID HMAC', 400 # Store HMAC token for audit store_hmac_token({ 'hmac_token': received_hmac, 'purchase_data': purchase_data, 'ipn_data': ipn_data, 'verification_result': verification_result, 'timestamp': datetime.now().isoformat() }) # Process successful payment if ipn_data.get('payment_status') == 'Completed': process_completed_payment(ipn_data, custom_data) return 'OK', 200 except Exception as e: log_security_event('ipn_processing_error', { 'error': str(e), 'ipn_data': ipn_data if 'ipn_data' in locals() else 'unavailable' }, request.remote_addr) return 'ERROR', 500 def process_completed_payment(ipn_data, custom_data): """Process completed payment and provision VM""" try: conn = sqlite3.connect('paywall_kvm.db') cursor = conn.cursor() # Get user ID cursor.execute('SELECT id FROM users WHERE email = ?', (custom_data['user_email'],)) user = cursor.fetchone() if not user: raise ValueError(f"User not found: {custom_data['user_email']}") user_id = user[0] # Check for duplicate transaction cursor.execute('SELECT id FROM transactions WHERE paypal_txn_id = ?', (ipn_data['txn_id'],)) if cursor.fetchone(): log_security_event('duplicate_transaction', { 'txn_id': ipn_data['txn_id'], 'user_email': custom_data['user_email'] }) return # Store transaction record cursor.execute(''' INSERT INTO transactions (user_id, paypal_txn_id, amount, plan_type, status, verified_at) VALUES (?, ?, ?, ?, 'completed', ?) ''', (user_id, ipn_data['txn_id'], ipn_data['mc_gross'], custom_data['plan_type'], datetime.now())) transaction_id = cursor.lastrowid # Store receipt receipt_data = { 'transaction_id': transaction_id, 'paypal_data': ipn_data, 'custom_data': custom_data, 'user_id': user_id } receipt_id = store_receipt(receipt_data) # Provision VM kvm_manager = KVMManager() vm_name = f"{custom_data['plan_type']}_vm_{user_id}_{int(time.time())}" vm_details = kvm_manager.create_vm(vm_name, custom_data['plan_type'], custom_data['user_email']) # Store VM instance record expires_at = datetime.now() + timedelta(days=30) # 30-day access cursor.execute(''' INSERT INTO vm_instances (user_id, transaction_id, vm_name, vm_id, plan_type, ip_address, status, access_credentials, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ''', (user_id, transaction_id, vm_details['vm_name'], vm_details['vm_id'], custom_data['plan_type'], vm_details['ip_address'], vm_details['status'], json.dumps({ 'username': vm_details['username'], 'password': vm_details['password'] }), expires_at)) conn.commit() conn.close() # Send confirmation email send_vm_access_email(custom_data['user_email'], vm_details, custom_data['plan_type']) log_security_event('vm_provisioned', { 'user_email': custom_data['user_email'], 'vm_id': vm_details['vm_id'], 'transaction_id': ipn_data['txn_id'], 'receipt_id': receipt_id }) except Exception as e: log_security_event('payment_processing_error', { 'error': str(e), 'ipn_data': ipn_data, 'custom_data': custom_data }) raise def send_vm_access_email(user_email, vm_details, plan_type): """Send VM access credentials to user""" # Email configuration (set your SMTP settings) smtp_server = os.environ.get('SMTP_SERVER', 'localhost') smtp_port = int(os.environ.get('SMTP_PORT', '587')) smtp_username = os.environ.get('SMTP_USERNAME') smtp_password = os.environ.get('SMTP_PASSWORD') if not all([smtp_username, smtp_password]): log_security_event('email_config_missing', {'user_email': user_email}) return try: msg = MIMEMultipart() msg['From'] = smtp_username msg['To'] = user_email msg['Subject'] = f'Your {VM_PLANS[plan_type]["name"]} is Ready!' body = f""" Dear Customer, Your virtual machine has been successfully provisioned and is ready for use! VM Details: - Plan: {VM_PLANS[plan_type]['name']} - VM ID: {vm_details['vm_id']} - IP Address: {vm_details['ip_address']} - Username: {vm_details['username']} - Password: {vm_details['password']} You can access your VM via SSH: ssh {vm_details['username']}@{vm_details['ip_address']} Your VM will remain active for 30 days from the purchase date. Thank you for your purchase! """ msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(smtp_username, smtp_password) server.send_message(msg) server.quit() log_security_event('access_email_sent', { 'user_email': user_email, 'vm_id': vm_details['vm_id'] }) except Exception as e: log_security_event('email_send_failed', { 'error': str(e), 'user_email': user_email }) # ================================================================= # ADMIN AND MONITORING ROUTES # ================================================================= @app.route('/admin/status') def admin_status(): """Admin status page for monitoring system health""" # Add authentication check for admin access conn = sqlite3.connect('paywall_kvm.db') cursor = conn.cursor() # Get system statistics cursor.execute('SELECT COUNT(*) FROM users') total_users = cursor.fetchone()[0] cursor.execute('SELECT COUNT(*) FROM transactions WHERE status = "completed"') completed_transactions = cursor.fetchone()[0] cursor.execute('SELECT COUNT(*) FROM vm_instances WHERE status = "running"') active_vms = cursor.fetchone()[0] conn.close() # Get system resource usage try: disk_usage = subprocess.run(['df', '-h', KVM_BASE_PATH], capture_output=True, text=True).stdout memory_usage = subprocess.run(['free', '-h'], capture_output=True, text=True).stdout except: disk_usage = "Unable to retrieve" memory_usage = "Unable to retrieve" stats = { 'total_users': total_users, 'completed_transactions': completed_transactions, 'active_vms': active_vms, 'disk_usage': disk_usage, 'memory_usage': memory_usage } return jsonify(stats) # ================================================================= # APPLICATION INITIALIZATION # ================================================================= if __name__ == '__main__': # Create necessary directories for path in [RECEIPT_STORAGE_PATH, HMAC_TOKEN_PATH, USER_ACCESS_PATH, LOGS_PATH]: os.makedirs(path, exist_ok=True) # Initialize database init_database() # Log startup log_security_event('system_startup', { 'paypal_sandbox': PAYPAL_SANDBOX, 'kvm_base_path': KVM_BASE_PATH }) # Run Flask app app.run(host='0.0.0.0', port=5000, debug=False)