Technical Documentation v1.0.0 WHMCS 9.1.x · PHP 8.2–8.4

Haikhavan IP Manager & IPAM

Complete architecture reference, installation guide, database schema, hooks, and troubleshooting.

Quick Installation

  1. Purchase the module and download haikhavan_ip_manager-ioncube-8.2-1.0.0-install.zip from your VPSrv Client Area Downloads.
  2. Upload and extract the ZIP into your WHMCS root directory so files land in modules/addons/haikhavan_ip_manager/.
  3. Verify PHP 8.2–8.4 with ionCube PHP Loader 14+ / 15.5+ is enabled on your server.
  4. Go to System Settings → Addon Modules in WHMCS Admin, click Activate next to Haikhavan IP Manager & IPAM, and assign administrator role access.

Version: 1.0.0
Namespace: Haikhavan\IpManager\
Entry Point: modules/addons/haikhavan_ip_manager/haikhavan_ip_manager.php


1. Architecture & File Inventory

modules/addons/haikhavan_ip_manager/
├── haikhavan_ip_manager.php              # Addon config, activate/deactivate/upgrade, Admin & Client dispatchers, autoloader
├── hooks.php                      # 10 WHMCS provisioning, navigation, Admin Client Tab, Home Widget & Cron hooks
├── whmcs.json                     # WHMCS Marketplace 1.0 schema manifest
├── lib/
│   ├── Database.php               # Capsule schema installer (6 tables), settings, AES-256-CBC+HMAC crypto, audit logger
│   ├── CidrMath.php               # Pure-PHP IPv4 & IPv6 CIDR calculator, subnet carver, overlap check, rDNS/PTR builder
│   ├── SubnetService.php          # Hierarchical tree builder, subnet splitting, utilization/exhaustion metrics, heatmap, CSV I/O
│   ├── AllocationService.php      # Rule evaluator, auto/manual IP assignment, quarantine cool-down, tblhosting & PTR sync
│   ├── IntegrationManager.php     # Submodule registry for cPanel/WHM, Plesk, DirectAdmin, Proxmox VE, SolusVM, PowerDNS
│   ├── RblScanner.php             # Multi-provider DNSBL/RBL scanner (Spamhaus, Barracuda, SpamCop, SORBS, UCEPROTECT)
│   ├── AdminController.php        # Admin UI renderer, CSV exporter, CSRF-protected AJAX JSON router
│   └── ClientController.php       # Client Area IP portal, ownership-enforced PTR self-service AJAX handler
├── templates/
│   ├── admin/dashboard.php        # 7-tab Admin Dashboard + interactive heatmap + modals
│   └── client/overview.tpl        # Smarty Client Area template with copyable OS network config modal
└── assets/
    ├── css/haikhavan_ip_manager.css      # Scoped enterprise design system (zero external CDN)
    └── js/haikhavan_ip_manager.js        # Vanilla JS controller + HTML5 Canvas utilization chart + live CIDR preview

2. Database Schema

All 6 tables are created via WHMCS\Database\Capsule::schema() during activation and use parameterized queries exclusively.

2.1 mod_hk_ipam_subnets

Stores the hierarchical IPv4 and IPv6 subnet tree.

