Buckets:

download
raw
13.8 kB
"""
๐Ÿ–ฅ๏ธ Zen-AI Native Bridge - Python Bindings.
Provides Python interface to the native DLL/Shared Library.
Integrates with MemoryGuard for memory protection.
"""
import ctypes
import logging
import os
import platform
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional
logger = logging.getLogger(__name__)
@dataclass
class ProcessInfo:
"""Process information from native scan."""
pid: int
process_name: str
memory_usage: int
thread_count: int
is_suspicious: bool
@dataclass
class NetworkConnection:
"""Network connection information."""
local_addr: str
remote_addr: str
local_port: int
remote_port: int
pid: int
state: str
@dataclass
class MemoryRegion:
"""Memory region information."""
address: int
size: int
permission: str
module_name: str
class ZenAINativeBridge:
"""
Bridge to native DLL for low-level system operations.
Features:
- Process enumeration
- Network connection monitoring
- Memory protection (via MemoryGuard)
- Debugger detection
- Syscall monitoring (future)
"""
def __init__(self):
self._lib: Optional[ctypes.CDLL] = None
self._initialized = False
# Load the appropriate library
self._load_library()
def _load_library(self):
"""Load the native library based on platform."""
system = platform.system()
if system == "Windows":
lib_name = "zen_ai_bridge.dll"
elif system == "Linux":
lib_name = "libzen_ai_bridge.so"
elif system == "Darwin":
lib_name = "libzen_ai_bridge.dylib"
else:
raise OSError(f"Unsupported platform: {system}")
# Look for library in multiple locations
search_paths = [
Path(__file__).parent / lib_name,
Path(__file__).parent / "src" / lib_name,
Path("/usr/lib") / lib_name,
Path("/usr/local/lib") / lib_name,
]
for path in search_paths:
if path.exists():
try:
self._lib = ctypes.CDLL(str(path))
logger.info(f"Loaded native library: {path}")
return
except OSError as e:
logger.warning(f"Failed to load {path}: {e}")
logger.error(f"Could not find native library: {lib_name}")
self._lib = None
def initialize(self) -> bool:
"""Initialize the native bridge."""
if self._initialized:
return True
if not self._lib:
logger.warning("Native library not available, using fallback")
return False
try:
result = self._lib.zenai_initialize()
if result == 0:
self._initialized = True
logger.info("โœ… Native bridge initialized")
return True
else:
error = self._get_last_error()
logger.error(f"Failed to initialize native bridge: {error}")
return False
except Exception as e:
logger.error(f"Exception during initialization: {e}")
return False
def cleanup(self):
"""Cleanup native resources."""
if self._lib and self._initialized:
try:
self._lib.zenai_cleanup()
self._initialized = False
logger.info("Native bridge cleaned up")
except Exception as e:
logger.error(f"Error during cleanup: {e}")
def _get_last_error(self) -> str:
"""Get last error message from native code."""
if not self._lib:
return "Library not loaded"
try:
self._lib.zenai_get_last_error.restype = ctypes.c_char_p
error = self._lib.zenai_get_last_error()
return error.decode("utf-8") if error else "Unknown error"
except Exception:
return "Failed to get error"
def scan_processes(self) -> List[ProcessInfo]:
"""
Scan running processes.
Returns:
List of process information
"""
if not self._lib or not self._initialized:
# Fallback to pure Python implementation
return self._scan_processes_python()
try:
# Define structures
class ProcessInfoStruct(ctypes.Structure):
_fields_ = [
("pid", ctypes.c_uint32),
("process_name", ctypes.c_char * 256),
("memory_usage", ctypes.c_uint64),
("thread_count", ctypes.c_uint32),
("is_suspicious", ctypes.c_int),
]
max_processes = 1024
processes = (ProcessInfoStruct * max_processes)()
self._lib.zenai_scan_processes.argtypes = [
ctypes.POINTER(ProcessInfoStruct),
ctypes.c_int,
]
self._lib.zenai_scan_processes.restype = ctypes.c_int
count = self._lib.zenai_scan_processes(processes, max_processes)
if count < 0:
logger.error(f"Process scan failed: {self._get_last_error()}")
return self._scan_processes_python()
result = []
for i in range(count):
proc = processes[i]
result.append(
ProcessInfo(
pid=proc.pid,
process_name=proc.process_name.decode("utf-8", errors="ignore"),
memory_usage=proc.memory_usage,
thread_count=proc.thread_count,
is_suspicious=bool(proc.is_suspicious),
)
)
return result
except Exception as e:
logger.error(f"Exception during process scan: {e}")
return self._scan_processes_python()
def _scan_processes_python(self) -> List[ProcessInfo]:
"""Fallback Python implementation for process scanning."""
import psutil
processes = []
for proc in psutil.process_iter(["pid", "name", "memory_info", "num_threads"]):
try:
info = proc.info
processes.append(
ProcessInfo(
pid=info["pid"],
process_name=info["name"] or "unknown",
memory_usage=(info["memory_info"].rss if info["memory_info"] else 0),
thread_count=info["num_threads"] or 0,
is_suspicious=False,
)
)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
return processes
def scan_connections(self) -> List[NetworkConnection]:
"""
Scan network connections.
Returns:
List of network connections
"""
if not self._lib or not self._initialized:
return self._scan_connections_python()
try:
class NetworkConnectionStruct(ctypes.Structure):
_fields_ = [
("local_addr", ctypes.c_char * 64),
("remote_addr", ctypes.c_char * 64),
("local_port", ctypes.c_uint16),
("remote_port", ctypes.c_uint16),
("pid", ctypes.c_uint32),
("state", ctypes.c_char * 32),
]
max_connections = 4096
connections = (NetworkConnectionStruct * max_connections)()
self._lib.zenai_scan_connections.argtypes = [
ctypes.POINTER(NetworkConnectionStruct),
ctypes.c_int,
]
self._lib.zenai_scan_connections.restype = ctypes.c_int
count = self._lib.zenai_scan_connections(connections, max_connections)
if count < 0:
logger.error(f"Connection scan failed: {self._get_last_error()}")
return self._scan_connections_python()
result = []
for i in range(count):
conn = connections[i]
result.append(
NetworkConnection(
local_addr=conn.local_addr.decode("utf-8", errors="ignore"),
remote_addr=conn.remote_addr.decode("utf-8", errors="ignore"),
local_port=conn.local_port,
remote_port=conn.remote_port,
pid=conn.pid,
state=conn.state.decode("utf-8", errors="ignore"),
)
)
return result
except Exception as e:
logger.error(f"Exception during connection scan: {e}")
return self._scan_connections_python()
def _scan_connections_python(self) -> List[NetworkConnection]:
"""Fallback Python implementation for connection scanning."""
import psutil
connections = []
for conn in psutil.net_connections():
try:
laddr = conn.laddr
raddr = conn.raddr
connections.append(
NetworkConnection(
local_addr=laddr.ip if laddr else "",
remote_addr=raddr.ip if raddr else "",
local_port=laddr.port if laddr else 0,
remote_port=raddr.port if raddr else 0,
pid=conn.pid or 0,
state=conn.status or "UNKNOWN",
)
)
except Exception:
pass
return connections
def protect_memory(self, address: int, size: int, protection: int) -> bool:
"""
Protect memory region.
Args:
address: Memory address
size: Size of region
protection: Protection flags (0=none, 1=read, 2=write, 4=exec)
Returns:
True if successful
"""
if not self._lib or not self._initialized:
logger.warning("Native library not available for memory protection")
return False
try:
self._lib.zenai_protect_memory.argtypes = [
ctypes.c_void_p,
ctypes.c_size_t,
ctypes.c_int,
]
self._lib.zenai_protect_memory.restype = ctypes.c_int
result = self._lib.zenai_protect_memory(address, size, protection)
return result == 0
except Exception as e:
logger.error(f"Exception during memory protection: {e}")
return False
def detect_debugger(self) -> bool:
"""
Detect if a debugger is attached.
Returns:
True if debugger detected
"""
if not self._lib or not self._initialized:
# Fallback: Check for common debugger indicators
return self._detect_debugger_python()
try:
self._lib.zenai_detect_debugger.restype = ctypes.c_int
result = self._lib.zenai_detect_debugger()
return result == 1
except Exception as e:
logger.error(f"Exception during debugger detection: {e}")
return self._detect_debugger_python()
def _detect_debugger_python(self) -> bool:
"""Fallback Python debugger detection."""
# Check for debugger environment variables
debugger_envs = ["DEBUG", "PYDEVD", "PYCHARM_DEBUG", "VSCODE_DEBUG"]
for env in debugger_envs:
if os.getenv(env):
return True
# Check if running in interactive mode with tracing
if hasattr(sys, "gettrace") and sys.gettrace() is not None:
return True
return False
def is_available(self) -> bool:
"""Check if native bridge is available."""
return self._lib is not None and self._initialized
# Global instance
_native_bridge: Optional[ZenAINativeBridge] = None
def get_native_bridge() -> ZenAINativeBridge:
"""Get global native bridge instance."""
global _native_bridge
if _native_bridge is None:
_native_bridge = ZenAINativeBridge()
return _native_bridge
# Convenience functions
def scan_processes() -> List[ProcessInfo]:
"""Scan running processes."""
bridge = get_native_bridge()
if not bridge._initialized:
bridge.initialize()
return bridge.scan_processes()
def scan_connections() -> List[NetworkConnection]:
"""Scan network connections."""
bridge = get_native_bridge()
if not bridge._initialized:
bridge.initialize()
return bridge.scan_connections()
def detect_debugger() -> bool:
"""Detect debugger."""
bridge = get_native_bridge()
if not bridge._initialized:
bridge.initialize()
return bridge.detect_debugger()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
bridge = get_native_bridge()
if bridge.initialize():
print("โœ… Native bridge initialized")
print("\n๐Ÿ“Š Processes:")
processes = bridge.scan_processes()
for proc in processes[:10]:
print(f" {proc.pid}: {proc.process_name} ({proc.memory_usage / 1024 / 1024:.1f} MB)")
print(f"\n๐ŸŒ Connections ({len(bridge.scan_connections())} active)")
print(f"\n๐Ÿ” Debugger detected: {bridge.detect_debugger()}")
bridge.cleanup()
else:
print("โš ๏ธ Native bridge not available, using Python fallback")
# Use Python fallback
processes = bridge.scan_processes()
print(f"\n๐Ÿ“Š Processes (Python): {len(processes)}")

Xet Storage Details

Size:
13.8 kB
ยท
Xet hash:
a91cc1dec61955115e8a2a2ddfb439eb3113cd1975d15ca3d9851824db2fa2a7

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.