Column Type Attributes Purpose
id INT UNSIGNED PK, Auto-Increment Unique subnet ID
parent_id INT UNSIGNED Nullable, Indexed Parent subnet ID (NULL = root pool)
name VARCHAR(191) Not Null Human-readable pool label
ip_version TINYINT UNSIGNED Default 4, Indexed 4 (IPv4) or 6 (IPv6)
cidr VARCHAR(64) Unique Canonical CIDR (e.g. 192.0.2.0/26, 2001:db8:42::/48)
network_address VARCHAR(64) Indexed Canonical network base address
broadcast_address VARCHAR(64) Nullable Broadcast (IPv4) or range end address (IPv6)
netmask VARCHAR(64) Nullable Dotted netmask (IPv4) or full hex mask (IPv6)
prefix_len SMALLINT UNSIGNED Default 24 CIDR prefix length (0–32 / 0–128)
gateway VARCHAR(64) Nullable Default gateway IP
vlan_id INT UNSIGNED Nullable, Indexed Layer-2 VLAN tag
dns_primary / dns_secondary VARCHAR(64) Nullable Default DNS resolvers for clients
datacenter / location / rack VARCHAR(128/64) Nullable Physical DC/Location/Cabinet tagging
server_id INT UNSIGNED Nullable, Indexed Optional FK to tblservers.id
rdns_zone VARCHAR(128) Nullable Reverse DNS zone (in-addr.arpa / ip6.arpa)
total_hosts VARCHAR(64) Default '0' String-encoded usable host count (supports 128-bit IPv6)
reserve_net_bcast TINYINT Default 1 Auto-reserve network & broadcast addresses
alert_threshold_pct SMALLINT UNSIGNED Default 80 Capacity warning threshold (10–100%)
notes TEXT Nullable Routing / BGP / administrative notes
status VARCHAR(24) Default 'active' active | archived

2.2 mod_hk_ipam_ips

Tracks individual IPv4 addresses and delegated IPv6 blocks (e.g., /64 or /128).

Column Type Attributes Purpose
id INT UNSIGNED PK, Auto-Increment Unique IP record ID
subnet_id INT UNSIGNED Indexed Owning subnet (mod_hk_ipam_subnets.id)
ip_version TINYINT UNSIGNED Default 4, Indexed 4 or 6
ip_address VARCHAR(64) Unique Canonical IP string
ip_numeric BIGINT UNSIGNED Indexed Unsigned 32-bit integer for IPv4
ip_hex CHAR(32) Indexed Zero-padded 32-char lowercase hex for uniform IPv4/IPv6 ordering
prefix_len SMALLINT UNSIGNED Default 32 Allocation prefix (32 for IPv4, 64/128 for IPv6)
status VARCHAR(24) Indexed available | assigned | reserved | excluded | quarantined | suspended
userid / service_id / addon_id / server_id INT UNSIGNED Nullable, Indexed WHMCS client, service (tblhosting), addon, and server relations
hostname / ptr_record VARCHAR(191/255) Nullable Assigned hostname and Reverse DNS PTR FQDN
ptr_synced_at TIMESTAMP Nullable Timestamp of last PowerDNS PTR push
assigned_at TIMESTAMP Nullable Assignment timestamp
quarantine_until TIMESTAMP Nullable, Indexed Cool-down expiry timestamp for quarantined IPs
rbl_status VARCHAR(24) Indexed unknown | clean | listed
rbl_listed_count INT UNSIGNED Default 0 Number of blacklists currently listing this IP
rbl_last_checked_at TIMESTAMP Nullable Last RBL scan time
rbl_details_json TEXT Nullable Per-provider DNSBL lookup responses

2.3 mod_hk_ipam_rules

Defines automated IP provisioning, suspension, and termination policies linked to product, server, addon, or configoption (relation_type, relation_id, subnet_id, ipv6_subnet_id, ipv4_count, ipv6_count, ipv6_prefix_len, on_suspend, on_terminate, quarantine_hours, integration_id, auto_ptr_template, priority, enabled).

2.4 mod_hk_ipam_integrations

Stores external control panel, hypervisor, and PowerDNS submodule endpoints (driver, hostname, port, use_ssl, username, credential_encrypted, config_json, server_id, enabled, last_sync_at, last_sync_status, last_sync_message).

2.5 mod_hk_ipam_rbl_scans

Chronological history of every single, bulk, and cron RBL scan (ip_id, ip_address, subnet_id, status, listed_count, checked_lists_count, providers_json, scanned_by, created_at).

2.6 mod_hk_ipam_audit_log

Immutable audit trail recording every admin, client, hook, and cron action (actor_type, actor_id, action, entity_type, entity_id, ip_address, summary, details_json, remote_ip, created_at).


3. CIDR & IPv6 Mathematical Engine (CidrMath)

  • IPv4 Calculations: Uses unsigned 32-bit integer bitmasks (sprintf('%u', ip2long($ip))) avoiding 32-bit signed overflow, deriving canonical network, broadcast, dotted netmask, wildcard, first/last usable host, and in-addr.arpa reverse zone.
  • IPv6 Calculations: Uses 16-byte packed binary arithmetic (inet_pton / inet_ntop + bitmask operations) with gmp / bcmath host count formatting and nibble-reversed ip6.arpa zone derivation.
  • Uniform Sorting & Containment: Both IPv4 (24 leading zero hex nibbles + 8 IPv4 hex chars) and IPv6 (32 hex chars) map to canonical 32-character hex strings (ip_hex), enabling exact lexicographical isSubnetOf(), overlaps(), and ipInCidr() comparisons without precision loss.
  • Subnet Splitting / Carving: splitSubnet($parentCidr, $newPrefix) divides any IPv4 or IPv6 block into $2^{(\text{newPrefix} - \text{parentPrefix})}$ equal child blocks (capped at 32 per operation for safety) and automatically migrates existing parent IP records into their matching child pool.
  • Large Pool Safety: IPv4 subnets up to /22 (1,024 addresses) materialize all host records upon creation; larger blocks materialize network/broadcast/gateway only and remain responsive. IPv6 pools seed gateway + initial /64 delegated blocks on creation.

4. WHMCS Lifecycle & UI Hooks (hooks.php)

Hook Point Priority Behavior
AfterModuleCreate 1 Evaluates active mod_hk_ipam_rules (product, server, configurable options), allocates IPv4/IPv6 (skipping RBL-listed IPs), applies auto_ptr_template, syncs tblhosting, and triggers linked control panel sync.
AfterModuleSuspend 1 Transitions service-linked assigned IPs to suspended and writes an audit record.
AfterModuleUnsuspend 1 Restores suspended IPs back to assigned.
AfterModuleTerminate 1 Applies rule termination policy: places IPs into quarantined cool-down (quarantine_until = NOW + quarantine_hours), releases immediately, or keeps for manual review; syncs tblhosting.
ServiceDelete 1 Prevents orphaned IPs by running termination release/quarantine logic when a service is deleted.
ClientAreaPrimaryNavbar 1 Adds IP Management & rDNS under the Client Area Services dropdown.
ClientAreaPrimarySidebar 1 Adds Assigned IPs & rDNS with live IP count badge on Product Details pages.
AdminClientServicesTabFields 1 Renders assigned IPv4/IPv6, CIDR, Gateway, VLAN, PTR, and RBL badge inside Admin Client Services tab.
AdminHomeWidgets 1 Registers Haikhavan IP Manager & IPAM — Capacity & Reputation widget showing subnet count, assigned/available/quarantined/RBL-listed counts, overall utilization %, and low-capacity pool warnings.
DailyCronJob 1 Releases expired quarantine IPs back to available, runs scheduled RBL scans (up to 100 IPv4/day), and logs subnet capacity exhaustion alerts.

5. Control Panel & PowerDNS Submodules (IntegrationManager)

Driver Protocol & Endpoint Authentication Key Capabilities
cpanel HTTPS :2087 /json-api/version?api.version=1 Authorization: whm user:token Server IP sync, pool management, dedicated IP assignment
plesk HTTPS :8443 /api/v2/server X-API-Key: <key> REST v2 IP listing and pool sync
directadmin HTTPS :2222 /CMD_API_SHOW_RESELLER_IPS HTTP Basic (Login Key) Reseller/User IP allocation sync
proxmox HTTPS :8006 /api2/json/version Authorization: PVEAPIToken=... Cloud-Init ipconfig0 & LXC net0 IP/VLAN sync
solusvm HTTPS :5656 /api/admin/command.php Admin id:key query auth vserver-addip / vserver-delip sync
powerdns HTTP/S :8081 /api/v1/servers/{srv}/zones/{zone} X-API-Key: <key> Automated PATCH PTR RRSet sync for in-addr.arpa & ip6.arpa

6. RBL / DNSBL Blacklist Scanner (RblScanner)

  • Reverses IPv4 octets (a.b.c.d → d.c.b.a.<zone>.) and queries DNS A records via dns_get_record().
  • Default zones: zen.spamhaus.org, b.barracudacentral.org, bl.spamcop.net, dnsbl.sorbs.net, dnsbl-1.uceprotect.net.
  • Validates 127.0.0.x DNSBL return codes while filtering out non-listing error responses; safely detects RFC1918/RFC5737 non-public ranges so local dev subnets never stall on external DNS timeouts.
  • Updates mod_hk_ipam_ips.rbl_status + rbl_listed_count, inserts a historical row into mod_hk_ipam_rbl_scans, and records an rbl_listed_alert audit event whenever a listing is discovered.

7. Security Model

  1. Authenticated Credential Encryption at Rest: All integration tokens/keys are encrypted with AES-256-CBC + HMAC-SHA256 (Encrypt-then-MAC) using HKDF-style domain-separated keys derived from WHMCS $cc_encryption_hash, verified via constant-time hash_equals() prior to decryption.
  2. CSRF Enforcement: Separate 192-bit random session CSRF tokens ($_SESSION['hk_ipam_admin_csrf'] and $_SESSION['hk_ipam_client_csrf']) are verified via hash_equals() on every state-changing POST/AJAX operation (HTTP 403 on failure).
  3. Client Ownership Isolation: Client Area PTR updates strictly verify (int) $ip->userid === (int) $_SESSION['uid'] and enforce FQDN regex validation (CidrMath::isValidPtrHostname()).
  4. Output Encoding & Entry Guards: Direct access guards (if (!defined('WHMCS')) die(...)), htmlspecialchars(..., ENT_QUOTES, 'UTF-8') in Admin PHP templates, and |escape in Smarty .tpl templates prevent XSS.

8. AJAX & Export API Reference

Admin Endpoint (admin/addonmodules.php?module=haikhavan_ip_manager&ajax=1)

op Method CSRF Description
calc_cidr GET No Parse & calculate IPv4/IPv6 CIDR metadata
get_heatmap GET No Fetch ordered heatmap cells for subnet_id
create_subnet / update_subnet / delete_subnet POST Yes Subnet CRUD with overlap/containment checks
split_subnet POST Yes Carve parent subnet into child subnets
assign_ip / release_ip / update_ip_status POST Yes Manual assignment, quarantine/release, reserve/exclude
update_ptr POST Yes Update PTR and push to PowerDNS if enabled
process_quarantine POST Yes Release all expired quarantine IPs immediately
save_rule / toggle_rule / delete_rule POST Yes Allocation rule lifecycle management
save_integration / test_integration / delete_integration POST Yes Control panel & PowerDNS submodule CRUD + connectivity test
scan_rbl_ip / scan_rbl_bulk POST Yes On-demand single or bulk DNSBL scan
bulk_import POST Yes Bulk CSV/CIDR subnet or IP record import
?export_csv=subnets|ips GET Admin Session Stream RFC4180 CSV download

Client Endpoint (index.php?m=haikhavan_ip_manager&ajax=1)

op Method CSRF Description
update_ptr POST Yes Self-service Reverse DNS update (ownership + allow_client_rdns enforced)

9. Troubleshooting

  • IPs not auto-assigned on service create: Confirm an enabled rule in Allocation Rules matches the service's Product ID or Server ID, the linked subnet has available (non-RBL-listed) IPs, and haikhavan_ip_manager is active in AddonModulesHooks.
  • PowerDNS PTR update saved locally only: Verify the PowerDNS integration is Enabled, the subnet's rdns_zone exists in PowerDNS (e.g., 2.0.192.in-addr.arpa.), and Dry-Run mode is disabled for production.
  • Quarantined IPs not releasing automatically: Confirm WHMCS Daily Cron (cron.php) is running, or click Process Quarantine in the Admin header to trigger immediate release.