# ByteHide Documentation — Full Reference > This file contains the complete ByteHide documentation concatenated for LLM consumption. > Generated on: 2026-07-13 > Source: https://docs.bytehide.com --- # General Documentation # Looks like you got lost No worries, let's get you back on track. Pick a product or platform below. {% .lead %} ## Products - [Shield](/products/shield) — Code obfuscation and protection against reverse engineering. - [Secrets](/products/secrets) — AI-powered secret detection and secure credential management. - [Monitor](/products/monitor) — Runtime application self-protection (RASP) and threat detection. - [Logs](/products/logs) — Centralized structured logging with monitoring and alerting. - [Radar](/products/radar) — SAST, SCA, and secret scanning for vulnerability detection. - [ByteHide AI](/products/ai) — AI agent that detects, correlates, and auto-fixes vulnerabilities. ## Platforms - [.NET](/platforms/dotnet) — Shield, Secrets, Monitor, Logs, and Radar for .NET Framework, Core, MAUI, Unity, and Blazor. - [JavaScript](/platforms/javascript) — Shield, Secrets, and Logs for Node.js, React, Vue, Angular, and Next.js. - [Java](/platforms/java) — Secrets and Logs for Spring Boot, Jakarta EE, and Android. - [Go](/platforms/go) — Secrets and Logs for Go web servers, CLI tools, and microservices. - [Python](/platforms/python) — Secrets and Logs for Django, Flask, FastAPI, and scripts. - [PHP](/platforms/php) — Secrets for Laravel, Symfony, WordPress, and PHP APIs. - [Android](/platforms/android) — Shield and Monitor for native Android and Kotlin apps. - [iOS](/platforms/ios) — Shield and Monitor for Swift, Objective-C, and SwiftUI apps. ## Still lost? > **Need help?** > - Check if the URL is spelled correctly > - Visit our [homepage](/) to start fresh > - Use the search bar above to find what you need --- # 500 - Server Error Ops! You got lost here... how about going to the following sections: {% .lead %} - [Easy Integration (Recommended)](platforms/dotnet/products/shield/msbuild-install) — Integrate Shield into your .NET project in the most common way for devs. - [Visual Studio Extension](platforms/dotnet/products/shield/vs-install) — Add Shield to your VS and protect automatically from it. - [CLI Integration](platforms/dotnet/products/shield/cli-install) — Protect your applications from the console of your operating system. - [Cloud](platforms/dotnet/products/shield/cloud-project) — Learn how to use Shield from our web panel without installations. --- # Shield Configurator Desktop Downloads Download the ByteHide Shield Desktop Configurator for visual configuration of your .NET solution protection settings. > **Current Version 1.3.0** > Released September 28, 2025 - Global settings management, assembly signing configuration, and protection enhancements. > **Download Information** > Downloads are hosted on Google Drive for reliability and speed. Files will download directly when you click the download button. > > **New to Shield Desktop Configurator?** After downloading, check out our comprehensive guides: > - **[Introduction & Overview](/platforms/dotnet/products/shield/desktop-config-intro)** - Learn what the configurator can do > - **[Setup Guide](/platforms/dotnet/products/shield/desktop-config-install)** - Detailed installation instructions > - **[Configuration Workflow](/platforms/dotnet/products/shield/desktop-config-workflow)** - Step-by-step usage guide > - **[Video Tutorials](/platforms/dotnet/products/shield/tutorials)** - Visual learning resources ## Windows Downloads ## macOS Downloads ## System Requirements ### Windows - **OS**: Windows 10 version 1903 or later - **Memory**: 2 GB RAM minimum, 4 GB recommended - **Storage**: 200 MB available space - **Runtime**: .NET 6.0 Desktop Runtime ### macOS - **OS**: macOS 10.15 Catalina or later - **Memory**: 2 GB RAM minimum, 4 GB recommended - **Storage**: 200 MB available space - **Runtime**: .NET 6.0 Runtime > **macOS Installation - Unsigned Application** > These macOS applications are not signed with an Apple Developer Certificate. Follow the specific installation steps below to install safely. ## Installation ### Windows 1. Download the EXE installer 2. Run as administrator (right-click → "Run as administrator") 3. Follow the installation wizard 4. Launch "Shield Configurator" from Start Menu or Desktop ### macOS - Special Installation Steps Required > **Why these steps are needed** > The macOS applications are not signed with an Apple Developer Certificate, so macOS will block them by default for security. These steps allow you to install them safely. #### Step 1: Download and Mount 1. Download the appropriate DMG file for your Mac architecture: - **Intel Macs**: Choose "macOS Intel (x64)" - **Apple Silicon Macs (M1/M2/M3)**: Choose "macOS Apple Silicon (ARM64)" 2. Double-click the downloaded DMG file to mount it #### Step 2: Attempt Installation 1. Drag "Shield Configurator" to your Applications folder 2. Try to launch the application from Applications folder 3. macOS will show a security warning: **"Shield Configurator cannot be opened because it is from an unidentified developer"** #### Step 3: Allow the Application 1. Go to **System Preferences** (or **System Settings** on macOS 13+) 2. Click **Security & Privacy** (or **Privacy & Security**) 3. Click the **General** tab 4. You'll see a message: **"Shield Configurator was blocked from use because it is not from an identified developer"** 5. Click **Open Anyway** 6. Confirm by clicking **Open** in the dialog #### Step 4: Launch Successfully 1. The application will now open 2. Future launches will work normally without these steps 3. You can find "Shield Configurator" in your Applications folder #### Alternative Method: Right-Click to Open If the Security & Privacy method doesn't work: 1. In Applications folder, **right-click** on "Shield Configurator" 2. Select **Open** from the context menu 3. Click **Open** in the security dialog that appears ## What's Next? After downloading and installing the Shield Desktop Configurator, follow these guides to get started: ### Getting Started 1. **[Introduction & Overview](/platforms/dotnet/products/shield/desktop-config-intro)** - Understand the capabilities and features 2. **[Installation & Setup](/platforms/dotnet/products/shield/desktop-config-install)** - Complete installation guide with troubleshooting 3. **[Configuration Workflow](/platforms/dotnet/products/shield/desktop-config-workflow)** - Learn the step-by-step process ### Advanced Usage - **[Protection Settings](/platforms/dotnet/products/shield/desktop-config-protection)** - Configure advanced protection options - **[Advanced Features](/platforms/dotnet/products/shield/desktop-config-advanced)** - Expert-level configuration - **[Video Tutorials](/platforms/dotnet/products/shield/tutorials)** - Watch comprehensive video guides ### Related Documentation - **[MSBuild Integration](/platforms/dotnet/products/shield/msbuild-install)** - Alternative integration method - **[Configuration Files](/platforms/dotnet/products/shield/configuration-files)** - Understanding Shield configuration - **[CI/CD Integration](/platforms/dotnet/products/shield/msbuild-cicd-integration)** - Automated protection workflows ## Release Notes ### Version 1.3.0 - September 28, 2025 #### 🚀 New Features **Global Settings Management** - **NEW:** Added comprehensive Global Settings modal accessible from the footer - **NEW:** Environment variable support for global settings (`BYTEHIDE_SHIELD_ENABLED`) - **NEW:** Visual indicator when Shield protection is globally disabled - **NEW:** Toggle between manual configuration and environment variable control **Assembly Signing Configuration** - **NEW:** Complete assembly signing options support - **NEW:** Strong name signing configuration (`.snk` files and passwords) - **NEW:** Enhanced signing configuration with custom signatures - **NEW:** Delay signature option for postponed signing workflows - **NEW:** Individual property-level configuration (not nested objects) **Protection Enhancements** - **NEW:** Added Virtualization protection option - **IMPROVED:** Protection presets now include virtualization in maximum configuration #### 🛠️ Improvements **User Interface** - **IMPROVED:** Enhanced sidebar scrolling with proper container management - **IMPROVED:** Fixed project list cutoff issues with responsive design - **IMPROVED:** Global Settings modal with larger size for better usability - **IMPROVED:** Consistent toggle design patterns across all settings **Configuration Management** - **IMPROVED:** Individual assembly signing properties saved at project level - **IMPROVED:** Enhanced copy settings functionality includes all signing options - **IMPROVED:** Better error handling and debugging for configuration saving/loading **API Integration** - **FIXED:** Corrected NuGet API URL for Bytehide.Shield.Integration package versions - **IMPROVED:** More reliable version fetching with proper endpoint #### 🐛 Bug Fixes **Project Management** - **FIXED:** Project list in sidebar no longer cuts off at the bottom - **FIXED:** Proper padding added to prevent footer overlap - **FIXED:** Assembly signing options now correctly save and load from JSON **Configuration Persistence** - **FIXED:** Individual signing properties properly persist to `bytehide.shield.global.json` - **FIXED:** Global options correctly load from existing configuration files - **FIXED:** Environment variable initialization issues resolved **UI/UX Fixes** - **FIXED:** Modal accessibility and click-outside-to-close functionality - **FIXED:** Toggle state management for environment variable switches - **FIXED:** Proper visual feedback for save operations #### 📋 Technical Changes **Data Structure Updates** - Assembly signing properties moved from nested `signing` object to individual project properties - Global options now include `useEnvEnabled` flag for environment variable control - Enhanced project initialization with complete default values **Environment Variable Support** - `BYTEHIDE_SHIELD_ENABLED`: Controls global Shield protection state - `BYTEHIDE_SHIELD_TOKEN`: Project token authentication (existing) - Runtime evaluation of environment variables in main process **Configuration Schema** ```json { "globalOptions": { "enabled": true, "throwOnError": true, "copyMagicKey": false }, "projects": [{ "SignFilePath": "", "SignPublicFilePath": "", "SignSignatureFilePath": "", "SignSignaturePublicFilePath": "", "SignFilePassword": "", "SignSignaturePassword": "", "DelaySignature": false }] } ``` #### 🔧 Developer Notes **Breaking Changes** - Assembly signing configuration structure changed from nested to flat properties - Global options initialization moved to application startup **Migration** - Existing configurations will automatically migrate to new structure - No manual intervention required for existing projects --- ### Version 1.0.0 - September 21, 2025 #### 🎉 Initial Release Features **Core Functionality** - Complete Visual Studio solution integration - Protection configuration management - Real-time configuration preview - Multiple protection presets (Basic, Balanced, Maximum) **Project Management** - Multi-project solution support - Individual project configuration - Settings copy between projects - JSON configuration export/import **Protection Options** - Renaming obfuscation - Control flow obfuscation - String encryption - Anti-debugging protection - Invalid metadata injection - Call hiding **User Interface** - Modern, intuitive interface - Dark/light theme support - Responsive design - Real-time validation *This release establishes the foundation for visual .NET protection configuration with comprehensive solution management capabilities.* --- # Monitor - Guía de Integración de Monitor ## Android (Java/Kotlin) & iOS (Swift/Objective-C) --- ## Tabla de Contenidos - [Introducción](#introduccion) - [Integración Android](#integracion-android-javakotlin) - [Instalación](#instalacion) - [Configuración](#configuracion) - [Opción A: Configuración desde la Nube (Zero-Config)](#opcion-a-configuracion-desde-la-nube-zero-config---recomendada) - [Opción B: Configuración con Archivo JSON](#opcion-b-configuracion-con-archivo-json---para-control-local) - [Opción C: Configuración Programática](#opcion-c-configuracion-programatica---para-maximo-control) - [Tipos de Acciones Disponibles](#tipos-de-acciones-disponibles) - [Configuración Híbrida](#configuracion-hibrida-recomendada-para-produccion) - [Integración iOS](#integracion-ios-swiftobjective-c) - [Instalación](#instalacion-1) - [Configuración](#configuracion-1) - [Configuración de Protecciones](#configuracion-de-protecciones) - [Opción A: Configuración desde la Nube (Zero-Config)](#opcion-a-configuracion-desde-la-nube-zero-config---recomendada-1) - [Opción B: Configuración con Archivo JSON](#opcion-b-configuracion-con-archivo-json---para-control-local-1) - [Opción C: Configuración Programática](#opcion-c-configuracion-programatica---para-maximo-control-1) - [Tipos de Acciones Disponibles](#tipos-de-acciones-disponibles-1) - [Configuración Híbrida](#configuracion-hibrida-recomendada-para-produccion-1) - [Auto-inicialización](#auto-inicializacion) - [Integración CI/CD](#integracion-cicd) - [Protecciones Disponibles](#protecciones-disponibles) - [1. Debugger Detection](#1-debugger-detection) - [2. Jailbreak/Root Detection](#2-jailbreakroot-detection) - [3. Clock Tampering Detection](#3-clock-tampering-detection) - [4. Virtual Machine Detection](#4-virtual-machine-detection) - [5. Emulator Detection](#5-emulator-detection) - [6. Memory Dump Detection](#6-memory-dump-detection) - [7. Tampering Detection](#7-tampering-detection) - [8. Process Injection Detection](#8-process-injection-detection) - [9. Network Tampering Detection](#9-network-tampering-detection) - [10. License Binding Detection](#10-license-binding-detection) - [11. Container Detection](#11-container-detection) - [12. Remote Desktop Detection](#12-remote-desktop-detection) - [13. Cloud Metadata Detection](#13-cloud-metadata-detection) - [Protecciones Web Adicionales](#protecciones-web-adicionales) --- ## Introducción **Monitor** es una solución RASP (Runtime Application Self-Protection) que protege aplicaciones en tiempo de ejecución contra amenazas, tampering y entornos maliciosos. Esta guía de integración está dirigida específicamente a **aplicaciones móviles Android e iOS**. Monitor detecta amenazas en dispositivos y entornos como debuggers, máquinas virtuales, emuladores, jailbreak/root, manipulación del reloj y volcados de memoria. **Nota:** ByteHide Monitor también dispone de una versión web que actúa como WAF (Web Application Firewall) integrado en la aplicación para interceptar ataques web como SQL Injection, XSS, NoSQL Injection, entre otros. Esta guía no cubre la versión web, está enfocada exclusivamente en protecciones para aplicaciones móviles. Esta guía está dirigida a **desarrolladores y organizaciones** que desean integrar la protección de Monitor en sus aplicaciones móviles. Monitor es un **producto comercial** disponible a través de ByteHide. --- ## Integración Android (Java/Kotlin) ### Instalación #### Paso 1: Añadir el Repositorio Maven de ByteHide Añade el repositorio de Monitor a tu `settings.gradle.kts`: ```kotlin pluginManagement { repositories { maven { url = uri("https://maven.bytehide.com/releases") } google() mavenCentral() } } dependencyResolutionManagement { repositories { maven { url = uri("https://maven.bytehide.com/releases") } google() mavenCentral() } } ``` #### Paso 2: Añadir la Dependencia de Monitor Añade Monitor a tu `build.gradle.kts` del módulo app: ```kotlin dependencies { implementation("com.bytehide:monitor-integration:2.0.0") } ``` --- ### Configuración Monitor ofrece **3 opciones de configuración** según tus necesidades: #### Opción A: Configuración desde la Nube (Zero-Config) - Recomendada La forma más simple. Solo añade el paquete y Monitor obtiene la configuración automáticamente desde tu dashboard de ByteHide. **Ventajas:** - Sin archivos de configuración - Sin código adicional - Actualización de protecciones en tiempo real desde el dashboard - Cambios instantáneos sin necesidad de rebuild **¿Qué sucede?** 1. Durante el build, el plugin Gradle embebe tu token en el APK 2. En runtime, Monitor se conecta a la API de ByteHide 3. Descarga la configuración activa desde tu dashboard 4. Aplica las protecciones configuradas remotamente 5. Sincroniza cambios periódicamente (actualizaciones en caliente) **Setup:** Configura tu token como variable de entorno: ```bash # Windows (PowerShell) $env:BYTEHIDE_TOKEN = "tu-token-aqui" # Windows (CMD) set BYTEHIDE_TOKEN=tu-token-aqui # Linux/macOS export BYTEHIDE_TOKEN="tu-token-aqui" ``` Build tu proyecto - ¡y listo! Monitor se inicializará automáticamente con la configuración de tu dashboard. #### Opción B: Configuración con Archivo JSON - Para Control Local Define las protecciones localmente en un archivo JSON. Ideal si necesitas configuración offline o control total sobre las protecciones. **Ventajas:** - Configuración versionada en tu repositorio - Funciona completamente offline - Control total sobre protecciones y acciones - Fácil de auditar y revisar Crea `monitor-config.json` en `src/main/assets/`: ```json { "projectToken": "tu-token-aqui", "logging": { "level": "info", "console": true, "file": { "enabled": true, "path": "logs/monitor.log" } }, "protections": [ { "type": "DEBUGGER_DETECTION", "enabled": true, "action": "CLOSE", }, { "type": "JAILBREAK_DETECTION", "enabled": true, "action": "CLOSE", }, { "type": "EMULATOR_DETECTION", "enabled": true, "action": "LOG", }, { "type": "CLOCK_TAMPERING", "enabled": true, "action": "LOG", }, { "type": "MEMORY_DUMP_DETECTION", "enabled": true, "action": "CLOSE", }, { "type": "VIRTUAL_MACHINE_DETECTION", "enabled": true, "action": "CLOSE", } ] } ``` Monitor cargará automáticamente este archivo sin código adicional. #### Opción C: Configuración Programática - Para Máximo Control Configura Monitor directamente en código. Ideal para lógica de protección dinámica, acciones personalizadas y debugging avanzado. **Ventajas:** - Control total mediante código - Acciones personalizadas (custom handlers) - Configuración dinámica según condiciones - Integración con tu lógica de negocio ```kotlin import android.app.Application import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType import android.util.Log class MyApplication : Application() { override fun onCreate() { super.onCreate() // Configurar Monitor programáticamente Monitor.configure { config -> // Token (opcional si ya está embebido) config.useToken("bh_TuTokenAqui") // Registrar acción personalizada config.registerCustomAction("notificar") { threat -> Log.w("ByteHideMonitor", "🚨 ALERTA: ${threat.description}") // Enviar notificación al usuario // Registrar en analytics // Enviar a sistema de alertas } // Configurar logging config.configureLogging { logging -> logging.enableConsole() logging.enableFileLogging("monitor.log") logging.setMinimumLevel(LogLevel.INFO) } // Habilitar todas las protecciones con acción personalizada config.enableAllProtections(ActionType.CUSTOM, 60000) // O configurar protecciones individuales config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.CLOSE, 60000 ) config.addProtection( ProtectionModuleType.JAILBREAK_DETECTION, "notificar", // Usar acción personalizada 60000 ) } } override fun onTerminate() { super.onTerminate() Monitor.shutdown() } } ``` No olvides registrar tu Application en el `AndroidManifest.xml`: ```xml ``` --- ### Tipos de Acciones Disponibles Monitor ofrece diferentes acciones que se ejecutan cuando se detecta una amenaza: | Tipo | Descripción | Uso Recomendado | |------|-------------|-----------------| | **NONE** | Solo detecta, no toma acción | Testing, análisis inicial | | **LOG** | Registra el incidente en logs | Producción con monitoreo | | **CLOSE** | Cierra la aplicación inmediatamente | Máxima seguridad | | **ERASE** | Borra datos sensibles y cierra | Datos críticos (finanzas, salud) | | **CUSTOM** | Ejecuta tu handler personalizado | Lógica de negocio específica | **Ejemplo de Acción Personalizada:** ```kotlin config.registerCustomAction("miAccion") { threat -> // 1. Registrar el incidente analytics.trackSecurityThreat(threat.type, threat.description) // 2. Notificar al usuario showSecurityWarning(threat.description) // 3. Enviar alerta al backend securityApi.reportThreat(threat) // 4. Tomar medida según severidad when (threat.confidence) { in 0.8..1.0 -> { // Alta confianza: cerrar app exitProcess(1) } in 0.5..0.8 -> { // Media confianza: limitar funcionalidad disableSensitiveFeatures() } else -> { // Baja confianza: solo log Log.i("Security", "Posible amenaza: ${threat.description}") } } } ``` --- ### Configuración Híbrida (Recomendada para Producción) Puedes combinar las opciones para máxima flexibilidad: ```kotlin Monitor.configure { config -> // Cargar configuración base desde Cloud/JSON // (Monitor ya cargó automáticamente desde cloud o monitor-config.json) // Sobrescribir solo lo que necesitas config.registerCustomAction("alertaCritica") { threat -> // Tu lógica personalizada para amenazas críticas sendPushNotification("Alerta de Seguridad", threat.description) exitProcess(1) } // Añadir protección adicional con acción custom config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, "alertaCritica", 60000 ) } ``` **Flujo de carga de configuración:** 1. Monitor intenta cargar desde `monitor-config.json` embebido 2. Si no existe, obtiene configuración desde la nube (dashboard) 3. Aplica configuración programática (si usas `Monitor.configure`) 4. La configuración programática sobrescribe la automática --- ## Integración iOS (Swift/Objective-C) ### Instalación Monitor para iOS soporta **CocoaPods** y **Swift Package Manager**. #### Opción 1: CocoaPods (Recomendada - Configuración Cero) Añade Monitor a tu `Podfile`: ```ruby platform :ios, '12.0' target 'TuApp' do use_frameworks! pod 'ByteHideMonitor', '~> 1.0.0' end ``` Instala: ```bash pod install ``` **¡Listo!** La validación en build-time se ejecuta automáticamente. #### Opción 2: Swift Package Manager **Paso 1:** Añadir el Paquete 1. Xcode → File → Add Package Dependencies... 2. URL: `https://github.com/bytehide/bytehide-monitor` 3. Versión: `1.0.0+` 4. Añadir a tu target **Paso 2:** Ejecutar Script de Setup (Una sola vez) ```bash # Instalar xcodeproj gem (si no está instalado) gem install xcodeproj # Ejecutar setup desde el directorio de tu proyecto cd TuProyecto ruby Packages/ByteHideMonitor/setup-spm.rb ``` **¡Listo!** Después de este setup único, los builds funcionan automáticamente como con CocoaPods. --- ### Configuración #### Paso 1: Obtener tu Project Token Obtén tu **ByteHide Project Token** desde [cloud.bytehide.com](https://cloud.bytehide.com) #### Paso 2: Configurar el Token Tienes **3 opciones** para configurar tu token (elige una): ##### Opción A: Variable de Entorno (Recomendada) Configura `BYTEHIDE_TOKEN` en tu esquema de Xcode: 1. Edit Scheme → Run → Arguments → Environment Variables 2. Añade: `BYTEHIDE_TOKEN` = `tu-project-token` ##### Opción B: Info.plist Añade a tu `Info.plist`: ```xml ByteHideMonitor APIToken ${BYTEHIDE_TOKEN} ``` Luego configura la variable de entorno `BYTEHIDE_TOKEN` (igual que Opción A). ##### Opción C: Archivo de Configuración JSON Crea `monitor-config.json` en la raíz de tu proyecto: ```json { "apiToken": "${BYTEHIDE_TOKEN}", "logLevel": "info", "protections": [ { "type": "DebuggerDetection", "action": "close", }, { "type": "JailbreakDetection", "action": "close", } ] } ``` Configura la variable de entorno `BYTEHIDE_TOKEN` (igual que Opción A). --- ### Configuración de Protecciones Monitor ofrece **3 opciones de configuración** según tus necesidades: #### Opción A: Configuración desde la Nube (Zero-Config) - Recomendada La forma más simple. Monitor obtiene la configuración automáticamente desde tu dashboard de ByteHide. **Ventajas:** - Sin archivos de configuración - Sin código adicional - Actualización de protecciones en tiempo real desde el dashboard - Cambios instantáneos sin necesidad de rebuild **Setup:** Simplemente configura tu token (como se explicó arriba) y compila tu app. Durante el build, se valida el token y se embebe la configuración. En runtime, Monitor se auto-inicializa usando `+load()` (antes de `main()`) y aplica las protecciones configuradas en tu dashboard. ```bash # Compilar en Xcode: Product → Build (⌘B) # O vía línea de comandos: xcodebuild -workspace TuApp.xcworkspace -scheme TuApp -configuration Release ``` **¡No se requiere código!** Todo es automático. #### Opción B: Configuración con Archivo JSON - Para Control Local Define las protecciones localmente en un archivo JSON. Ideal si necesitas configuración offline o control total. **Ventajas:** - Configuración versionada en tu repositorio - Funciona completamente offline - Control total sobre protecciones y acciones - Fácil de auditar y revisar Crea `monitor-config.json` en la raíz de tu proyecto: ```json { "projectToken": "bh_TuToken", "logging": { "level": "info", "console": true }, "protections": [ { "type": "DebuggerDetection", "enabled": true, "action": "close", }, { "type": "JailbreakDetection", "enabled": true, "action": "close", }, { "type": "EmulatorDetection", "enabled": true, "action": "log", }, { "type": "ClockTampering", "enabled": true, "action": "log", }, { "type": "MemoryDumpDetection", "enabled": true, "action": "close", }, { "type": "VirtualMachineDetection", "enabled": true, "action": "close", } ] } ``` Monitor cargará automáticamente este archivo sin código adicional. #### Opción C: Configuración Programática - Para Máximo Control Configura Monitor directamente en código Swift/Objective-C. Ideal para lógica de protección dinámica y acciones personalizadas. **Ventajas:** - Control total mediante código - Acciones personalizadas (custom handlers) - Configuración dinámica según condiciones - Integración con tu lógica de negocio **Swift:** ```swift import ByteHideMonitor @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Configurar Monitor programáticamente Monitor.configure { config in // Token (opcional si ya está embebido) config.useToken("bh_TuToken") // Registrar acción personalizada config.registerCustomAction("notificar") { threat in print("🚨 ALERTA: \(threat.description)") // Enviar notificación al usuario // Registrar en analytics // Enviar a sistema de alertas } // Configurar logging config.configureLogging { logging in logging.enableConsole() logging.setMinimumLevel(.info) } // Habilitar todas las protecciones con acción personalizada config.enableAllProtections(.log) // O configurar protecciones individuales config.addProtection(.debuggerDetection, action: .close) config.addProtection(.jailbreakDetection, customAction: "notificar") } return true } func applicationWillTerminate(_ application: UIApplication) { Monitor.shutdown() } } ``` **Objective-C:** ```objc #import @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Configurar Monitor programáticamente [Monitor configure:^(MonitorConfiguration *config) { // Token [config useToken:@"bh_TuToken"]; // Registrar acción personalizada [config registerCustomAction:@"notificar" handler:^(Threat *threat) { NSLog(@"🚨 ALERTA: %@", threat.description); }]; // Habilitar todas las protecciones [config enableAllProtections:ActionTypeCustom]; // O protecciones individuales [config addProtection:ProtectionTypeDebuggerDetection action:ActionTypeClose intervalMs:60000]; }]; return YES; } - (void)applicationWillTerminate:(UIApplication *)application { [Monitor shutdown]; } @end ``` --- ### Tipos de Acciones Disponibles Monitor ofrece diferentes acciones que se ejecutan cuando se detecta una amenaza: | Tipo | Descripción | Uso Recomendado | |------|-------------|-----------------| | **none** | Solo detecta, no toma acción | Testing, análisis inicial | | **log** | Registra el incidente en logs | Producción con monitoreo | | **close** | Cierra la aplicación inmediatamente | Máxima seguridad | | **erase** | Borra datos sensibles y cierra | Datos críticos (finanzas, salud) | | **custom** | Ejecuta tu handler personalizado | Lógica de negocio específica | --- ### Configuración Híbrida (Recomendada para Producción) Puedes combinar las opciones para máxima flexibilidad: ```swift Monitor.configure { config in // Cargar configuración base desde Cloud/JSON // (Monitor ya cargó automáticamente desde cloud o monitor-config.json) // Sobrescribir solo lo que necesitas config.registerCustomAction("alertaCritica") { threat in // Tu lógica personalizada para amenazas críticas sendPushNotification("Alerta de Seguridad", threat.description) exit(1) } // Añadir protección adicional con acción custom config.addProtection(.memoryDumpDetection, customAction: "alertaCritica" ) } ``` **Flujo de carga de configuración:** 1. Monitor intenta cargar desde `monitor-config.json` embebido 2. Si no existe, obtiene configuración desde la nube (dashboard) 3. Aplica configuración programática (si usas `Monitor.configure`) 4. La configuración programática sobrescribe la automática --- ### Auto-inicialización Monitor para iOS **se auto-inicializa automáticamente** usando el método `+load()` de Objective-C, que se ejecuta antes de `main()`. **¿Cómo funciona?** - **Durante el build**: Se valida el token y se embebe la configuración necesaria en el bundle de la app - **Durante la ejecución**: Monitor se inicializa automáticamente antes de que tu código se ejecute, validando la firma y activando las protecciones configuradas **¡No se requiere código adicional!** A menos que uses la Opción C (configuración programática) --- ## Integración CI/CD ### Android - GitHub Actions ```yaml name: Build Android App on: push: branches: [main] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up JDK 11 uses: actions/setup-java@v3 with: java-version: '11' distribution: 'temurin' - name: Build con Monitor env: BYTEHIDE_TOKEN: ${{ secrets.BYTEHIDE_TOKEN }} run: | ./gradlew assembleRelease - name: Subir APK uses: actions/upload-artifact@v3 with: name: app-release path: app/build/outputs/apk/release/app-release.apk ``` ### iOS - GitHub Actions ```yaml name: Build iOS App on: push: branches: [main] jobs: build: runs-on: macos-latest steps: - uses: actions/checkout@v3 - name: Instalar CocoaPods run: | gem install cocoapods pod install - name: Compilar IPA env: BYTEHIDE_TOKEN: ${{ secrets.BYTEHIDE_TOKEN }} run: | xcodebuild archive \ -workspace TuApp.xcworkspace \ -scheme TuApp \ -configuration Release \ -archivePath TuApp.xcarchive xcodebuild -exportArchive \ -archivePath TuApp.xcarchive \ -exportPath . \ -exportOptionsPlist ExportOptions.plist - name: Subir IPA uses: actions/upload-artifact@v3 with: name: app-protected path: TuApp.ipa ``` ### GitLab CI **Android:** ```yaml build_android: stage: build image: gradle:7.6-jdk11 script: - export BYTEHIDE_TOKEN=$BYTEHIDE_TOKEN - ./gradlew assembleRelease artifacts: paths: - app/build/outputs/apk/release/app-release.apk ``` **iOS:** ```yaml build_ios: stage: build image: macos-12-xcode-14 script: - export BYTEHIDE_TOKEN=$BYTEHIDE_TOKEN - pod install - xcodebuild archive ... artifacts: paths: - TuApp.ipa ``` --- ## Protecciones Disponibles Monitor ofrece **13 protecciones de seguridad en tiempo de ejecución** para aplicaciones móviles y de escritorio: --- ### 1. Debugger Detection Detecta y bloquea debuggers adjuntos a tu aplicación en tiempo de ejecución. **Qué protege:** Previene el análisis dinámico con herramientas como LLDB, GDB, Android Studio Debugger, Frida, y otros debuggers que permiten a atacantes analizar el comportamiento de tu aplicación. **Técnicas de detección:** - Detección de procesos debugger adjuntos - Verificación de flags de debugging del sistema - Detección de breakpoints y hooks - Detección de herramientas de instrumentación --- ### 2. Jailbreak/Root Detection Detecta dispositivos con jailbreak (iOS) o root (Android) que tienen privilegios elevados. **Qué protege:** Evita que tu app se ejecute en dispositivos comprometidos donde existen herramientas avanzadas de hacking como Magisk, Xposed Framework, Cydia, Sileo, checkra1n, unc0ver. **Verificaciones incluidas:** - Detección de archivos y rutas de jailbreak/root - Verificación de permisos del sistema de archivos - Detección de modificaciones del sistema - Identificación de hooks y frameworks de modificación - Detección de binarios sospechosos (su, busybox) --- ### 3. Clock Tampering Detection Detecta manipulación del reloj del sistema. **Qué protege:** Previene bypass de funcionalidades basadas en tiempo como trials, licencias temporales, ofertas limitadas, y validaciones de certificados. **Técnicas de detección:** - Comparación de tiempo local vs tiempo de red - Detección de saltos temporales anormales - Verificación de sincronización NTP - Detección de cambios en zona horaria sospechosos --- ### 4. Virtual Machine Detection Identifica si tu aplicación se está ejecutando en un entorno de máquina virtual. **Qué protege:** Detecta entornos virtualizados como VMware, VirtualBox, Hyper-V, Parallels, QEMU, KVM donde los atacantes suelen realizar análisis de malware y reversing. **Verificaciones incluidas:** - Detección de hardware virtualizado (CPU, chipset) - Identificación de drivers de VM - Verificación de características específicas de hypervisors - Detección de MAC addresses de VM - Análisis de BIOS/UEFI --- ### 5. Emulator Detection Detecta si tu aplicación se ejecuta en un emulador en lugar de un dispositivo físico. **Qué protege:** Previene la ejecución en emuladores como Android Emulator, Genymotion, iOS Simulator, BlueStacks, donde los atacantes pueden tener control total del entorno. **Verificaciones incluidas:** - Detección de características de emulador (sensores, hardware) - Identificación de archivos y propiedades de sistema de emuladores - Análisis de comportamiento de dispositivo - Detección de build properties de emulador - Verificación de hardware falso --- ### 6. Memory Dump Detection Detecta intentos de volcar la memoria de la aplicación. **Qué protege:** Previene la extracción de datos sensibles de la memoria como tokens, claves de API, credenciales, secretos, y datos de sesión almacenados temporalmente. **Detecciones incluidas:** - Herramientas de memory dumping (GameGuardian, Cheat Engine) - Procesos sospechosos accediendo a memoria - Intentos de lectura no autorizada - Detección de memory scanning tools --- ### 7. Tampering Detection Detecta modificaciones no autorizadas en los archivos de la aplicación. **Qué protege:** Identifica si el código, recursos, o configuración de tu aplicación han sido modificados, lo que podría indicar repacking, patching, o distribución no autorizada. **Verificaciones incluidas:** - Validación de firma digital de la aplicación - Verificación de checksums de archivos críticos - Detección de modificaciones en el APK/IPA - Detección de instaladores no oficiales - Validación de integridad del código --- ### 8. Process Injection Detection Detecta intentos de inyección de código en el proceso de tu aplicación. **Qué protege:** Previene ataques donde código malicioso es inyectado en tu proceso para robar datos, modificar comportamiento, o bypassear protecciones. **Técnicas de detección:** - Detección de DLL/library injection - Identificación de code injection - Detección de hooks maliciosos - Monitoreo de módulos cargados - Detección de ptrace attachments --- ### 9. Network Tampering Detection Detecta manipulación de tráfico de red. **Qué protege:** Identifica ataques Man-in-the-Middle (MITM), uso de proxies maliciosos, y manipulación de peticiones/respuestas HTTP/HTTPS. **Verificaciones incluidas:** - Detección de certificados SSL/TLS no confiables - Identificación de proxies (Charles, Burp Suite, Fiddler) - Detección de VPNs sospechosas - Validación de certificate pinning - Detección de network interception tools --- ### 10. License Binding Detection Valida que la licencia esté correctamente vinculada al dispositivo. **Qué protege:** Previene que una licencia legítima sea usada en dispositivos no autorizados, evitando piratería y uso compartido de cuentas. **Validaciones incluidas:** - Binding a hardware único (device fingerprint) - Validación de machine ID - Verificación de licencia en servidor - Detección de clonación de dispositivos - Límites de activaciones por licencia --- ### 11. Container Detection Detecta si la aplicación se ejecuta dentro de un contenedor. **Qué protege:** Identifica entornos containerizados como Docker, LXC, Kubernetes donde los atacantes pueden tener control avanzado del entorno de ejecución. **Técnicas de detección:** - Detección de control groups (cgroups) - Identificación de namespaces de contenedor - Verificación de filesystem containers - Detección de Docker/containerd - Análisis de procesos init del contenedor --- ### 12. Remote Desktop Detection Detecta conexiones de escritorio remoto activas. **Qué protege:** Identifica si alguien está controlando el dispositivo remotamente, lo que podría indicar acceso no autorizado o análisis remoto. **Detecciones incluidas:** - RDP (Remote Desktop Protocol) - VNC (Virtual Network Computing) - TeamViewer y AnyDesk - Apple Remote Desktop - Chrome Remote Desktop - Otras soluciones de acceso remoto --- ### 13. Cloud Metadata Detection Detecta si la aplicación se ejecuta en infraestructura cloud. **Qué protege:** Identifica ejecución en servicios cloud (AWS, Azure, GCP) donde los atacantes pueden usar recursos temporales para análisis sin dejar rastro. **Verificaciones incluidas:** - Detección de metadata endpoints de AWS - Identificación de Azure Instance Metadata Service - Detección de Google Cloud metadata - Verificación de IPs cloud conocidas - Detección de hostnames cloud característicos --- ### Protecciones Web Adicionales **Nota:** ByteHide Monitor también incluye **9 protecciones adicionales para aplicaciones web** que actúan como WAF (Web Application Firewall) integrado: - SQL Injection - Cross-Site Scripting (XSS) - Path Traversal - Command Injection - Server-Side Request Forgery (SSRF) - LDAP Injection - XML External Entity (XXE) - NoSQL Injection - LLM Prompt Injection Estas protecciones web no están cubiertas en esta guía móvil. Consulta la documentación de Monitor Web para más detalles. --- **Monitor** es un producto comercial de **ByteHide**. Visita https://bytehide.com para más información. --- # Shield - Guía de Integración de Shield ## Android (Kotlin/Java) & iOS (Swift/Objective-C) --- ## Tabla de Contenidos - [Introducción](#introduccion) - [Integración Android](#integracion-android-kotlinjava) - [Instalación](#instalacion) - [Uso](#uso) - [Configuración](#configuracion) - [Exclusión de Clases](#exclusion-de-clases-y-paquetes) - [Variantes de Build](#configuracion-por-variante-de-build) - [Integración iOS](#integracion-ios-swiftobjective-c) - [Instalación](#instalacion-1) - [Opciones de Uso](#opciones-de-uso) - [Configuración](#configuracion-1) - [Exclusión de Clases](#excluir-clases-de-la-proteccion) - [Opciones de Build](#opciones-de-integracion-con-build) - [Integración CI/CD](#integracion-cicd) - [Protecciones Disponibles](#protecciones-disponibles) - [1. Encriptación de Strings](#1-encriptacion-de-strings) - [2. Ofuscación de Nombres](#2-ofuscacion-de-nombres) - [3. Ofuscación de Flujo de Control](#3-ofuscacion-de-flujo-de-control) - [4. Mutación de Constantes](#4-mutacion-de-constantes) - [5. Anti-Debug](#5-anti-debug) - [6. Anti-Jailbreak/Root](#6-anti-jailbreakroot) - [7. Eliminación de Información de Debug](#7-eliminacion-de-informacion-de-debug) - [8. Swift Symbol Stripping](#8-swift-symbol-stripping) - [9. Reference Proxy](#9-reference-proxy) - [10. Inyección de Código Inválido](#10-inyeccion-de-codigo-invalido) --- ## Introducción **Shield** es una suite integral de protección para aplicaciones móviles que proporciona ofuscación de código, anti-debugging, anti-tampering y protecciones de seguridad para aplicaciones Android e iOS. Esta guía está dirigida a **desarrolladores y organizaciones** que desean integrar la protección de Shield en sus aplicaciones móviles. Shield es un **producto comercial** disponible a través de ByteHide. --- ## Integración Android (Kotlin/Java) ### Instalación #### Paso 1: Añadir el Repositorio Maven de ByteHide Añade el repositorio de Shield a tu `settings.gradle.kts`: ```kotlin pluginManagement { repositories { maven { url = uri("https://maven.bytehide.com/releases") } google() mavenCentral() } } dependencyResolutionManagement { repositories { maven { url = uri("https://maven.bytehide.com/releases") } google() mavenCentral() } } ``` #### Paso 2: Aplicar el Plugin de Shield Añade el plugin de Shield al `build.gradle.kts` de tu módulo app: ```kotlin plugins { id("com.android.application") id("org.jetbrains.kotlin.android") id("com.bytehide.shield") version "1.0.0" } ``` --- ### Uso Shield para Android puede configurarse de dos formas: #### Opción 1: Configuración Directa en Gradle (DSL) Configura Shield directamente en tu archivo `build.gradle.kts`: ```kotlin shield { enabled = true protections { stringEncryption = true constantMutation = true debugRemoval = true nameObfuscation = true controlFlowObfuscation = false antiDebug = true antiTamper = true } excludedPackages = listOf( "android", "androidx", "kotlin", "kotlinx", "com.google" ) excludedClasses = listOf( "com.myapp.models.User", "com.myapp.api.ApiResponse" ) verbose = true } ``` #### Opción 2: Archivo de Configuración JSON Crea un archivo `shield-config.json` en el directorio de tu módulo app: ```json { "enabled": true, "protections": { "stringEncryption": true, "constantMutation": true, "debugRemoval": true, "nameObfuscation": true, "controlFlowObfuscation": false, "antiDebug": true, "antiTamper": true }, "excludedPackages": [ "android", "androidx", "kotlin", "kotlinx", "com.google" ], "excludedClasses": [ "com.myapp.models.User", "com.myapp.api.ApiResponse" ], "verbose": true } ``` Shield detectará y usará automáticamente `shield-config.json` si está presente en el directorio de tu módulo app. --- ### Configuración #### Project Token (Requerido) Para conectar tu aplicación al dashboard de ByteHide y habilitar la validación en la nube, necesitas configurar tu project token: **Opción 1: Configuración directa en build.gradle.kts** ```kotlin shield { enabled = true setProjectToken("bh_zU5jY5dfZCnfyqUtggndngBfJwUNF1PQQ") // REQUIRED for cloud validation } ``` **Opción 2: Variable de Entorno (Recomendado para CI/CD)** ```kotlin shield { enabled = true setProjectToken(System.getenv("SHIELD_PROJECT_TOKEN")) } ``` Luego configura la variable de entorno: ```sh export SHIELD_PROJECT_TOKEN="bh_zU5jY5dfZCnfyqUtggndngBfJwUNF1PQQ" ``` **Opción 3: Local Properties (Recomendado para desarrollo local)** Añade a tu archivo `local.properties` (este archivo está en gitignore por defecto): ```properties shield.projectToken=bh_zU5jY5dfZCnfyqUtggndngBfJwUNF1PQQ ``` Luego referéncialo en tu `build.gradle.kts`: ```kotlin shield { enabled = true val properties = Properties() properties.load(project.rootProject.file("local.properties").inputStream()) setProjectToken(properties.getProperty("shield.projectToken")) } ``` #### Protection Secret (Opcional) El protection secret es una clave personalizada utilizada para encriptar los stack traces. Esto te permite posteriormente recuperar y desofuscar las excepciones de tu aplicación protegida usando la API de ByteHide. **¿Por qué usar un Protection Secret?** Cuando tu aplicación está ofuscada, los stack traces se vuelven ilegibles. Al configurar un protection secret: - Los stack traces se encriptan con tu clave personalizada - Puedes usar la API de ByteHide para buscar y recuperar excepciones - Desofuscar los stack traces de vuelta a su forma original usando tu archivo de mapeo **Configuración:** ```kotlin shield { enabled = true setProjectToken("bh_YOUR_PROJECT_TOKEN") setProtectionSecret("mi-secret-personalizado-123") // OPTIONAL } ``` **Usando variables de entorno:** ```kotlin shield { enabled = true setProjectToken(System.getenv("SHIELD_PROJECT_TOKEN")) setProtectionSecret(System.getenv("SHIELD_PROTECTION_SECRET")) } ``` **Recuperando excepciones vía API de ByteHide:** Una vez configurado, puedes usar el dashboard o la API de ByteHide para: 1. Buscar excepciones por tu protection secret 2. Ver stack traces encriptados 3. Desofuscarlos usando tu archivo de mapeo 4. Analizar crashes de tu aplicación en producción --- ### Exclusión de Clases y Paquetes #### ¿Por qué Excluir? Deberías excluir ciertos paquetes y clases de la protección para evitar problemas con: - **Serialización** (JSON, XML, Parcelable) - **Frameworks basados en reflexión** - **Clases del sistema Android/AndroidX** - **Librerías de terceros** - **Modelos de API** que necesitan nombres consistentes #### Excluir por Paquete Excluye paquetes completos (incluyendo sub-paquetes): ```kotlin shield { excludedPackages = listOf( "android", // Android framework "androidx", // AndroidX libraries "kotlin", // Kotlin stdlib "kotlinx", // Kotlin extensions "com.google", // Google libraries "com.myapp.api", // Your API models "com.myapp.models" // Your data models ) } ``` #### Excluir por Clase Excluye clases específicas: ```kotlin shield { excludedClasses = listOf( "com.myapp.MainActivity", "com.myapp.models.User", "com.myapp.api.ApiResponse", "com.myapp.serialization.CustomSerializer" ) } ``` #### Patrones con Wildcards Usa wildcards para exclusión flexible: ```kotlin shield { excludedClasses = listOf( "com.myapp.models.*", // Todas las clases del paquete "com.myapp.*Activity", // Todas las activities "**/*Serializer" // Todas las clases serializer ) } ``` #### Exclusión mediante Anotaciones Shield respeta automáticamente las anotaciones en tu código. **No necesitas configuración adicional** - simplemente añade las anotaciones a tus clases: **Anotaciones estándar:** ```kotlin import androidx.annotation.Keep @Keep class UserModel { @Keep var name: String = "" @Keep fun importantMethod() { // Este método no será ofuscado } } ``` **Otras anotaciones soportadas automáticamente:** ```kotlin // Serialización @JsonProperty("user_name") // Jackson @SerializedName("user_name") // Gson // JPA/Hibernate @Entity @Column(name = "username") // Spring @Component @Service @Repository @Controller ``` Shield detecta estas anotaciones automáticamente y excluye las clases/métodos/campos anotados de la protección. #### Integración con ProGuard Si ya tienes reglas de ProGuard en tu proyecto (`proguard-rules.pro`), Shield las respeta. Puedes seguir usando tus reglas de ProGuard existentes: **proguard-rules.pro:** ```proguard # Mantener modelos de datos -keep class com.myapp.models.** { *; } # Mantener clases de API -keep class com.myapp.api.** { *; } # Mantener nombres de métodos nativos -keepclasseswithmembernames class * { native ; } ``` Shield integra estas reglas con su propio sistema de exclusión, por lo que **no perderás tus exclusiones existentes** al adoptar Shield. --- ### Configuración por Variante de Build Configura diferentes niveles de protección para builds Debug y Release: ```kotlin android { buildTypes { debug { // Debug configuration } release { isMinifyEnabled = true proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } } } shield { enabled = true // Debug: minimal protection for faster builds debugProtections { stringEncryption = true constantMutation = false debugRemoval = false nameObfuscation = false controlFlowObfuscation = false antiDebug = false } // Release: maximum protection releaseProtections { stringEncryption = true constantMutation = true debugRemoval = true nameObfuscation = true controlFlowObfuscation = true antiDebug = true antiTamper = true } } ``` --- ### Compilar tu Aplicación Compila tu aplicación normalmente - Shield procesará automáticamente las clases durante la compilación: ```sh # Build Debug (protección mínima) ./gradlew assembleDebug # Build Release (protección completa) ./gradlew assembleRelease # Ver tareas de Shield ./gradlew tasks --all | grep shield ``` **Salida de la Compilación:** ``` > Task :app:transformReleaseClassesWithShield [Shield] ======================================== [Shield] Shield Protection - Variant: release [Shield] ======================================== [Shield] Loading classes... [Shield] Loaded 847 classes (245 app classes, 602 dependencies) [Shield] Applying String Encryption... [Shield] - Encrypted 1,284 strings [Shield] Applying Constant Mutation... [Shield] - Mutated 456 constants [Shield] Applying Name Obfuscation... [Shield] - Renamed 123 classes, 567 methods, 234 fields [Shield] Shield protection completed in 12.3s ``` --- ## Integración iOS (Swift/Objective-C) ### Instalación Instala Shield iOS vía pip: ```sh pip install bytehide-shield-ios # Verificar instalación bytehide-shield --version ``` --- ### Opciones de Uso Shield iOS ofrece **dos métodos de integración**: 1. **Método CLI** - Protege archivos IPA directamente desde línea de comandos 2. **Integración con Xcode** - Protección automática durante los builds de Xcode --- ### Opción 1: Método CLI #### Paso 1: Crear Archivo de Configuración Genera una configuración por defecto: ```sh bytehide-shield init ``` Esto crea `shield.json`: ```json { "projectToken": "bh_YOUR_PROJECT_TOKEN_HERE", "protections": { "anti_debug": true, "anti_jailbreak": true, "string_encryption": true, "symbol_renaming": true, "swift_stripping": true, "control_flow": "medium" }, "code_signing": { "identity": "iPhone Distribution: Your Company", "provisioning_profile": "/path/to/profile.mobileprovision", "skip_if_not_macos": true }, "output": { "suffix": "_protected" } } ``` #### Paso 2: Protege tu IPA ```sh # Protección básica (usa shield.json en el directorio actual) bytehide-shield protect MyApp.ipa # Archivo de configuración personalizado bytehide-shield protect MyApp.ipa --config custom-config.json # Ruta de salida personalizada bytehide-shield protect MyApp.ipa --output MyApp_secured.ipa # Salida detallada bytehide-shield protect MyApp.ipa --verbose ``` **Salida del CLI:** ``` 🛡️ Shield iOS v1.0.0 ✓ Validación en la nube exitosa! ✓ IPA desempaquetado: MyApp ✓ Aplicando protección anti-debug... ✓ Aplicando detección anti-jailbreak... ✓ Encriptando 1,847 strings... ✓ Renombrando 234 símbolos... ✓ Ofuscando flujo de control... ✓ Firma de código con: iPhone Distribution ✓ IPA protegido: MyApp_protected.ipa ✓ Tu aplicación iOS ahora está protegida! 🛡️ ``` --- ### Opción 2: Integración con Xcode Protege tu aplicación automáticamente durante los builds de Xcode. #### Paso 1: Instalar Shield iOS ```sh pip install bytehide-shield-ios ``` #### Paso 2: Copiar Script de Build Copia el script de integración de Xcode a tu proyecto: ```sh cd YourXcodeProject curl -o shield-xcode.sh https://xcode.shield..bytehide.com/install.sh chmod +x shield-xcode.sh ``` #### Paso 3: Añadir Run Script Phase en Xcode 1. Abre tu proyecto en Xcode 2. Selecciona tu **target** 3. Ve a la pestaña **Build Phases** 4. Haz clic en **+ → New Run Script Phase** 5. Nómbralo **"Shield iOS Protection"** 6. **Arrástralo DESPUÉS de "Compile Sources"** y **ANTES de "Copy Bundle Resources"** 7. Añade este script: ```bash bash "${PROJECT_DIR}/shield-xcode.sh" ``` #### Paso 4: Crear Archivo de Configuración Crea `shield.json` en la raíz de tu proyecto: ```json { "projectToken": "bh_YOUR_PROJECT_TOKEN", "protections": { "anti_debug": true, "anti_jailbreak": true, "string_encryption": true, "symbol_renaming": true, "swift_stripping": true, "control_flow": "medium" }, "build_integration": { "skip_debug": true, "skip_simulator": true } } ``` #### Paso 5: Compilar tu Aplicación Compila normalmente en Xcode: ```sh # En Xcode: Product → Build (⌘B) # O vía línea de comandos: xcodebuild -project MyApp.xcodeproj -scheme MyApp -configuration Release ``` ¡Shield protegerá automáticamente tu aplicación durante el build! 🎉 --- ## Configuración ### Project Token El **Project Token** es obligatorio y conecta tu aplicación con el dashboard de ByteHide para validación en la nube. ```json { "projectToken": "bh_zU5jY5dfZCnfyqUtggndngBfJwUNF1PQQ" } ``` **¿Dónde obtener tu token?** 1. Ve a https://cloud.bytehide.com 2. Crea o selecciona un proyecto 3. Copia el token (formato: `bh_...`) --- ### Protection Secret (Opcional) El **Protection Secret** es una clave opcional que Shield usa para encriptar los stack traces de tu aplicación. ```json { "projectToken": "bh_YOUR_PROJECT_TOKEN", "protectionSecret": "mi-secret-personalizado-123" } ``` **¿Por qué usar Protection Secret?** Cuando tu aplicación protegida crashea, los stack traces estarán ofuscados (nombres de clases/métodos renombrados). El Protection Secret te permite: 1. **Encriptar stack traces** - Shield encripta los stack traces usando tu secret 2. **Desofuscar remotamente** - ByteHide API puede desencriptar y mapear los símbolos originales 3. **Debugging post-producción** - Analiza crashes sin exponer tu código fuente **Ejemplo de uso:** ```json { "projectToken": "bh_YOUR_PROJECT_TOKEN", "protectionSecret": "MiSecretSeguro2024!", "protections": { "symbol_renaming": true, "string_encryption": true } } ``` Sin el secret, los stack traces estarán ofuscados pero no podrás mapearlos de vuelta a los nombres originales. --- ### Excluir Clases de la Protección Puedes excluir clases específicas del renombrado de símbolos mediante configuración: ```json { "protections": { "symbol_renaming": { "enabled": true, "exclude": [ "AppDelegate", "SceneDelegate", "*Delegate", // Wildcard: todos los delegates "MyViewController", "NetworkManager" ] } } } ``` **Patrones soportados:** - Nombres exactos: `"AppDelegate"`, `"MyViewController"` - Wildcards: `"*Delegate"` (todos los nombres que terminen en Delegate) - Prefijos: `"Test*"` (todos los nombres que empiecen con Test) --- ### Opciones de Integración con Build Controla cuándo Shield se ejecuta durante los builds de Xcode: ```json { "build_integration": { "skip_debug": true, // Omitir protección para builds Debug "skip_simulator": true, // Omitir protección para builds Simulator "verbose": false // Mostrar salida detallada } } ``` **Configuraciones diferentes para Debug/Release:** Crea `bytehide-shield-debug.json`: ```json { "protections": { "anti_debug": false, "string_encryption": true } } ``` Crea `bytehide-shield-release.json`: ```json { "protections": { "anti_debug": true, "anti_jailbreak": true, "string_encryption": true, "control_flow": "medium" } } ``` Actualiza tu Run Script Phase: ```bash if [ "${CONFIGURATION}" = "Debug" ]; then CONFIG="bytehide-shield-debug.json" else CONFIG="bytehide-shield-release.json" fi bytehide-shield protect "${APP}" --config "${PROJECT_DIR}/${CONFIG}" ``` --- ## Integración CI/CD ### Android - GitHub Actions ```yaml name: Build Android App on: push: branches: [main] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up JDK 11 uses: actions/setup-java@v3 with: java-version: '11' distribution: 'temurin' - name: Build con Shield env: SHIELD_PROJECT_TOKEN: ${{ secrets.SHIELD_PROJECT_TOKEN }} run: | ./gradlew assembleRelease - name: Subir APK uses: actions/upload-artifact@v3 with: name: app-release path: app/build/outputs/apk/release/app-release.apk ``` ### iOS - GitHub Actions ```yaml name: Build iOS App on: push: branches: [main] jobs: build: runs-on: macos-latest steps: - uses: actions/checkout@v3 - name: Instalar Shield iOS run: pip install bytehide-shield-ios - name: Compilar IPA run: | xcodebuild archive \ -project MyApp.xcodeproj \ -scheme MyApp \ -configuration Release \ -archivePath MyApp.xcarchive xcodebuild -exportArchive \ -archivePath MyApp.xcarchive \ -exportPath . \ -exportOptionsPlist ExportOptions.plist - name: Proteger App env: SHIELD_TOKEN: ${{ secrets.SHIELD_PROJECT_TOKEN }} run: | cat > shield-config.json << EOF { "projectToken": "$SHIELD_TOKEN", "protections": { "anti_debug": true, "string_encryption": true, "control_flow": "medium" } } EOF bytehide-shield protect MyApp.ipa --config shield-config.json - name: Subir IPA uses: actions/upload-artifact@v3 with: name: app-protected path: MyApp_protected.ipa ``` ### GitLab CI **Android:** ```yaml build_android: stage: build image: gradle:7.6-jdk11 script: - ./gradlew assembleRelease artifacts: paths: - app/build/outputs/apk/release/app-release.apk ``` **iOS:** ```yaml build_ios: stage: build image: macos-12-xcode-14 script: - pip install bytehide-shield-ios - xcodebuild archive ... - bytehide-shield protect MyApp.ipa --config shield-config.json artifacts: paths: - MyApp_protected.ipa ``` --- ## Protecciones Disponibles Shield ofrece un conjunto completo de protecciones de seguridad para tus aplicaciones móviles en Android e iOS: --- ### 1. Encriptación de Strings Encripta todas las cadenas de texto en tu código para evitar que sean legibles en el binario. Las strings se desencriptan en tiempo de ejecución solo cuando se necesitan. **Configuración Android:** ```kotlin protections { stringEncryption = true } ``` **Configuración iOS:** ```json { "protections": { "string_encryption": true } } ``` **Qué protege:** Evita que atacantes extraigan URLs, API keys, mensajes, y otras strings sensibles del APK o IPA descompilado. --- ### 2. Ofuscación de Nombres Renombra clases, métodos, campos y propiedades con nombres cortos y sin sentido (a, b, c, aa, ab...) manteniendo la funcionalidad completa de la aplicación. **Configuración Android:** ```kotlin protections { nameObfuscation = true } ``` **Configuración iOS:** ```json { "protections": { "symbol_renaming": true } } ``` **Qué protege:** Dificulta enormemente la lectura del código descompilado al eliminar nombres descriptivos que revelan la arquitectura y lógica de tu aplicación. --- ### 3. Ofuscación de Flujo de Control Reestructura el flujo de ejecución del código insertando saltos, condiciones opacas y bloques de código falsos, haciendo extremadamente difícil seguir la lógica del programa. **Configuración Android:** ```kotlin protections { controlFlowObfuscation = true } ``` **Configuración iOS:** ```json { "protections": { "control_flow": "medium" } } ``` **Qué protege:** Hace extremadamente difícil seguir la lógica del programa, incluso con decompiladores avanzados. Esta es la protección más intensiva computacionalmente. --- ### 4. Mutación de Constantes Transforma valores constantes en expresiones calculadas en tiempo de ejecución, haciendo más difícil entender la lógica del código. **Configuración Android:** ```kotlin protections { constantMutation = true } ``` **Configuración iOS:** ```json { "protections": { "constant_mutation": true } } ``` **Qué protege:** Oculta valores numéricos, booleanos y constantes que podrían revelar lógica de negocio, límites de sistema o parámetros de seguridad. --- ### 5. Anti-Debug Detecta y bloquea intentos de debugging en tiempo de ejecución, evitando que atacantes analicen tu app con debuggers. **Configuración Android:** ```kotlin protections { antiDebug = true } ``` **Configuración iOS:** ```json { "protections": { "anti_debug": true } } ``` **Qué protege:** Previene análisis dinámico con herramientas como Android Studio Debugger, LLDB, Frida, JDWP, y otros frameworks de debugging y hooking. --- ### 6. Anti-Jailbreak/Root Detecta dispositivos jailbroken (iOS) o rooteados (Android) y puede terminar la app o alertar al servidor. **Configuración Android:** ```kotlin protections { antiRoot = true } ``` **Configuración iOS:** ```json { "protections": { "anti_jailbreak": true } } ``` **Qué protege:** Evita que tu app se ejecute en entornos comprometidos donde existen herramientas avanzadas de hacking como Magisk, Xposed, Cydia o Sileo. --- ### 7. Eliminación de Información de Debug Elimina toda la información de debugging, logs, símbolos de depuración y metadatos del binario compilado. **Configuración Android:** ```kotlin protections { debugRemoval = true } ``` **Configuración iOS:** ```json { "protections": { "strip_debug": true } } ``` **Qué protege:** Elimina trazas, logs, símbolos y metadatos que facilitan el análisis y reversing del código. --- ### 8. Swift Symbol Stripping Elimina metadatos de reflexión y nombres de símbolos Swift del binario, específicamente diseñado para código Swift en iOS. **Configuración iOS:** ```json { "protections": { "swift_stripping": true } } ``` **Qué protege:** Reduce el tamaño del binario y elimina nombres de tipos Swift, metadatos de reflexión y nombres de protocolos que son valiosos para atacantes. --- ### 9. Reference Proxy Crea clases y métodos proxy intermediarios que redirigen todas las llamadas a métodos y accesos a campos, añadiendo una capa de indirección que dificulta el análisis estático del código. **Configuración Android:** ```kotlin protections { referenceProxy = true } ``` **Configuración iOS:** ```json { "protections": { "reference_proxy": true } } ``` **Qué protege:** Hace extremadamente difícil rastrear el flujo de datos y las llamadas entre componentes. Los decompiladores muestran proxies en lugar de las referencias directas reales. --- ### 10. Inyección de Código Inválido Inserta código bytecode sintácticamente válido pero semánticamente inválido que nunca se ejecuta. Este código confunde y rompe herramientas de análisis estático y decompiladores. **Configuración Android:** ```kotlin protections { invalidCodeInjection = true } ``` **Configuración iOS:** ```json { "protections": { "invalid_code": true } } ``` **Qué protege:** Muchos decompiladores y herramientas de análisis fallan al encontrar este código, mostrando errores o código ilegible. Esto previene el análisis automatizado del binario. --- **Shield** es un producto comercial de **ByteHide**. Visita https://bytehide.com para más información. --- # Detecting and Responding to Runtime Attacks Your application is live. Static analysis ran during development, obfuscation protected the build. But once the application is running, it faces a completely different category of threats. This guide explains how runtime protection actually works under the hood, why the tools most teams rely on have architectural blind spots they cannot fix, and what effective runtime defense looks like for both cloud APIs and mobile applications. {% .lead %} --- ## Two Different Runtime Problems Runtime security covers two fundamentally different scenarios. The threats, the attack surface, and the protection mechanisms are completely different. Understanding this split is the starting point for any runtime security strategy. ```mermaid flowchart TB subgraph "Cloud / Server" C1["The attacker sends requests
to your API"] C1 --> C2["Injection attacks"] C1 --> C3["Business logic abuse"] C1 --> C4["Bot and session attacks"] end subgraph "Mobile" M1["The attacker has your binary
on their device"] M1 --> M2["Reverse engineering"] M1 --> M3["Hooking & debugging"] M1 --> M4["Tampering & repackaging"] end style C1 fill:#4f46e5,color:#fff style M1 fill:#7c3aed,color:#fff ``` **On cloud/server**, the attacker sends requests. They are trying to exploit vulnerabilities in your code through the network. Your application processes those requests, and the attack happens inside the execution path. **On mobile**, the attacker has your binary on their device. They can decompile it, attach a debugger, hook functions, and modify the binary itself. There is no server sitting in front of it. This guide covers both, starting with cloud because it is where most teams already have (and over-trust) their existing defenses. --- ## Part 1: Cloud and API Runtime Security ### How a Web Application Firewall Actually Works Before understanding why a WAF has limitations, it helps to understand what it actually does at a technical level. Most teams deploy a WAF and trust it without fully understanding the architecture. That understanding is what separates a reasonable security posture from a dangerous one. A WAF is a reverse proxy. It sits between the internet and your application server. Every HTTP request passes through it before reaching your application. ```mermaid flowchart LR U["Client"] -->|"HTTP Request"| W["WAF
(Reverse Proxy)"] W -->|"Inspect"| R{"Rule Engine"} R -->|"Match"| B["Block"] R -->|"No Match"| A["Forward to
Application"] style W fill:#f97316,color:#fff style B fill:#ef4444,color:#fff style A fill:#22c55e,color:#fff ``` When a request arrives, the WAF performs these steps: **1. Request parsing.** The WAF extracts the components of the HTTP request: URL path, query parameters, headers, cookies, and request body. It decodes URL encoding, Base64, and common encoding schemes. **2. Signature matching.** Each component is compared against a library of regular expressions that represent known attack patterns. For SQL injection, these are patterns like `' OR 1=1`, `UNION SELECT`, `; DROP TABLE`, `WAITFOR DELAY`, and hundreds of variations. For XSS, patterns like ` ``` ## Basic Integration Example ### Node.js / ES Modules ```javascript import { Log } from '@bytehide/logger'; // Configure the logger Log.configure({ minimumLevel: 'info', consoleEnabled: true }); // Set your project token Log.setProjectToken('your-project-token'); // Start logging Log.info('Application started successfully!'); ``` ### CommonJS (Node.js) ```javascript const { Log } = require('@bytehide/logger'); // Configure the logger Log.configure({ minimumLevel: 'info', consoleEnabled: true }); // Set your project token Log.setProjectToken('your-project-token'); // Start logging Log.info('Application started successfully!'); ``` ### Browser ```html ``` ## Verify Installation After installing the SDK, you can verify it's working by logging a test message: ```javascript import { Log } from '@bytehide/logger'; // Configure the logger Log.configure({ minimumLevel: 'debug', consoleEnabled: true }); Log.setProjectToken('your-project-token'); try { // Test logging Log.info('ByteHide Logger initialized successfully!'); Log.debug('Debug message - visible with debug level'); Log.warn('Warning message'); Log.error('Error message for testing'); console.log('Logger is working correctly!'); } catch (error) { console.error('Error initializing logger:', error.message); } ``` ## Runtime Compatibility ByteHide Logger is compatible with: ### Server-side Environments - **Node.js 16+**: Full logging capabilities including file persistence - **Deno**: Modern TypeScript runtime - **Bun**: Fast JavaScript runtime ### Browser Support - **Chrome 88+**: Full support for modern features - **Firefox 78+**: Complete compatibility - **Safari 14+**: Full support - **Edge 88+**: Complete functionality ### Framework Compatibility - **Express.js**: Server-side web applications - [Integration guide](/platforms/javascript/products/logs/frameworks/express) - **React**: Client-side applications - [Integration guide](/platforms/javascript/products/logs/frameworks/react) - **Next.js**: Full-stack applications - [Integration guide](/platforms/javascript/products/logs/frameworks/nextjs) - **Vue.js**: Progressive framework - [Integration guide](/platforms/javascript/products/logs/frameworks/vue) - **Angular**: Enterprise applications - [Integration guide](/platforms/javascript/products/logs/frameworks/angular) - **Fastify**: High-performance server - [Integration guide](/platforms/javascript/products/logs/frameworks/fastify) ## Environment-Specific Setup ### Node.js Applications ```javascript import { Log } from '@bytehide/logger'; // Node.js specific configuration Log.configure({ minimumLevel: 'info', consoleEnabled: true, persist: true, // Enable file logging filePath: 'logs/app.log', rollingInterval: 'day' }); Log.setProjectToken(process.env.BYTEHIDE_PROJECT_TOKEN); Log.info('Node.js application started'); ``` ### Browser Applications ```javascript import { Log } from '@bytehide/logger'; // Browser specific configuration Log.configure({ minimumLevel: 'warn', consoleEnabled: true // Note: File logging not available in browsers }); Log.setProjectToken('your-project-token'); Log.info('Web application started'); ``` ## TypeScript Support ByteHide Logger includes TypeScript definitions: ```typescript import { Log, LogSettings } from '@bytehide/logger'; // Type-safe configuration const config: Partial = { minimumLevel: 'info', consoleEnabled: true, maskSensitiveData: ['password', 'token'] }; Log.configure(config); Log.setProjectToken('your-project-token'); // Type-safe logging Log.info('TypeScript application started', { metadata: { version: '1.0.0' }, tags: ['startup', 'typescript'] }); ``` ## Next Steps - [Learn how to configure the logger](/platforms/javascript/products/logs/core/configuration) - [Follow the quick start guide](/platforms/javascript/products/logs/core/quick-start) - [Explore basic logging features](/platforms/javascript/products/logs/features/basic-logging) --- # Quick Start with ByteHide Logger > **Prerequisites** > Before you begin, make sure you have: > - A ByteHide account and [project token](/platforms/javascript/products/logs/create-logs-project) > - Node.js 16+ for server-side applications or a modern browser for client-side applications ## Quick Start Guide 1. **Install ByteHide Logger** in your project 2. **Configure** the logger with your settings 3. **Set your project token** for cloud logging 4. **Start logging** with simple API calls 5. **View logs** in the ByteHide web panel 6. **Explore advanced features** as needed ## Step 1: Installation Add the ByteHide Logger package to your project: ```bash npm install @bytehide/logger ``` ## Step 2: Basic Setup Initialize the logger in your application startup: ### Node.js Application ```javascript import { Log } from '@bytehide/logger'; // Step 1: Configure the logger Log.configure({ minimumLevel: 'debug', consoleEnabled: true, maskSensitiveData: ['password', 'token'], duplicateSuppressionWindowMs: 1000, // File logging for Node.js persist: true, filePath: 'logs/app.log', rollingInterval: 'day' }); // Step 2: Set your project token Log.setProjectToken('your-project-token'); // Step 3: Add global metadata Log.addMetaContext('AppVersion', '1.2.3'); Log.addMetaContext('Environment', 'Development'); // Your application code runApplication(); function runApplication() { Log.info('Application started successfully!'); try { // Simulate some work processOrder('ORD-001', 'CUST-123'); } catch (error) { Log.critical('Application error occurred', { tags: ['critical'] }, error); } finally { Log.info('Application finished'); } } function processOrder(orderId, customerId) { const correlationId = generateCorrelationId(); Log.info('Processing order', { correlationId, tags: ['orders', 'processing'], metadata: { orderId, customerId } }); // Simulate processing time setTimeout(() => { Log.info('Order processed successfully', { correlationId, tags: ['orders', 'success'], metadata: { orderId, processingTime: '1.2s' } }); }, 1000); } function generateCorrelationId() { return Math.random().toString(36).substring(2, 15); } ``` ### Browser Application ```html ByteHide Logger Demo

ByteHide Logger Quick Start

``` ## Step 3: Basic Logging Use the simple logging API throughout your application: ```javascript import { Log } from '@bytehide/logger'; // Simple logging Log.info('User logged in'); Log.warn('API rate limit approaching'); Log.error('Database connection failed'); // Logging with context Log.info('User action performed', { tags: ['user', 'action'], metadata: { userId: '12345', action: 'profile_update' } }); // Logging with correlation ID const correlationId = 'req-abc123'; Log.debug('Processing request', { correlationId, tags: ['api', 'request'], metadata: { endpoint: '/api/users' } }); // Error logging with exception try { // Some operation that might fail throw new Error('Something went wrong'); } catch (error) { Log.error('Operation failed', { tags: ['error', 'operation'], metadata: { operation: 'user_update' } }, error); } ``` ## Step 4: Advanced Features ### User Identification ```javascript // Identify user for all subsequent logs Log.identify('john.doe', 'john@example.com', 'user-token-123'); // All logs after this will include user information Log.info('User performed action'); Log.warn('User attempted unauthorized action'); ``` ### Correlation IDs for Request Tracking ```javascript // Generate correlation ID for request tracking const correlationId = crypto.randomUUID(); Log.info('Request started', { correlationId, tags: ['api', 'request'], metadata: { method: 'POST', endpoint: '/api/orders' } }); Log.info('Validating request data', { correlationId, tags: ['validation'] }); Log.info('Request completed', { correlationId, tags: ['api', 'response'], metadata: { statusCode: 200, duration: '150ms' } }); ``` ### Data Masking in Action ```javascript // Sensitive data will be automatically masked Log.info('User login attempt', { metadata: { username: 'john.doe', password: 'secret123', // Will be masked as *** token: 'abc123xyz', // Will be masked as *** email: 'john@example.com' // Will not be masked } }); ``` ### Duplicate Suppression ```javascript // These duplicate messages will be suppressed for (let i = 0; i < 10; i++) { Log.warn('Database connection slow'); // Only first occurrence logged } // Different messages are not suppressed Log.warn('API rate limit reached'); Log.warn('Memory usage high'); ``` ## Step 5: View Your Logs After your application runs, you can view logs in multiple places: ### Console Output (Development) ``` [2024-01-15 10:30:15] [INFO] Application started successfully! {AppVersion: "1.2.3", Environment: "Development"} [2024-01-15 10:30:15] [INFO] Processing order {correlationId: "abc123", orderId: "ORD-001", customerId: "CUST-123"} [2024-01-15 10:30:16] [INFO] Order processed successfully {correlationId: "abc123", orderId: "ORD-001", processingTime: "1.2s"} ``` ### Log Files (Node.js) Check your configured log file path (e.g., `logs/app.log`): ``` 2024-01-15 10:30:15.123 [INFO] Application started successfully! AppVersion=1.2.3 Environment=Development 2024-01-15 10:30:15.456 [INFO] Processing order correlationId=abc123 orderId=ORD-001 customerId=CUST-123 2024-01-15 10:30:16.789 [INFO] Order processed successfully correlationId=abc123 orderId=ORD-001 processingTime=1.2s ``` ### ByteHide Web Panel 1. Log in to [ByteHide Cloud](https://cloud.bytehide.com) 2. Select your Logs project 3. View real-time logs, search, filter, and analyze ## Dynamic Logging Control ```javascript // Disable logging temporarily Log.disable(); Log.info('This will not be logged'); // Re-enable logging Log.enable(); Log.info('Logging is active again'); // Reset all configuration Log.reset(); // Reconfigure Log.configure({ minimumLevel: 'warn', consoleEnabled: true }); ``` ## Best Practices > **JavaScript Logging Best Practices** > - **Configure early**: Set up logging at application startup > - **Use correlation IDs**: Track requests across async operations > - **Tag consistently**: Establish tagging conventions for your team > - **Mask sensitive data**: Always include PII and credentials in masking > - **Environment-specific config**: Use different settings for dev/prod > - **File logging**: Only use in Node.js, not in browsers ## Next Steps Now that you have basic logging working: - [Explore configuration options](/platforms/javascript/products/logs/core/configuration) - [Learn about advanced features](/platforms/javascript/products/logs/features/basic-logging) - [Set up framework integrations](/platforms/javascript/products/logs/frameworks/express) - [Configure the web panel](/platforms/javascript/products/logs/web-panel/log-visualization) --- # Create a Logs Project ## What are ByteHide Projects? ByteHide projects are the foundation for organizing and managing your application logs and monitoring. Projects allow you to: - **Organize your logs** by application or service - **Manage multiple environments** (development, staging, production) - **Control access** for team members with different permission levels - **Configure alerting** for log monitoring and error detection - **View logging history** and analyze patterns across your applications - **Connect with source control** for automated log correlation Each project provides a unique token that authenticates your applications with the ByteHide logging service. ## Create Your Project 1. Sign in to [ByteHide Cloud](https://cloud.bytehide.com) 2. Go to **Projects** section 3. Click **Create Project** in the dashboard ![Create Project](/images/dotnet/logs/create-project.png) 4. Select **Logs** as the project type 5. Enter a project name and description ![Project Configuration](/images/dotnet/logs/project-config.png) 6. Click **Create** ## Get Your Project Token > **Security Notice** > Keep your project token secure and never commit it to source control. After creating your project, you'll need the project token for your logging configuration: 1. Go to your logs project 2. In the main view you will see the **Project token** box ![Project Token](/images/dotnet/logs/project-token.png) 3. Copy your project token ## Project Settings In the ByteHide Cloud panel, you can configure: - **Environments**: Set up different environments (development, staging, production) - **Access Control**: Manage team access and permissions - **Notifications**: Configure alerts for critical errors and monitoring - **Integrations**: Set up CI/CD and webhook integrations - **Retention**: Configure log retention periods ## Next Steps Choose your integration path: - [Logger SDK](/platforms/javascript/products/logs/core/installation) — Install and configure the ByteHide Logger SDK in your JavaScript application. --- # Browser ByteHide Logger works in all modern browsers with console logging capabilities. File logging is not available in browser environments. {% .lead %} ## Installation ### Via CDN ```html ``` ### Via npm ```bash npm install @bytehide/logger ``` ```javascript import { Log } from '@bytehide/logger'; ``` ## Basic Setup ```javascript // Configure logger Log.configure({ projectToken: 'your-project-token', logLevel: 'info', consoleOutput: true }); // Start logging Log.info('Application loaded'); ``` ## Browser-Specific Features ### User Session Tracking ```javascript Log.identify(userId, userEmail); Log.info('User action performed', { context: { action: 'button-click', page: window.location.pathname } }); ``` ### Error Handling ```javascript window.addEventListener('error', (event) => { Log.error('Unhandled error occurred', { context: { filename: event.filename, lineno: event.lineno, colno: event.colno } }, event.error); }); ``` ## React Integration ```javascript import { Log } from '@bytehide/logger'; function App() { useEffect(() => { Log.configure({ projectToken: process.env.REACT_APP_BYTEHIDE_TOKEN }); }, []); const handleClick = () => { Log.info('Button clicked', { context: { component: 'App', action: 'click' } }); }; return ; } ``` ## Limitations > **Browser Limitations** > - **No file logging**: Browsers cannot write to the file system > - **Console only**: All logs output to browser console > - **Network requests**: Logs are sent to ByteHide cloud service > - **CORS considerations**: Ensure proper CORS configuration --- # Bun ByteHide Logger works seamlessly with Bun's fast JavaScript runtime, providing excellent performance for logging operations. {% .lead %} ## Installation ```bash bun add @bytehide/logger ``` ## Basic Setup ```javascript import { Log } from '@bytehide/logger'; // Configure logger Log.configure({ projectToken: 'your-project-token', logLevel: 'info', consoleOutput: true }); // Start logging Log.info('Bun application started'); ``` ## TypeScript Support ```typescript import { Log } from '@bytehide/logger'; Log.configure({ projectToken: process.env.BYTEHIDE_PROJECT_TOKEN!, logLevel: 'info' }); Log.info('TypeScript with Bun works great'); ``` ## Environment Variables ```javascript // Using Bun's built-in environment support Log.configure({ projectToken: process.env.BYTEHIDE_PROJECT_TOKEN, logLevel: process.env.LOG_LEVEL || 'info' }); ``` ## File Logging ```javascript Log.configure({ projectToken: 'your-project-token', fileOutput: { enabled: true, path: './logs' } }); ``` ## Bun Server Integration ```javascript import { Log } from '@bytehide/logger'; const server = Bun.serve({ port: 3000, fetch(req) { Log.info('Request received', { context: { method: req.method, url: req.url } }); return new Response('Hello from Bun!'); }, }); Log.info(`Server running on port ${server.port}`); ``` ## Performance Bun's fast runtime provides excellent logging performance: ```javascript // High-frequency logging performs well with Bun for (let i = 0; i < 1000; i++) { Log.debug('Processing item', { context: { itemId: i } }); } ``` ## Best Practices > **Bun Best Practices** > - Leverage Bun's fast startup time for logging initialization > - Use TypeScript for better development experience > - Take advantage of Bun's built-in environment variable support > - Utilize Bun's performance for high-frequency logging scenarios --- # Deno ByteHide Logger supports Deno with full TypeScript integration and modern JavaScript features. {% .lead %} ## Installation ```typescript import { Log } from "https://deno.land/x/bytehide_logger/mod.ts"; ``` ## Basic Setup ```typescript // Configure logger Log.configure({ projectToken: 'your-project-token', logLevel: 'info', consoleOutput: true }); // Start logging Log.info('Deno application started'); ``` ## TypeScript Support ```typescript interface UserContext { userId: number; username: string; } const userContext: UserContext = { userId: 123, username: 'john.doe' }; Log.info('User logged in', { context: userContext }); ``` ## Environment Variables ```typescript // Load from environment Log.configure({ projectToken: Deno.env.get('BYTEHIDE_PROJECT_TOKEN'), logLevel: Deno.env.get('LOG_LEVEL') || 'info' }); ``` ## File Logging ```typescript // Requires --allow-write permission Log.configure({ projectToken: 'your-project-token', fileOutput: { enabled: true, path: './logs' } }); ``` ## Permissions Run with necessary permissions: ```bash deno run --allow-net --allow-env --allow-write app.ts ``` ## Best Practices > **Deno Best Practices** > - Use TypeScript for better type safety > - Configure proper permissions for file logging > - Use environment variables for sensitive configuration > - Leverage Deno's built-in testing framework --- # Node.js ByteHide Logger provides full logging capabilities in Node.js environments, including console and file logging. {% .lead %} ## Installation ```bash npm install @bytehide/logger ``` ## Basic Setup ```javascript const { Log } = require('@bytehide/logger'); // Configure logger Log.configure({ projectToken: 'your-project-token', logLevel: 'info', consoleOutput: true, fileOutput: { enabled: true, path: './logs' } }); // Start logging Log.info('Application started'); ``` ## File Logging Node.js supports file logging with automatic rotation: ```javascript Log.configure({ projectToken: 'your-project-token', fileOutput: { enabled: true, path: './logs', maxFileSize: '10MB', maxFiles: 5 } }); ``` ## Environment Variables ```javascript // Load from environment Log.configure({ projectToken: process.env.BYTEHIDE_PROJECT_TOKEN, logLevel: process.env.LOG_LEVEL || 'info' }); ``` ## Express.js Integration ```javascript const express = require('express'); const app = express(); app.use((req, res, next) => { Log.info('Request received', { context: { method: req.method, url: req.url } }); next(); }); ``` ## Best Practices > **Node.js Best Practices** > - Use file logging for production applications > - Configure log rotation to manage disk space > - Use environment variables for configuration > - Log unhandled exceptions and promise rejections --- # Basic Logging ByteHide Logger provides six logging levels with simple, intuitive methods. Each level serves different purposes and accepts various parameters for flexible logging. {% .lead %} ## Logging Methods Overview | Method | Purpose | Parameters | |--------|---------|------------| | `Log.trace(message, options)` | Most detailed diagnostic information | `string message`, `object options` | | `Log.debug(message, options)` | Detailed diagnostic information | `string message`, `object options` | | `Log.info(message, options)` | General information messages | `string message`, `object options` | | `Log.warn(message, options)` | Warning messages | `string message`, `object options` | | `Log.error(message, options, error)` | Error messages | `string message`, `object options`, `Error error` | | `Log.critical(message, options, error)` | Critical errors | `string message`, `object options`, `Error error` | ## Basic Logging Methods ### Trace Level Use for the most detailed diagnostic information: ```javascript Log.trace('Entering function processOrder'); Log.trace('Processing item 1 of 10'); Log.trace('Database connection established'); ``` ### Debug Level Use for detailed diagnostic information during development: ```javascript Log.debug('User authentication started'); Log.debug('Cache miss for key: user_123'); Log.debug('API response received in 250ms'); ``` ### Info Level Use for general information about application flow: ```javascript Log.info('Application started successfully'); Log.info('User logged in'); Log.info('Order processed successfully'); ``` ## Advanced Logging Methods ### Warn Level Use for potential issues that don't stop execution: ```javascript // Simple warning Log.warn('API rate limit approaching'); // Warning with context Log.warn('Non-critical operation failed, using fallback', { context: { operation: 'cacheUpdate', fallback: 'database' } }); ``` ### Error Level Use for errors that affect functionality: ```javascript // Error with context and error object try { await processOrder(orderId); } catch (error) { Log.error('Failed to process order', { context: { orderId, userId }, metadata: { attempt: 1 } }, error); } // Error with context only Log.error('Invalid configuration detected', { context: { configFile: 'config.json', section: 'database' } }); ``` ### Critical Level Use for critical errors that may cause application termination: ```javascript // Critical error with error object try { await initializeDatabase(); } catch (error) { Log.critical('Failed to initialize database - application cannot continue', { context: { connectionString: '***' } }, error); process.exit(1); } // Critical error without error object Log.critical('Out of memory - shutting down', { metadata: { memoryUsage: '95%' } }); ``` ## Options Object All logging methods accept an `options` object with these properties: ```javascript const options = { context: { orderId: '123', userId: '456' }, tags: ['orders', 'payment'], correlationId: 'req-abc123', metadata: { processingTime: 250, attempt: 1 } }; Log.info('Order processed successfully', options); ``` ## Practical Examples ### API Request Logging ```javascript // Express.js route app.post('/api/orders', async (req, res) => { const correlationId = req.headers['x-correlation-id'] || generateId(); Log.info('Order creation started', { correlationId, context: { customerId: req.body.customerId }, tags: ['api', 'orders'] }); try { const order = await orderService.create(req.body); Log.info('Order created successfully', { correlationId, context: { orderId: order.id }, metadata: { processingTime: Date.now() - startTime } }); res.json(order); } catch (error) { Log.error('Order creation failed', { correlationId, context: { customerId: req.body.customerId }, tags: ['api', 'orders', 'error'] }, error); res.status(500).json({ error: 'Internal server error' }); } }); ``` ### Service Layer Logging ```javascript class OrderService { async createOrder(orderData) { Log.info('Creating new order', { context: { customerId: orderData.customerId }, tags: ['service', 'orders'] }); try { const order = await this.repository.save(orderData); Log.info('Order created successfully', { context: { orderId: order.id }, metadata: { itemCount: orderData.items.length } }); return order; } catch (error) { Log.error('Failed to create order', { context: { customerId: orderData.customerId }, tags: ['service', 'orders', 'error'] }, error); throw error; } } } ``` ### Background Task Logging ```javascript class EmailProcessor { async processEmails() { Log.info('Email processing started', { tags: ['background', 'email'] }); const emails = await this.getePendingEmails(); Log.debug('Found pending emails', { metadata: { count: emails.length }, tags: ['background', 'email'] }); for (const email of emails) { try { await this.sendEmail(email); Log.trace('Email sent successfully', { context: { emailId: email.id, recipient: email.to } }); } catch (error) { Log.error('Failed to send email', { context: { emailId: email.id }, tags: ['email', 'error'] }, error); } } Log.info('Email processing completed', { metadata: { processed: emails.length }, tags: ['background', 'email'] }); } } ``` ## Best Practices > **When to Use Each Level** > - **Trace**: Function entry/exit, loop iterations, detailed flow > - **Debug**: Variable values, cache hits/misses, intermediate results > - **Info**: Application milestones, user actions, business events > - **Warn**: Recoverable errors, deprecated usage, performance issues > - **Error**: Exceptions, failed operations, data inconsistencies > - **Critical**: System failures, security breaches, unrecoverable errors ### Context Best Practices ```javascript // ✅ Good - Structured context Log.error('Order processing failed', { context: { orderId: order.id, stage: 'payment', amount: order.total } }, error); // ❌ Avoid - String concatenation Log.error(`Order ${order.id} processing failed at payment stage with amount ${order.total}`); // ✅ Good - Relevant context only Log.error('Database query failed', { context: { query: 'getUserById', userId } }, error); // ❌ Avoid - Too much context Log.error('Database query failed', { context: entireUserObject }, error); ``` ## Next Steps - [Error Logging](/platforms/javascript/products/logs/features/error-logging) - Learn proper error handling with Error and Critical methods - [Data Masking](/platforms/javascript/products/logs/features/data-masking) - Protect sensitive information - [User Identification](/platforms/javascript/products/logs/features/user-identification) - Associate logs with users - [Correlation IDs](/platforms/javascript/products/logs/features/correlation-ids) - Track requests across services - [Global Metadata](/platforms/javascript/products/logs/features/global-metadata) - Add consistent context to all logs --- # Correlation IDs Correlation IDs help you track requests as they flow through different services, components, and layers of your application. {% .lead %} ## Basic Usage Use the `correlationId` property in the options object: ```javascript // Set correlation ID for a log entry Log.info('Payment process started', { correlationId: 'operation-123' }); // Use with different log levels Log.debug('Processing user request', { correlationId: 'req-456' }); Log.error('Request failed', { correlationId: 'req-456', context: { errorCode: 'TIMEOUT' } }, error); ``` ## Generating Correlation IDs ```javascript // Generate unique correlation IDs const correlationId = crypto.randomUUID().substring(0, 8); // Or use a simple function const generateId = () => Math.random().toString(36).substring(2, 10); Log.info('Order processing started', { correlationId: generateId() }); ``` ## Express.js Integration ```javascript // Middleware to add correlation ID to all requests app.use((req, res, next) => { req.correlationId = req.headers['x-correlation-id'] || crypto.randomUUID().substring(0, 8); res.setHeader('x-correlation-id', req.correlationId); next(); }); // Use in routes app.post('/api/orders', async (req, res) => { Log.info('Order creation started', { correlationId: req.correlationId, context: { customerId: req.body.customerId } }); try { const order = await orderService.create(req.body, req.correlationId); Log.info('Order created successfully', { correlationId: req.correlationId, context: { orderId: order.id } }); res.json(order); } catch (error) { Log.error('Order creation failed', { correlationId: req.correlationId }, error); res.status(500).json({ error: 'Failed to create order' }); } }); ``` ## Service Layer Usage ```javascript class OrderService { async createOrder(orderData, correlationId) { Log.info('Order validation started', { correlationId, context: { customerId: orderData.customerId } }); try { const order = await this.processOrder(orderData); Log.info('Order processed successfully', { correlationId, context: { orderId: order.id } }); return order; } catch (error) { Log.error('Order processing failed', { correlationId, context: { customerId: orderData.customerId } }, error); throw error; } } } ``` ## Best Practices > **Correlation ID Best Practices** > - **Use short IDs**: 8-12 characters are usually sufficient > - **Pass IDs between services**: Include correlation IDs when calling other services > - **Generate unique IDs**: Use crypto.randomUUID() or similar for unique identifiers > - **Log at boundaries**: Always log when entering/exiting services or operations ## Next Steps - [Global Metadata](/platforms/javascript/products/logs/features/global-metadata) - Add consistent context to all logs - [User Identification](/platforms/javascript/products/logs/features/user-identification) - Associate logs with users - [Tags](/platforms/javascript/products/logs/features/tags) - Organize and categorize logs --- # Data Masking Data masking automatically protects sensitive information in your logs by replacing sensitive values with masked characters. {% .lead %} ## How Data Masking Works ByteHide Logger automatically scans log messages and context objects for sensitive property names and masks their values: ```javascript // Original log Log.info('User login', { context: { username: 'john.doe', password: 'secret123' } }); // Output with masking // [Info] User login { username: "john.doe", password: "***" } ``` ## Configuration Configure data masking during logger initialization: ```javascript Log.configure({ maskSensitiveData: ['password', 'token', 'secret', 'key'] // Default: ['password', 'token'] }); ``` ## Default Masked Properties ByteHide Logger masks these properties by default: | Property Name | Example Values | |---------------|----------------| | `password` | `password`, `PASSWORD`, `user_password` | | `token` | `token`, `ACCESS_TOKEN`, `auth_token` | ## Custom Masking Patterns ```javascript Log.configure({ maskSensitiveData: [ // Default patterns 'password', 'token', // Custom patterns 'secret', 'key', 'credential', 'connectionstring', 'api_key', 'bearer_token', 'ssn', 'credit_card', 'phone', 'email' ] }); ``` ## Masking Examples ### Simple Object Masking ```javascript Log.info('User authentication', { context: { username: 'john.doe', password: 'mySecretPassword', // Will be masked email: 'john@example.com' } }); // Output: { username: "john.doe", password: "***", email: "john@example.com" } ``` ### Complex Object Masking ```javascript const userProfile = { id: 123, username: 'john.doe', credentials: { password: 'secret123', // Masked apiKey: 'abc123xyz', // Masked if configured lastLogin: new Date() } }; Log.error('Profile update failed', { context: userProfile }, error); ``` ## Environment-Specific Configuration ```javascript // Development - minimal masking if (process.env.NODE_ENV === 'development') { Log.configure({ maskSensitiveData: ['password', 'token'] }); } // Production - comprehensive masking if (process.env.NODE_ENV === 'production') { Log.configure({ maskSensitiveData: [ 'password', 'token', 'secret', 'key', 'api_key', 'auth_token', 'bearer_token', 'connectionstring', 'ssn', 'credit_card' ] }); } ``` ## Best Practices > **Data Masking Best Practices** > - **Start with defaults**: Begin with `['password', 'token']` and add as needed > - **Test thoroughly**: Verify masking works in all environments > - **Consider compliance**: Include patterns required by GDPR, HIPAA, PCI-DSS > - **Review regularly**: Audit your masking patterns periodically ## Next Steps - [User Identification](/platforms/javascript/products/logs/features/user-identification) - Associate logs with specific users - [Global Metadata](/platforms/javascript/products/logs/features/global-metadata) - Add consistent context to all logs - [Basic Logging](/platforms/javascript/products/logs/features/basic-logging) - Learn fundamental logging methods --- # Error Logging ByteHide Logger provides specialized methods for handling errors: `error` and `critical`. Both methods can accept an `Error` parameter to automatically capture exception details like stack traces and error types. {% .lead %} ## Error Logging Methods ### Error Method Use `error` for exceptions that affect functionality but allow the application to continue: ```javascript // Method signature Log.error(message, options, error) // Basic error logging try { await processOrder(orderId); } catch (error) { Log.error('Failed to process order', {}, error); } // Error with context try { await processPayment(paymentRequest); } catch (error) { Log.error('Payment processing failed', { context: { transactionId: paymentRequest.transactionId, amount: paymentRequest.amount }, tags: ['payment', 'error'] }, error); } ``` ### Critical Method Use `critical` for critical errors that may cause application termination: ```javascript // Method signature Log.critical(message, options, error) // Critical system failures try { await initializeDatabase(); } catch (error) { Log.critical('Database initialization failed - application cannot continue', { context: { connectionString: '***' } }, error); process.exit(1); } // Critical configuration errors try { await loadConfiguration(); } catch (error) { Log.critical('Invalid configuration detected - shutting down', { tags: ['config', 'critical'] }, error); throw error; } ``` ## Error Information Captured When you pass an `Error` to `error` or `critical` methods, ByteHide Logger automatically captures: - **Error Name**: The error's name/type - **Error Message**: The error's message - **Stack Trace**: Complete stack trace for debugging - **Error Properties**: Additional properties attached to the error ```javascript try { const result = await callExternalApi(); } catch (error) { // All error details are automatically captured Log.error('External API call failed', { context: { endpoint: '/api/payments' } }, error); // Logged information includes: // - Error name: TypeError, ReferenceError, etc. // - Message: "Network request failed" // - Stack trace: Full call stack // - Additional error properties } ``` ## Common Error Scenarios ### API Calls ```javascript try { const response = await fetch('/api/orders', { method: 'POST', body: JSON.stringify(orderData) }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } return await response.json(); } catch (error) { Log.error('API request failed', { context: { endpoint: '/api/orders', method: 'POST', status: error.status }, tags: ['api', 'error'] }, error); throw error; } ``` ### Database Operations ```javascript try { const orders = await database.query('SELECT * FROM orders WHERE customer_id = ?', [customerId]); return orders; } catch (error) { Log.error('Database query failed', { context: { customerId, query: 'getOrdersByCustomer' }, metadata: { timeout: 30000 }, tags: ['database', 'error'] }, error); throw error; } ``` ### File Operations ```javascript try { const content = await fs.readFile(filePath, 'utf8'); return JSON.parse(content); } catch (error) { if (error.code === 'ENOENT') { Log.error('Configuration file not found', { context: { filePath }, tags: ['config', 'file'] }, error); } else if (error instanceof SyntaxError) { Log.critical('Invalid JSON configuration', { context: { filePath }, tags: ['config', 'json', 'critical'] }, error); } else { Log.error('File operation failed', { context: { filePath, operation: 'read' } }, error); } throw error; } ``` ### Business Logic Errors ```javascript class OrderService { async validateAndProcessOrder(order) { try { await this.validateOrder(order); return await this.processOrder(order); } catch (error) { if (error instanceof ValidationError) { Log.error('Order validation failed', { context: { orderId: order.id, validationErrors: error.errors }, tags: ['validation', 'orders'] }, error); } else if (error instanceof InsufficientStockError) { Log.error('Insufficient stock for order', { context: { orderId: order.id, productId: error.productId, requestedQuantity: error.requestedQuantity, availableStock: error.availableStock }, tags: ['inventory', 'orders'] }, error); } else { Log.critical('Unexpected error in order processing', { context: { orderId: order.id }, tags: ['orders', 'critical'] }, error); } throw error; } } } ``` ## Error Handling Patterns ### Catch and Log ```javascript async function getOrder(orderId) { try { return await orderRepository.findById(orderId); } catch (error) { Log.error('Failed to retrieve order', { context: { orderId }, tags: ['repository', 'orders'] }, error); throw error; // Re-throw to preserve original error } } ``` ### Catch, Log, and Transform ```javascript async function getOrderSafely(orderId) { try { const order = await orderRepository.findById(orderId); return { success: true, data: order }; } catch (error) { if (error.name === 'NotFoundError') { Log.error('Order not found', { context: { orderId } }, error); return { success: false, error: 'Order not found' }; } else { Log.critical('Unexpected error retrieving order', { context: { orderId } }, error); return { success: false, error: 'Internal server error' }; } } } ``` ### Critical Failure Handling ```javascript async function startApplication() { try { await initializeDatabase(); await loadConfiguration(); await startServices(); } catch (error) { if (error.name === 'DatabaseConnectionError') { Log.critical('Database initialization failed', { tags: ['startup', 'database'] }, error); process.exit(1); } else if (error.name === 'ConfigurationError') { Log.critical('Configuration loading failed', { tags: ['startup', 'config'] }, error); process.exit(1); } else { Log.critical('Application startup failed', { tags: ['startup', 'critical'] }, error); process.exit(1); } } } ``` ## Express.js Integration ### Route Error Handling ```javascript app.get('/api/orders/:id', async (req, res) => { try { const order = await orderService.getOrder(req.params.id); res.json(order); } catch (error) { if (error.name === 'NotFoundError') { Log.error('Order not found', { context: { orderId: req.params.id, requestId: req.id }, tags: ['api', 'orders'] }, error); res.status(404).json({ error: 'Order not found' }); } else { Log.critical('Unexpected error in getOrder endpoint', { context: { orderId: req.params.id, requestId: req.id }, tags: ['api', 'orders', 'critical'] }, error); res.status(500).json({ error: 'Internal server error' }); } } }); ``` ### Global Error Handler ```javascript app.use((error, req, res, next) => { const requestInfo = { requestId: req.id, path: req.path, method: req.method, query: req.query }; if (error.status && error.status < 500) { Log.error('Client error', { context: requestInfo, metadata: { statusCode: error.status }, tags: ['http', 'client-error'] }, error); res.status(error.status); } else { Log.critical('Server error', { context: requestInfo, tags: ['http', 'server-error'] }, error); res.status(500); } res.json({ error: 'An error occurred' }); }); ``` ## Best Practices > **Error Logging Best Practices** > - **Always pass the Error**: Include the `Error` parameter to capture full details > - **Add relevant context**: Include business context like IDs, operation names, and state > - **Use appropriate levels**: `error` for recoverable issues, `critical` for system failures > - **Don't swallow errors**: Log and re-throw or transform appropriately > - **Include correlation IDs**: Use correlation IDs for request tracking > - **Avoid sensitive data**: Don't log passwords, tokens, or PII in error context ## Common Mistakes to Avoid ```javascript // ❌ Don't lose error details try { await processOrder(order); } catch (error) { Log.error('Something went wrong'); // Missing error parameter throw new Error('Operation failed'); // Lost original error } // ✅ Capture full error details try { await processOrder(order); } catch (error) { Log.error('Order processing failed', { context: { orderId: order.id } }, error); throw error; // Preserve original error } // ❌ Don't log and swallow try { await processOrder(order); } catch (error) { Log.error('Error occurred', {}, error); return null; // Swallowing error } // ✅ Log and handle appropriately try { await processOrder(order); } catch (error) { Log.error('Error occurred', {}, error); throw error; // Or return appropriate error response } ``` ## Next Steps - [Basic Logging](/platforms/javascript/products/logs/features/basic-logging) - Learn the fundamental logging methods - [Correlation IDs](/platforms/javascript/products/logs/features/correlation-ids) - Track errors across service calls - [Data Masking](/platforms/javascript/products/logs/features/data-masking) - Protect sensitive data in error logs - [Tags](/platforms/javascript/products/logs/features/tags) - Organize error logs with tags --- # Global Metadata Global metadata allows you to add consistent metadata that will be included with all subsequent logs automatically. This is useful for application-wide context like environment, version, or deployment information. {% .lead %} ## Adding Global Metadata Use `Log.addMetaContext()` to add metadata that will be included with all subsequent logs: ```javascript // Add global metadata Log.addMetaContext('appVersion', '1.2.3'); Log.addMetaContext('environment', 'production'); Log.addMetaContext('server', process.env.HOSTNAME); // All subsequent logs will include this metadata Log.info('Application started'); // Includes appVersion, environment, server Log.error('Database connection failed', {}, error); // Also includes the metadata ``` ## Common Global Metadata ### Application Information ```javascript // Basic application context Log.addMetaContext('applicationName', 'OrderService'); Log.addMetaContext('version', process.env.npm_package_version); Log.addMetaContext('environment', process.env.NODE_ENV); Log.addMetaContext('nodeVersion', process.version); ``` ### Deployment Context ```javascript // Cloud deployment context Log.addMetaContext('deploymentId', process.env.DEPLOYMENT_ID); Log.addMetaContext('region', process.env.AWS_REGION); Log.addMetaContext('instanceId', process.env.EC2_INSTANCE_ID); Log.addMetaContext('containerId', process.env.HOSTNAME); ``` ## Complex Objects and Arrays You can add any type of data, including complex objects and arrays: ```javascript // Simple values Log.addMetaContext('buildNumber', 12345); Log.addMetaContext('isDebugMode', process.env.NODE_ENV === 'development'); // Complex objects const deploymentInfo = { version: '1.2.3', branch: 'main', commitHash: 'abc123def', deployedAt: new Date().toISOString() }; Log.addMetaContext('deployment', deploymentInfo); // Arrays Log.addMetaContext('features', ['featureA', 'featureB', 'featureC']); ``` ## Express.js Integration Set global metadata during application startup: ```javascript import express from 'express'; import { Log } from '@bytehide/logger'; const app = express(); // Set application-wide metadata Log.addMetaContext('applicationName', 'OrderService'); Log.addMetaContext('environment', process.env.NODE_ENV); Log.addMetaContext('version', process.env.npm_package_version); Log.addMetaContext('startTime', new Date().toISOString()); app.listen(3000, () => { Log.info('Server started', { context: { port: 3000 } }); }); ``` ## Configuration-Based Metadata Load metadata from configuration files: ```javascript // config.json { "logging": { "globalMetadata": { "applicationName": "OrderService", "environment": "production", "region": "us-east-1", "version": "2.1.0" } } } ``` ```javascript import config from './config.json'; // Load global metadata from configuration const globalMetadata = config.logging.globalMetadata; for (const [key, value] of Object.entries(globalMetadata)) { Log.addMetaContext(key, value); } ``` ## Environment-Based Metadata ```javascript // Load metadata based on environment const environment = process.env.NODE_ENV || 'development'; // Common metadata Log.addMetaContext('environment', environment); Log.addMetaContext('nodeVersion', process.version); Log.addMetaContext('platform', process.platform); // Environment-specific metadata if (environment === 'production') { Log.addMetaContext('cluster', process.env.CLUSTER_ID); Log.addMetaContext('region', process.env.AWS_REGION); } else if (environment === 'development') { Log.addMetaContext('developer', process.env.USER); Log.addMetaContext('debugMode', true); } ``` ## Package.json Integration ```javascript import packageJson from './package.json'; // Add package information as global metadata Log.addMetaContext('packageName', packageJson.name); Log.addMetaContext('version', packageJson.version); Log.addMetaContext('description', packageJson.description); Log.addMetaContext('author', packageJson.author); ``` ## Docker Integration ```javascript // Add Docker/container information Log.addMetaContext('containerId', process.env.HOSTNAME); Log.addMetaContext('imageTag', process.env.IMAGE_TAG); Log.addMetaContext('buildDate', process.env.BUILD_DATE); // Kubernetes information if (process.env.KUBERNETES_SERVICE_HOST) { Log.addMetaContext('k8sNamespace', process.env.NAMESPACE); Log.addMetaContext('k8sPodName', process.env.POD_NAME); Log.addMetaContext('k8sServiceName', process.env.SERVICE_NAME); } ``` ## Performance Metadata ```javascript // System performance information const getSystemInfo = () => ({ memoryUsage: process.memoryUsage(), uptime: process.uptime(), cpuUsage: process.cpuUsage() }); // Add initial system info Log.addMetaContext('systemInfo', getSystemInfo()); // Update periodically (optional) setInterval(() => { Log.addMetaContext('systemInfo', getSystemInfo()); }, 60000); // Update every minute ``` ## Best Practices > **Best Practices** > - Set global metadata during application startup, not runtime > - Use consistent naming conventions (camelCase recommended for JavaScript) > - Include useful debugging context like version, environment, deployment info > - Avoid sensitive data like passwords or tokens > - Keep metadata relevant and focused ## Common Patterns ### Startup Configuration ```javascript // startup.js function configureGlobalMetadata() { // Application metadata Log.addMetaContext('applicationName', 'MyApp'); Log.addMetaContext('version', process.env.npm_package_version); Log.addMetaContext('environment', process.env.NODE_ENV); // Runtime metadata Log.addMetaContext('nodeVersion', process.version); Log.addMetaContext('platform', process.platform); Log.addMetaContext('startTime', new Date().toISOString()); // Deployment metadata if (process.env.DEPLOYMENT_ID) { Log.addMetaContext('deploymentId', process.env.DEPLOYMENT_ID); } if (process.env.BUILD_NUMBER) { Log.addMetaContext('buildNumber', parseInt(process.env.BUILD_NUMBER)); } Log.info('Global metadata configured'); } // Call during app initialization configureGlobalMetadata(); ``` ### Microservice Metadata ```javascript // microservice-config.js export function configureServiceMetadata(serviceName) { Log.addMetaContext('serviceName', serviceName); Log.addMetaContext('serviceVersion', process.env.SERVICE_VERSION); Log.addMetaContext('serviceId', process.env.SERVICE_ID || generateServiceId()); // Service discovery metadata Log.addMetaContext('serviceRegistry', process.env.SERVICE_REGISTRY); Log.addMetaContext('loadBalancer', process.env.LOAD_BALANCER); // Health check metadata Log.addMetaContext('healthCheckEndpoint', '/health'); Log.addMetaContext('metricsEndpoint', '/metrics'); } // Usage configureServiceMetadata('order-service'); ``` ### Cloud Provider Metadata ```javascript // AWS metadata if (process.env.AWS_REGION) { Log.addMetaContext('cloud', 'aws'); Log.addMetaContext('region', process.env.AWS_REGION); Log.addMetaContext('availabilityZone', process.env.AWS_AVAILABILITY_ZONE); Log.addMetaContext('instanceType', process.env.AWS_INSTANCE_TYPE); } // Google Cloud metadata if (process.env.GOOGLE_CLOUD_PROJECT) { Log.addMetaContext('cloud', 'gcp'); Log.addMetaContext('project', process.env.GOOGLE_CLOUD_PROJECT); Log.addMetaContext('zone', process.env.GOOGLE_CLOUD_ZONE); } // Azure metadata if (process.env.AZURE_RESOURCE_GROUP) { Log.addMetaContext('cloud', 'azure'); Log.addMetaContext('resourceGroup', process.env.AZURE_RESOURCE_GROUP); Log.addMetaContext('subscription', process.env.AZURE_SUBSCRIPTION_ID); } ``` ## Dynamic Metadata Updates ```javascript // Update metadata based on application state class MetadataManager { static updateConnectionStatus(status) { Log.addMetaContext('dbConnectionStatus', status); } static updateActiveUsers(count) { Log.addMetaContext('activeUsers', count); } static updateFeatureFlags(flags) { Log.addMetaContext('featureFlags', flags); } } // Usage MetadataManager.updateConnectionStatus('connected'); MetadataManager.updateActiveUsers(150); MetadataManager.updateFeatureFlags({ newCheckout: true, betaFeature: false }); ``` ## Next Steps - [Tags](/platforms/javascript/products/logs/features/tags) - Organize and categorize logs - [Metadata & Context](/platforms/javascript/products/logs/features/metadata-context) - Add context to individual logs - [User Identification](/platforms/javascript/products/logs/features/user-identification) - Associate logs with users - [Basic Logging](/platforms/javascript/products/logs/features/basic-logging) - Learn fundamental logging methods --- # Metadata & Context Metadata and context allow you to add structured information to your logs, making them more informative and easier to analyze. {% .lead %} ## Context Property Use the `context` property to add structured data to your logs: ```javascript // Basic context usage Log.info('User login successful', { context: { userId: 123, username: 'john.doe', ipAddress: '192.168.1.1' } }); // Context with error logging Log.error('Database connection failed', { context: { database: 'users', host: 'localhost', port: 5432, retryCount: 3 } }, error); ``` ## Metadata Property Use the `metadata` property for additional structured information: ```javascript // Metadata with performance data Log.info('API request completed', { metadata: { responseTime: 234, statusCode: 200, cacheHit: true } }); // Metadata with business context Log.warn('Order processing delayed', { metadata: { orderId: 'ORD-123', priority: 'high', estimatedDelay: '5 minutes' } }); ``` ## Combining Context and Metadata ```javascript // Using both context and metadata Log.info('Payment processed', { context: { customerId: 456, orderId: 'ORD-789' }, metadata: { amount: 99.99, currency: 'USD', paymentMethod: 'credit_card', processingTime: 1.2 } }); ``` ## Express.js Integration ```javascript app.use((req, res, next) => { // Add request context to all logs req.logContext = { requestId: req.id, method: req.method, url: req.url, userAgent: req.get('User-Agent') }; next(); }); app.post('/api/users', async (req, res) => { Log.info('User creation started', { context: req.logContext, metadata: { email: req.body.email, role: req.body.role } }); try { const user = await userService.create(req.body); Log.info('User created successfully', { context: req.logContext, metadata: { userId: user.id, email: user.email } }); res.json(user); } catch (error) { Log.error('User creation failed', { context: req.logContext, metadata: { email: req.body.email, validationErrors: error.validationErrors } }, error); res.status(400).json({ error: 'Failed to create user' }); } }); ``` ## Common Usage Patterns ### Performance Monitoring ```javascript const startTime = Date.now(); // ... operation ... Log.info('Operation completed', { metadata: { duration: Date.now() - startTime, operationType: 'database_query', recordsProcessed: 150 } }); ``` ### Error Context ```javascript try { await processPayment(paymentData); } catch (error) { Log.error('Payment processing failed', { context: { customerId: paymentData.customerId, orderId: paymentData.orderId }, metadata: { amount: paymentData.amount, paymentMethod: paymentData.method, attemptNumber: 2 } }, error); } ``` ### Business Events ```javascript Log.info('Product purchased', { context: { customerId: customer.id, sessionId: session.id }, metadata: { productId: product.id, price: product.price, category: product.category, discountApplied: discount.amount } }); ``` ## Best Practices > **Best Practices** > - **Use context for request/operation data**: User IDs, request IDs, session data > - **Use metadata for business/technical data**: Performance metrics, business values > - **Keep objects flat**: Avoid deeply nested structures > - **Use consistent naming**: Stick to camelCase or snake_case throughout your app > - **Include relevant data only**: Don't log everything, focus on what's useful for debugging ## Next Steps - [Global Metadata](/platforms/javascript/products/logs/features/global-metadata) - Add consistent context to all logs - [Tags](/platforms/javascript/products/logs/features/tags) - Categorize and organize logs - [Correlation IDs](/platforms/javascript/products/logs/features/correlation-ids) - Track requests across services --- # Tags Tags allow you to categorize and organize your logs for easier filtering and analysis. Use tags to group related logs by feature, module, or any custom criteria. {% .lead %} ## Adding Tags Use the `tags` property in the options object: ```javascript // Add multiple tags Log.info('Database query completed', { tags: ['performance', 'database'] }); // Single tag Log.warn('Failed login attempt', { tags: ['authentication'] }); // Tags with context Log.error('External API call failed', { tags: ['api', 'external'], context: { endpoint: '/payments' } }, error); ``` ## Common Tag Categories ### Feature-Based Tags ```javascript // Authentication feature Log.info('Login attempt successful', { tags: ['authentication', 'security'] }); // Payment processing Log.error('Payment gateway timeout', { tags: ['payment', 'transaction'] }); // Database operations Log.warn('Slow query detected', { tags: ['database', 'performance'] }); ``` ### Component-Based Tags ```javascript // Cache operations Log.info('Cache entry expired', { tags: ['cache', 'redis'] }); // External APIs Log.error('External service unavailable', { tags: ['api', 'external', 'payment-gateway'] }); // Background jobs Log.info('Email processing completed', { tags: ['background-job', 'email'] }); ``` ## Express.js Integration ```javascript app.post('/api/orders', async (req, res) => { Log.info('Order creation started', { tags: ['api', 'orders', 'create'], context: { customerId: req.body.customerId } }); try { const order = await orderService.create(req.body); Log.info('Order created successfully', { tags: ['api', 'orders', 'success'], context: { orderId: order.id } }); res.json(order); } catch (error) { Log.error('Order creation failed', { tags: ['api', 'orders', 'error'] }, error); res.status(500).json({ error: 'Failed to create order' }); } }); ``` ## Tag Conventions ### Naming Standards ```javascript // ✅ Good - Lowercase with hyphens Log.info('Profile updated successfully', { tags: ['user-management', 'profile'] }); // ✅ Good - Simple and clear Log.warn('Slow query detected', { tags: ['database', 'performance'] }); // ❌ Avoid - Inconsistent casing and spaces Log.info('Profile updated', { tags: ['UserManagement', 'PROFILE'] }); ``` ## Filtering and Analysis Tags make it easy to filter and analyze logs: ```javascript // All payment-related logs can be filtered by "payment" tag Log.info('Payment processing started', { tags: ['payment', 'gateway'] }); Log.warn('Payment retry attempt', { tags: ['payment', 'retry'] }); Log.error('Payment processing failed', { tags: ['payment', 'error'] }); ``` ## Best Practices > **Best Practices** > - Use lowercase with hyphens for consistency (e.g., "user-management") > - Keep tags short and meaningful > - Use multiple tags for better filtering capabilities > - Document your tagging strategy for the team > - Combine tags with metadata and context for comprehensive logging ## Next Steps - [Metadata & Context](/platforms/javascript/products/logs/features/metadata-context) - Add context to individual logs - [Global Metadata](/platforms/javascript/products/logs/features/global-metadata) - Add consistent context to all logs - [User Identification](/platforms/javascript/products/logs/features/user-identification) - Associate logs with users --- # User Identification User identification allows you to associate logs with specific users, making it easier to track user actions, debug user-specific issues, and maintain audit trails. {% .lead %} ## Basic Usage Use `Log.identify()` to associate logs with a specific user: ```javascript // Identify user with id, email, and token Log.identify('user_12345', 'john.doe@company.com', 'auth_token_abc123'); // All subsequent logs will be associated with this user Log.info('User performed action'); Log.error('User encountered error', { context: { action: 'checkout' } }); // Logout to make subsequent logs anonymous Log.logout(); ``` ## Method Signature ```javascript Log.identify(id, email?, token?) ``` ### Parameters - `id` (string, required): Unique user identifier - `email` (string, optional): User's email address - `token` (string, optional): Authentication token ## User Identification Examples ### Basic Identification ```javascript // Minimal identification with just ID Log.identify('user_12345'); // With email Log.identify('user_12345', 'john.doe@company.com'); // Complete identification Log.identify('user_12345', 'john.doe@company.com', 'jwt_token_here'); ``` ### Express.js Integration ```javascript // Login endpoint app.post('/api/login', async (req, res) => { try { const { email, password } = req.body; const user = await authService.authenticate(email, password); // Identify user in logs Log.identify(user.id, user.email, user.token); Log.info('User login successful', { context: { userId: user.id, loginMethod: 'email' }, tags: ['authentication', 'login'] }); res.json({ token: user.token }); } catch (error) { Log.error('Login failed', { context: { email: req.body.email }, tags: ['authentication', 'error'] }, error); res.status(401).json({ error: 'Invalid credentials' }); } }); // Logout endpoint app.post('/api/logout', (req, res) => { Log.info('User logout', { tags: ['authentication', 'logout'] }); Log.logout(); res.json({ message: 'Logged out successfully' }); }); ``` ### Middleware Integration ```javascript // Authentication middleware const authMiddleware = async (req, res, next) => { try { const token = req.headers.authorization?.replace('Bearer ', ''); if (!token) { return res.status(401).json({ error: 'No token provided' }); } const user = await authService.verifyToken(token); // Identify user for all subsequent logs in this request Log.identify(user.id, user.email, token); req.user = user; next(); } catch (error) { Log.error('Authentication failed', { context: { token: token?.substring(0, 10) + '...' }, tags: ['authentication', 'middleware'] }, error); res.status(401).json({ error: 'Invalid token' }); } }; // Protected route app.get('/api/profile', authMiddleware, (req, res) => { Log.info('Profile accessed', { context: { userId: req.user.id }, tags: ['profile', 'access'] }); res.json(req.user); }); ``` ## User Context in Logs Once a user is identified, all subsequent logs will include user information: ```javascript // After identification Log.identify('user_123', 'john@example.com'); // These logs will automatically include user context Log.info('Order created', { context: { orderId: 'order_456' }, tags: ['orders'] }); Log.error('Payment failed', { context: { paymentId: 'pay_789' }, tags: ['payment', 'error'] }); ``` ## Logout Functionality Use `Log.logout()` to make subsequent logs anonymous: ```javascript // User logs out Log.logout(); // Subsequent logs will be anonymous Log.info('Anonymous action performed'); ``` ## Session Management ### Session-based Identification ```javascript // Express session example app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: false })); app.post('/api/login', async (req, res) => { const user = await authService.authenticate(req.body.email, req.body.password); // Store in session req.session.userId = user.id; req.session.userEmail = user.email; // Identify in logs Log.identify(user.id, user.email); Log.info('User session created', { context: { sessionId: req.session.id }, tags: ['session', 'login'] }); res.json({ success: true }); }); // Middleware to restore user identification from session app.use((req, res, next) => { if (req.session.userId) { Log.identify(req.session.userId, req.session.userEmail); } next(); }); ``` ### JWT Token Integration ```javascript import jwt from 'jsonwebtoken'; // JWT middleware const jwtMiddleware = (req, res, next) => { const token = req.headers.authorization?.replace('Bearer ', ''); if (token) { try { const decoded = jwt.verify(token, process.env.JWT_SECRET); // Identify user from JWT payload Log.identify(decoded.userId, decoded.email, token); req.user = decoded; } catch (error) { Log.error('JWT verification failed', { context: { tokenPrefix: token.substring(0, 10) }, tags: ['jwt', 'authentication'] }, error); } } next(); }; ``` ## Best Practices > **User Identification Best Practices** > - **Set user context early**: Configure user identification as soon as user is authenticated > - **Include relevant information**: Add email and token when available > - **Clear on logout**: Always call `Log.logout()` when user logs out > - **Use consistent user IDs**: Maintain the same user ID format across your application > - **Consider privacy**: Be mindful of PII in user identification data ## Common Patterns ### Single Page Applications ```javascript // React/Vue.js example class AuthService { async login(email, password) { try { const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }); const data = await response.json(); if (data.success) { // Store token and identify user localStorage.setItem('token', data.token); Log.identify(data.user.id, data.user.email, data.token); Log.info('User authenticated', { context: { loginType: 'spa' }, tags: ['authentication', 'spa'] }); } return data; } catch (error) { Log.error('Login request failed', { context: { email }, tags: ['authentication', 'spa', 'error'] }, error); throw error; } } logout() { localStorage.removeItem('token'); Log.logout(); Log.info('User logged out', { tags: ['authentication', 'logout', 'spa'] }); } // Restore user identification on app start restoreSession() { const token = localStorage.getItem('token'); if (token) { try { const payload = jwt.decode(token); if (payload && payload.exp > Date.now() / 1000) { Log.identify(payload.userId, payload.email, token); Log.info('Session restored', { context: { userId: payload.userId }, tags: ['authentication', 'session'] }); } } catch (error) { Log.error('Session restoration failed', {}, error); this.logout(); } } } } ``` ### Microservices Communication ```javascript // Service-to-service calls with user context class ApiClient { constructor() { this.baseURL = process.env.API_BASE_URL; } async makeRequest(endpoint, options = {}) { // Get current user context if available const userContext = this.getCurrentUserContext(); const headers = { 'Content-Type': 'application/json', ...options.headers }; // Pass user context in headers for service-to-service calls if (userContext) { headers['X-User-ID'] = userContext.id; headers['X-User-Email'] = userContext.email; } try { const response = await fetch(`${this.baseURL}${endpoint}`, { ...options, headers }); Log.info('API request completed', { context: { endpoint, status: response.status, userId: userContext?.id }, tags: ['api', 'microservice'] }); return response; } catch (error) { Log.error('API request failed', { context: { endpoint, userId: userContext?.id }, tags: ['api', 'microservice', 'error'] }, error); throw error; } } } ``` ## Next Steps - [Correlation IDs](/platforms/javascript/products/logs/features/correlation-ids) - Track user actions across services - [Global Metadata](/platforms/javascript/products/logs/features/global-metadata) - Add consistent context to all logs - [Data Masking](/platforms/javascript/products/logs/features/data-masking) - Protect sensitive user information - [Tags](/platforms/javascript/products/logs/features/tags) - Organize user-related logs --- # Angular ByteHide Logger integrates with Angular applications through services and provides comprehensive logging for components and services. {% .lead %} ## Installation ```bash npm install @bytehide/logger @angular/core ``` ## Logger Service ```typescript // services/logger.service.ts import { Injectable } from '@angular/core'; import { Log } from '@bytehide/logger'; @Injectable({ providedIn: 'root' }) export class LoggerService { constructor() { Log.configure({ projectToken: environment.byteHideToken, logLevel: 'info' }); Log.info('Angular logger service initialized'); } info(message: string, options?: any) { Log.info(message, options); } warn(message: string, options?: any) { Log.warn(message, options); } error(message: string, options?: any, error?: Error) { Log.error(message, options, error); } identify(userId: string, email?: string) { Log.identify(userId, email); } } ``` ## Environment Configuration ```typescript // environments/environment.ts export const environment = { production: false, byteHideToken: 'your-project-token' }; ``` ## Component Usage ```typescript // components/user.component.ts import { Component, OnInit, OnDestroy } from '@angular/core'; import { LoggerService } from '../services/logger.service'; @Component({ selector: 'app-user', templateUrl: './user.component.html' }) export class UserComponent implements OnInit, OnDestroy { constructor(private logger: LoggerService) {} ngOnInit() { this.logger.info('UserComponent initialized'); } ngOnDestroy() { this.logger.info('UserComponent destroyed'); } onButtonClick() { this.logger.info('Button clicked', { context: { component: 'UserComponent', action: 'click' } }); } } ``` ## HTTP Interceptor ```typescript // interceptors/logging.interceptor.ts import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http'; import { LoggerService } from '../services/logger.service'; @Injectable() export class LoggingInterceptor implements HttpInterceptor { constructor(private logger: LoggerService) {} intercept(req: HttpRequest, next: HttpHandler) { this.logger.info('HTTP request started', { context: { method: req.method, url: req.url } }); return next.handle(req).pipe( tap( response => { this.logger.info('HTTP request completed', { context: { method: req.method, url: req.url, status: response.status } }); }, error => { this.logger.error('HTTP request failed', { context: { method: req.method, url: req.url } }, error); } ) ); } } ``` ## Error Handler ```typescript // error-handler.ts import { ErrorHandler, Injectable } from '@angular/core'; import { LoggerService } from './services/logger.service'; @Injectable() export class GlobalErrorHandler implements ErrorHandler { constructor(private logger: LoggerService) {} handleError(error: any): void { this.logger.error('Global error handler caught error', { context: { source: 'GlobalErrorHandler' } }, error); } } ``` ## App Module Configuration ```typescript // app.module.ts import { NgModule, ErrorHandler } from '@angular/core'; import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { LoggerService } from './services/logger.service'; import { LoggingInterceptor } from './interceptors/logging.interceptor'; import { GlobalErrorHandler } from './error-handler'; @NgModule({ providers: [ LoggerService, { provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true }, { provide: ErrorHandler, useClass: GlobalErrorHandler } ] }) export class AppModule {} ``` ## Route Logging ```typescript // app-routing.module.ts import { Router, NavigationEnd } from '@angular/router'; import { LoggerService } from './services/logger.service'; @Injectable() export class AppRoutingModule { constructor( private router: Router, private logger: LoggerService ) { this.router.events.pipe( filter(event => event instanceof NavigationEnd) ).subscribe((event: NavigationEnd) => { this.logger.info('Route navigation completed', { context: { url: event.url } }); }); } } ``` ## Best Practices > **Angular Best Practices** > - Use dependency injection for logger service > - Implement HTTP interceptors for API request logging > - Set up global error handlers for unhandled exceptions > - Log component lifecycle events and user interactions --- # Express.js ByteHide Logger integrates seamlessly with Express.js applications through middleware and route-level logging. {% .lead %} ## Installation ```bash npm install @bytehide/logger express ``` ## Basic Setup ```javascript const express = require('express'); const { Log } = require('@bytehide/logger'); const app = express(); // Configure logger Log.configure({ projectToken: process.env.BYTEHIDE_PROJECT_TOKEN, logLevel: 'info' }); app.listen(3000, () => { Log.info('Express server started', { context: { port: 3000 } }); }); ``` ## Request Logging Middleware ```javascript // Log all incoming requests app.use((req, res, next) => { Log.info('Request received', { context: { method: req.method, url: req.url, userAgent: req.get('User-Agent'), ip: req.ip } }); next(); }); ``` ## Route-Level Logging ```javascript app.get('/api/users', async (req, res) => { Log.info('Fetching users'); try { const users = await getUsersFromDatabase(); Log.info('Users fetched successfully', { context: { count: users.length } }); res.json(users); } catch (error) { Log.error('Failed to fetch users', { context: { endpoint: '/api/users' } }, error); res.status(500).json({ error: 'Internal server error' }); } }); ``` ## Error Handling Middleware ```javascript // Global error handler app.use((error, req, res, next) => { Log.error('Unhandled error', { context: { method: req.method, url: req.url, statusCode: res.statusCode } }, error); res.status(500).json({ error: 'Internal server error' }); }); ``` ## User Identification ```javascript // Middleware to identify users app.use((req, res, next) => { if (req.user) { Log.identify(req.user.id, req.user.email); } next(); }); ``` ## Best Practices > **Express.js Best Practices** > - Use middleware for consistent request logging > - Log both successful operations and errors > - Include relevant request context in logs > - Use global error handlers for unhandled exceptions --- # Fastify ByteHide Logger integrates with Fastify applications through plugins and request/response hooks for comprehensive logging. {% .lead %} ## Installation ```bash npm install @bytehide/logger fastify ``` ## Basic Setup ```javascript const fastify = require('fastify')({ logger: false }); const { Log } = require('@bytehide/logger'); // Configure logger Log.configure({ projectToken: process.env.BYTEHIDE_PROJECT_TOKEN, logLevel: 'info' }); // Start server const start = async () => { try { await fastify.listen({ port: 3000 }); Log.info('Fastify server started', { context: { port: 3000 } }); } catch (error) { Log.error('Failed to start server', {}, error); process.exit(1); } }; start(); ``` ## Logger Plugin ```javascript // plugins/logger.js const { Log } = require('@bytehide/logger'); async function loggerPlugin(fastify, options) { Log.configure({ projectToken: options.projectToken, logLevel: options.logLevel || 'info' }); // Add logger to fastify instance fastify.decorate('log', Log); Log.info('ByteHide logger plugin registered'); } module.exports = loggerPlugin; ``` ## Register Plugin ```javascript const fastify = require('fastify')(); // Register logger plugin fastify.register(require('./plugins/logger'), { projectToken: process.env.BYTEHIDE_PROJECT_TOKEN, logLevel: 'info' }); ``` ## Request Logging Hooks ```javascript // Log all requests fastify.addHook('onRequest', async (request, reply) => { fastify.log.info('Request received', { context: { method: request.method, url: request.url, userAgent: request.headers['user-agent'], ip: request.ip } }); }); // Log responses fastify.addHook('onSend', async (request, reply, payload) => { fastify.log.info('Response sent', { context: { method: request.method, url: request.url, statusCode: reply.statusCode } }); }); ``` ## Route Handlers ```javascript // GET route with logging fastify.get('/api/users', async (request, reply) => { fastify.log.info('Fetching users'); try { const users = await getUsersFromDatabase(); fastify.log.info('Users fetched successfully', { context: { count: users.length } }); return users; } catch (error) { fastify.log.error('Failed to fetch users', { context: { endpoint: '/api/users' } }, error); reply.status(500).send({ error: 'Internal server error' }); } }); // POST route with logging fastify.post('/api/users', async (request, reply) => { fastify.log.info('Creating user', { context: { email: request.body.email } }); try { const user = await createUser(request.body); fastify.log.info('User created successfully', { context: { userId: user.id } }); return user; } catch (error) { fastify.log.error('Failed to create user', { context: { email: request.body.email } }, error); reply.status(400).send({ error: 'Failed to create user' }); } }); ``` ## Error Handling ```javascript // Global error handler fastify.setErrorHandler((error, request, reply) => { fastify.log.error('Unhandled error', { context: { method: request.method, url: request.url, statusCode: reply.statusCode } }, error); reply.status(500).send({ error: 'Internal server error' }); }); ``` ## User Identification ```javascript // Authentication hook fastify.addHook('preHandler', async (request, reply) => { if (request.user) { fastify.log.identify(request.user.id, request.user.email); } }); ``` ## Best Practices > **Fastify Best Practices** > - Use plugins for logger configuration and registration > - Implement request/response hooks for automatic logging > - Log both successful operations and errors > - Use global error handlers for unhandled exceptions --- # Next.js ByteHide Logger works in Next.js applications on both client and server sides, providing comprehensive logging for full-stack applications. {% .lead %} ## Installation ```bash npm install @bytehide/logger next ``` ## Environment Configuration ```bash # .env.local BYTEHIDE_PROJECT_TOKEN=your-project-token NEXT_PUBLIC_BYTEHIDE_TOKEN=your-project-token ``` ## Client-Side Setup ```jsx // pages/_app.js import { Log } from '@bytehide/logger'; import { useEffect } from 'react'; function MyApp({ Component, pageProps }) { useEffect(() => { Log.configure({ projectToken: process.env.NEXT_PUBLIC_BYTEHIDE_TOKEN, logLevel: 'info' }); Log.info('Next.js client initialized'); }, []); return ; } export default MyApp; ``` ## Server-Side Setup ```javascript // lib/logger.js import { Log } from '@bytehide/logger'; Log.configure({ projectToken: process.env.BYTEHIDE_PROJECT_TOKEN, logLevel: 'info', fileOutput: { enabled: true, path: './logs' } }); export { Log }; ``` ## API Routes ```javascript // pages/api/users.js import { Log } from '../../lib/logger'; export default async function handler(req, res) { Log.info('API request received', { context: { method: req.method, url: req.url } }); try { const users = await getUsers(); Log.info('Users fetched successfully', { context: { count: users.length } }); res.status(200).json(users); } catch (error) { Log.error('Failed to fetch users', { context: { endpoint: '/api/users' } }, error); res.status(500).json({ error: 'Internal server error' }); } } ``` ## Server-Side Rendering ```jsx // pages/users.js import { Log } from '../lib/logger'; export async function getServerSideProps() { Log.info('Server-side rendering users page'); try { const users = await fetchUsers(); Log.info('Users data fetched for SSR', { context: { count: users.length } }); return { props: { users } }; } catch (error) { Log.error('SSR failed for users page', {}, error); return { props: { users: [] } }; } } ``` ## Page Component Logging ```jsx // pages/profile.js import { Log } from '@bytehide/logger'; import { useEffect } from 'react'; export default function Profile() { useEffect(() => { Log.info('Profile page loaded'); }, []); const handleUpdate = async () => { Log.info('Profile update initiated'); try { await updateProfile(); Log.info('Profile updated successfully'); } catch (error) { Log.error('Profile update failed', {}, error); } }; return ; } ``` ## Middleware ```javascript // middleware.js import { Log } from '@bytehide/logger'; import { NextResponse } from 'next/server'; export function middleware(request) { Log.info('Middleware executed', { context: { pathname: request.nextUrl.pathname, userAgent: request.headers.get('user-agent') } }); return NextResponse.next(); } ``` ## Best Practices > **Next.js Best Practices** > - Use different tokens for client and server if needed > - Configure file logging for server-side only > - Log both SSR/SSG and client-side events > - Use middleware for request-level logging --- # React ByteHide Logger works in React applications for client-side logging, user interaction tracking, and error boundary integration. {% .lead %} ## Installation ```bash npm install @bytehide/logger react ``` ## Basic Setup ```jsx import React, { useEffect } from 'react'; import { Log } from '@bytehide/logger'; function App() { useEffect(() => { Log.configure({ projectToken: process.env.REACT_APP_BYTEHIDE_TOKEN, logLevel: 'info' }); Log.info('React app initialized'); }, []); return
My React App
; } ``` ## Component Logging ```jsx function UserProfile({ userId }) { useEffect(() => { Log.info('UserProfile component mounted', { context: { userId } }); return () => { Log.info('UserProfile component unmounted', { context: { userId } }); }; }, [userId]); const handleClick = () => { Log.info('Profile button clicked', { context: { userId, action: 'view-profile' } }); }; return ( ); } ``` ## Error Boundary ```jsx class ErrorBoundary extends React.Component { componentDidCatch(error, errorInfo) { Log.error('React error boundary caught error', { context: { componentStack: errorInfo.componentStack } }, error); } render() { if (this.state?.hasError) { return

Something went wrong.

; } return this.props.children; } } ``` ## Custom Hook ```jsx import { useEffect } from 'react'; import { Log } from '@bytehide/logger'; function useLogger(componentName) { useEffect(() => { Log.info(`${componentName} mounted`); return () => { Log.info(`${componentName} unmounted`); }; }, [componentName]); const logAction = (action, context = {}) => { Log.info(`${componentName} action: ${action}`, { context: { component: componentName, ...context } }); }; return { logAction }; } // Usage function MyComponent() { const { logAction } = useLogger('MyComponent'); const handleSubmit = () => { logAction('form-submit', { formId: 'contact-form' }); }; return
...
; } ``` ## User Identification ```jsx function AuthProvider({ children }) { const login = async (credentials) => { try { const user = await authenticate(credentials); // Identify user for logging Log.identify(user.id, user.email); Log.info('User logged in successfully', { context: { userId: user.id } }); } catch (error) { Log.error('Login failed', { context: { email: credentials.email } }, error); } }; return {children}; } ``` ## Best Practices > **React Best Practices** > - Initialize logger in the root App component > - Use custom hooks for consistent component logging > - Implement error boundaries for unhandled errors > - Log user interactions and component lifecycle events --- # Vue.js ByteHide Logger integrates with Vue.js applications through plugins and provides component-level logging capabilities. {% .lead %} ## Installation ```bash npm install @bytehide/logger vue ``` ## Plugin Setup ```javascript // plugins/logger.js import { Log } from '@bytehide/logger'; export default { install(app, options) { Log.configure({ projectToken: options.projectToken || process.env.VUE_APP_BYTEHIDE_TOKEN, logLevel: 'info' }); app.config.globalProperties.$log = Log; app.provide('logger', Log); Log.info('Vue.js logger plugin initialized'); } }; ``` ## App Configuration ```javascript // main.js import { createApp } from 'vue'; import App from './App.vue'; import LoggerPlugin from './plugins/logger'; const app = createApp(App); app.use(LoggerPlugin, { projectToken: process.env.VUE_APP_BYTEHIDE_TOKEN }); app.mount('#app'); ``` ## Component Usage ```vue ``` ## Composition API ```vue ``` ## Error Handling ```javascript // main.js app.config.errorHandler = (error, instance, info) => { Log.error('Vue error handler caught error', { context: { componentName: instance?.$options.name, errorInfo: info } }, error); }; ``` ## Router Integration ```javascript // router/index.js import { createRouter } from 'vue-router'; import { Log } from '@bytehide/logger'; const router = createRouter({ // ... routes }); router.beforeEach((to, from, next) => { Log.info('Route navigation', { context: { from: from.path, to: to.path } }); next(); }); export default router; ``` ## Vuex/Pinia Integration ```javascript // store/index.js (Vuex) import { Log } from '@bytehide/logger'; const store = createStore({ mutations: { SET_USER(state, user) { Log.info('User state updated', { context: { userId: user.id } }); state.user = user; } }, actions: { async loginUser({ commit }, credentials) { Log.info('Login attempt started'); try { const user = await login(credentials); commit('SET_USER', user); Log.identify(user.id, user.email); Log.info('Login successful'); return user; } catch (error) { Log.error('Login failed', { context: { email: credentials.email } }, error); throw error; } } } }); ``` ## Best Practices > **Vue.js Best Practices** > - Use plugins for global logger configuration > - Provide logger instance through dependency injection > - Log component lifecycle events and user interactions > - Integrate with Vue Router for navigation logging --- # AI Assistant ByteHide's AI Assistant provides intelligent analysis of your logs, helping you understand issues, identify patterns, and resolve problems faster. {% .lead %} ## AI Explanation Feature Every log entry includes an "AI Explanation" button that provides instant analysis. ![AI Assistant Button](/images/dotnet/logs/dashboard/log-ia-button.png) ## How It Works 1. **Click AI Explanation**: Select the sparkle icon next to any log entry 2. **Instant Analysis**: The AI analyzes the log content, context, and metadata 3. **Detailed Explanation**: Get a comprehensive breakdown of the log entry ![AI Analysis Panel](/images/dotnet/logs/dashboard/log-ia-panel.png) ## AI Analysis Content The AI provides detailed explanations including: ### Log Classification - **Log Type**: Identifies the type of log (warning, error, info, etc.) - **Severity Assessment**: Evaluates the importance and urgency - **Context Understanding**: Interprets the business meaning ### Technical Details - **Source Information**: Where the log was generated - **Method Context**: What method or process created the log - **Application Context**: Relevant application information like version ### Example AI Analysis For a database connection error, the AI provides: ``` The log message 'Database connection timeout after 30 seconds' is a critical error. • It was generated by the ConnectionManager method in /src/Services/DatabaseService.cs at line 145. • The application version is 2.1.4. • The log level is Critical, indicating a system failure that requires immediate attention. • This suggests the database server may be overloaded or experiencing connectivity issues. ``` ## When to Use AI Assistant ### Debugging Errors - Get explanations for complex error messages - Understand exception stack traces - Identify root causes of failures ### Performance Analysis - Interpret performance-related logs - Understand timing and resource usage - Identify bottlenecks and optimization opportunities ### Security Investigations - Analyze security-related warnings - Understand authentication failures - Identify potential security threats ### Business Logic Understanding - Interpret application-specific log messages - Understand workflow and process logs - Correlate business events with technical logs ## AI Analysis Benefits ### Faster Problem Resolution - **Instant Understanding**: No need to research error codes manually - **Context Awareness**: AI understands your application context - **Pattern Recognition**: Identifies common issues and solutions ### Knowledge Transfer - **Team Education**: Helps junior developers understand complex logs - **Documentation**: Creates instant documentation for log entries - **Best Practices**: Suggests improvements and best practices ### Comprehensive Analysis - **Multi-faceted View**: Considers technical and business aspects - **Correlation**: Links related information across log entries - **Recommendations**: Provides actionable next steps ## AI Features ### Intelligent Parsing - Automatically extracts key information - Identifies patterns and anomalies - Understands log structure and format ### Context Awareness - Considers application metadata - Incorporates user and session information - Understands business domain context ### Natural Language Explanations - Clear, human-readable explanations - Technical details in accessible language - Actionable recommendations ## Access Methods ### Individual Log Analysis - Click "AI Explanation" on any log entry - Get instant analysis in a popup modal - Copy explanations for sharing ### Bulk Analysis - Select multiple logs for pattern analysis - Identify common issues across log groups - Generate summary reports ## Tips for Better AI Analysis ### Provide Rich Context - Use descriptive log messages - Include relevant metadata - Add appropriate tags and correlation IDs ### Structured Logging - Use consistent log formats - Include structured data in context - Maintain clear log hierarchies ### Regular Review - Use AI explanations for learning - Build team knowledge base - Improve logging practices based on insights ## Integration with Other Features ### Comments & Collaboration - Share AI explanations with team members - Add AI insights to collaborative discussions - Build knowledge base from AI analysis ### Filtering & Search - Use AI insights to create better filters - Search for patterns identified by AI - Focus on AI-recommended log types ## Privacy and Security - **No Data Storage**: AI analysis doesn't store your log data - **Secure Processing**: All analysis happens securely - **Privacy Focused**: No sensitive information is retained ## Next Steps - [Comments & Collaboration](/platforms/javascript/products/logs/web-panel/comments-collaboration) - Share AI insights with your team - [Filtering & Search](/platforms/javascript/products/logs/web-panel/filtering-search) - Use AI insights to improve your searches - [Log Visualization](/platforms/javascript/products/logs/web-panel/log-visualization) - Enhanced understanding of log details --- # Alerts & Workflows ByteHide's alerting system helps you stay informed about critical events in your applications through automated notifications and workflow triggers. {% .lead %} ## Log Retention Notifications ByteHide automatically notifies you about log retention limits to help manage your data storage. ### Free Plan Retention - **7 Days**: Free plan includes 7 days of log retention - **Upgrade Prompt**: Notification suggests upgrading to Team plan for longer retention - **Visual Indicator**: Blue info banner displays retention status ## Alert Types ### Critical Error Alerts - **Automatic Detection**: Monitor for Critical and Error level logs - **Threshold Based**: Alert when error count exceeds limits - **Real-time Notifications**: Instant alerts for critical issues ### Performance Alerts - **Slow Operations**: Alert on performance degradation - **Resource Usage**: Monitor memory and CPU through logs - **Response Time**: Track application response times ### Security Alerts - **Authentication Failures**: Monitor failed login attempts - **Suspicious Activity**: Detect unusual access patterns - **Security Violations**: Alert on security-related events ### Custom Alerts - **Tag-based**: Create alerts based on specific log tags - **Message Content**: Alert on specific log message patterns - **User Activity**: Monitor specific user actions ## Alert Configuration ### Alert Rules Configure alerts based on: - **Log Level**: Critical, Error, Warn, Info - **Time Window**: Alert frequency and timing - **Threshold**: Number of occurrences before alerting - **Conditions**: Complex filtering criteria ### Notification Methods - **Email**: Send alerts to team email addresses - **Webhook**: Integrate with external systems - **Dashboard**: In-app notifications - **Mobile**: Push notifications (if available) ## Workflow Automation ### Incident Response - **Auto-Escalation**: Escalate unresolved alerts - **Team Notification**: Alert relevant team members - **Ticket Creation**: Automatically create support tickets ### Integration Triggers - **Slack Integration**: Send alerts to Slack channels - **Teams Integration**: Microsoft Teams notifications - **PagerDuty**: Critical alert escalation - **Custom Webhooks**: Integrate with any external system ### Auto-Resolution - **Resolution Detection**: Automatically close alerts when issues resolve - **Follow-up Actions**: Trigger post-resolution workflows - **Report Generation**: Create incident summary reports ## Alert Management ### Alert Dashboard View and manage all alerts from a central dashboard: - **Active Alerts**: Currently triggered alerts - **Alert History**: Past alert activity - **Performance Metrics**: Alert response times - **Team Activity**: Who responded to which alerts ### Alert States - **Triggered**: Alert condition met - **Acknowledged**: Team member acknowledged alert - **Investigating**: Investigation in progress - **Resolved**: Issue resolved and alert closed ## Team Collaboration ### Alert Assignment - **Auto-Assignment**: Assign alerts based on rules - **Manual Assignment**: Team members can claim alerts - **Escalation**: Escalate unassigned alerts ### Communication - **Alert Comments**: Add comments to alert investigations - **Status Updates**: Update alert status with context - **Team Notifications**: Keep team informed of progress ## Configuration Examples ### Critical Error Alert ``` Trigger: Level is Critical Time Window: 1 minute Threshold: 1 occurrence Notification: Email + Slack ``` ### Performance Degradation Alert ``` Trigger: Tags contains "slow" AND Level is Warn Time Window: 5 minutes Threshold: 10 occurrences Notification: Email to DevOps team ``` ### Security Alert ``` Trigger: Tags contains "security" OR Message contains "unauthorized" Time Window: 1 minute Threshold: 1 occurrence Notification: Immediate email + PagerDuty ``` ## Best Practices ### Alert Design - **Actionable**: Ensure alerts lead to specific actions - **Clear Context**: Include enough information for investigation - **Appropriate Urgency**: Match notification method to severity ### Noise Reduction - **Threshold Tuning**: Adjust thresholds to reduce false positives - **Time Windows**: Use appropriate time windows for grouping - **Suppression**: Suppress duplicate or related alerts ### Team Coordination - **Clear Ownership**: Define who responds to which alerts - **Escalation Paths**: Establish clear escalation procedures - **Documentation**: Document common alert responses ## Integration Setup ### Webhook Configuration ```json { "url": "https://your-system.com/webhook", "method": "POST", "headers": { "Authorization": "Bearer your-token" } } ``` ### Slack Integration - Connect your Slack workspace - Choose notification channels - Configure message format - Set up threaded conversations ## Monitoring and Analytics ### Alert Metrics - **Response Time**: How quickly alerts are acknowledged - **Resolution Time**: Time from alert to resolution - **False Positive Rate**: Percentage of invalid alerts - **Coverage**: Percentage of issues caught by alerts ### Reporting - **Daily Summaries**: Alert activity summaries - **Trend Analysis**: Alert volume and pattern trends - **Team Performance**: Response time analytics - **System Health**: Overall application health metrics ## Next Steps - [Security Settings](/platforms/javascript/products/logs/web-panel/security-settings) - Configure access and security for alerts - [Comments & Collaboration](/platforms/javascript/products/logs/web-panel/comments-collaboration) - Collaborate on alert investigations - [Filtering & Search](/platforms/javascript/products/logs/web-panel/filtering-search) - Use alerts to improve log filtering --- # Comments & Collaboration ByteHide's commenting system enables team collaboration on log analysis, allowing developers to share insights, discuss issues, and build collective knowledge. {% .lead %} ## Comments Feature Each log entry supports collaborative comments for team discussion and knowledge sharing. ![Comment Button](/images/dotnet/logs/dashboard/log-comment-button.png) ## How to Add Comments 1. **Open Log Details**: Click on any log entry to view details 2. **Access Comments Tab**: Select the "Comments" tab in the modal 3. **Write Comment**: Type your comment in the text area 4. **Send**: Click "Send comment" to post ![Add Comment](/images/dotnet/logs/dashboard/log-comment-add.png) ## Comment Interface ### Comment Composition - **Text Area**: Large text input for detailed comments - **User Info**: Shows your name and email (e.g., "John Smith, john.smith@company.com") - **Send Button**: Blue "Send comment" button to post ### Comment Display - **Empty State**: "There are no comments yet" when no comments exist - **Encouragement**: "Be the first one to write a comment" - **Mentions**: Use "@" to mention team members ![Tag Team Members](/images/dotnet/logs/dashboard/log-comment-tag.png) ## Collaboration Use Cases ### Debugging Sessions - **Issue Discussion**: Team members discuss error causes - **Solution Sharing**: Share fixes and workarounds - **Knowledge Transfer**: Document discoveries for future reference ### Code Reviews - **Log Quality**: Comment on log message quality - **Best Practices**: Suggest logging improvements - **Pattern Recognition**: Identify recurring issues ### Incident Response - **Real-time Communication**: Coordinate during incidents - **Timeline Documentation**: Record investigation steps - **Resolution Tracking**: Document how issues were resolved ### Knowledge Building - **Context Explanation**: Explain business context of logs - **Documentation**: Create inline documentation - **Training**: Help junior developers understand complex logs ## Comment Features ### User Identification Comments show: - **Name**: Commenter's display name - **Email**: Associated email address - **Timestamp**: When the comment was posted ### Mention System - **@ Mentions**: Tag team members for attention - **Notifications**: Mentioned users receive notifications - **Team Collaboration**: Bring relevant people into discussions ### Rich Text Support - **Formatting**: Basic text formatting options - **Code Snippets**: Include code examples in comments - **Links**: Share relevant documentation or resources ## Team Collaboration Benefits ### Shared Knowledge - **Collective Intelligence**: Leverage team expertise - **Documentation**: Build searchable knowledge base - **Learning**: Share insights across skill levels ### Faster Resolution - **Multiple Perspectives**: Get different viewpoints on issues - **Experience Sharing**: Learn from team members' experiences - **Parallel Investigation**: Multiple team members can contribute ### Quality Improvement - **Peer Review**: Review each other's analysis - **Best Practices**: Share logging and debugging techniques - **Pattern Recognition**: Identify systemic issues together ## Comment Management ### Threading - Comments maintain chronological order - Easy to follow conversation flow - Clear attribution to comment authors ### Persistence - Comments remain with log entries permanently - Historical context preserved - Searchable for future reference ### Privacy - Comments visible to team members - Secure within your organization - No external access ## Integration with Other Features ### AI Assistant - **AI + Human**: Combine AI explanations with human insights - **Context Enhancement**: Add human context to AI analysis - **Learning**: Use AI insights to inform human discussions ### Filtering & Search - **Commented Logs**: Find logs with team discussions - **Knowledge Mining**: Search through comment content - **Pattern Discovery**: Identify frequently discussed issues ## Best Practices ### Effective Comments - **Be Descriptive**: Provide clear, detailed explanations - **Include Context**: Add business or technical context - **Reference Solutions**: Link to fixes or documentation ### Team Guidelines - **Response Time**: Establish comment response expectations - **Escalation**: When to escalate from comments to direct communication - **Documentation**: Use comments to build team knowledge base ### Comment Etiquette - **Professional Tone**: Maintain professional communication - **Constructive Feedback**: Provide helpful, actionable insights - **Acknowledgment**: Recognize others' contributions ## Notifications - **Real-time Updates**: See new comments as they appear - **Mention Alerts**: Get notified when mentioned - **Activity Tracking**: Track comment activity across logs ## Next Steps - [AI Assistant](/platforms/javascript/products/logs/web-panel/ai-assistant) - Enhance discussions with AI insights - [Alerts & Workflows](/platforms/javascript/products/logs/web-panel/alerts-workflows) - Set up automated notifications - [Log Visualization](/platforms/javascript/products/logs/web-panel/log-visualization) - Better understand logs for discussion --- # Filtering & Search ByteHide provides powerful filtering and search capabilities to help you quickly find specific logs and identify patterns in your application data. {% .lead %} ## Add Filters Use the "Add filters" button to create custom filters for your log search. ![Log Filters](/images/dotnet/logs/dashboard/log-filters.png) ### Available Filter Types The filter dropdown provides multiple options: - **level**: Filter by log level (Info, Warn, Error, Critical) - **tags**: Filter by log tags - **message**: Search within log messages - **correlation_id**: Find logs by correlation ID - **metadata**: Filter by metadata fields - **hostname**: Filter by source hostname - **user_id**: Filter by authenticated user ID - **user_email**: Filter by user email - **user_token**: Filter by user authentication token ![Filter Options](/images/dotnet/logs/dashboard/log-filters-dropdown.png) ## Filter Operations Each filter supports different operations: ### Text Filters - **contains**: Search for text within the field - **equals**: Exact match - **starts with**: Begins with specified text - **ends with**: Ends with specified text ### Level Filters - **is**: Exact level match (critical, error, warn, info) - **is not**: Exclude specific levels ### Example Filters Common filter combinations: ``` Level is critical Tags contains payment Message contains timeout ``` ![Active Filters](/images/dotnet/logs/dashboard/logs-filter-applied.png) ## Date Range Selection Control the time range of logs to display using the date picker. ![Date Range](/images/dotnet/logs/dashboard/log-date-range-button.png) ### Quick Date Options Pre-defined time ranges: - **Today**: Current day logs - **7 d**: Last 7 days - **15 d**: Last 15 days - **30 d**: Last 30 days ### Custom Date Range Select specific start and end dates using the calendar picker: - Click on the date range field - Navigate through months using arrow controls - Select start and end dates - Apply the custom range ![Date Picker](/images/dotnet/logs/dashboard/log-date-range-custom.png) ## Active Filters Display Active filters are shown as removable chips above the log list: - **Level is critical**: Shows level-based filtering - **Tags contains database**: Shows tag-based filtering - **Message contains connection**: Shows message content filtering Each filter chip includes an "X" button to remove individual filters. ## Reset Filters Use the "Reset" button to clear all active filters and return to the unfiltered log view. ![Reset Filters](/images/dotnet/logs/dashboard/log-reset-filters.png) ## Filter Combinations Combine multiple filters for precise log discovery: 1. **Error Investigation**: ``` Level is error Tags contains payment Date range: Last 7 days ``` 2. **User Activity Tracking**: ``` User_email contains user@company.com Message contains authentication ``` 3. **Performance Monitoring**: ``` Tags contains performance Level is warn ``` ## Search Tips - **Use specific terms**: More specific searches return better results - **Combine filters**: Use multiple criteria to narrow results - **Check spelling**: Ensure filter values match log content exactly - **Use correlation IDs**: Track related logs across requests - **Filter by time**: Narrow down to specific time periods ## Real-time Filtering Filters apply in real-time as you type, immediately updating the log display to show matching entries. ## Filter Persistence - Filters remain active while navigating the dashboard - Date ranges persist across page refreshes - Filter state is maintained during session ## Performance The filtering system is optimized for: - **Fast response**: Results appear instantly - **Large datasets**: Efficiently handles thousands of logs - **Complex queries**: Multiple simultaneous filters - **Real-time updates**: New logs automatically match active filters ## Next Steps - [AI Assistant](/platforms/javascript/products/logs/web-panel/ai-assistant) - Get AI-powered analysis of filtered logs - [Log Visualization](/platforms/javascript/products/logs/web-panel/log-visualization) - View detailed log information - [Comments & Collaboration](/platforms/javascript/products/logs/web-panel/comments-collaboration) - Share filtered views with team members --- # Log Visualization The ByteHide web panel provides a comprehensive interface to visualize and analyze all logs from your JavaScript applications in real-time. {% .lead %} ## Main Log View The main dashboard displays all your logs in a clean, organized table format. ![Main Dashboard](/images/dotnet/logs/dashboard/main-dashboard.png) ### Log List Features - **Message**: The main log message content - **Level**: Log level with color-coded badges (Info, Warn, Error, Critical) - **Time**: Timestamp when the log was generated - **Actions**: Access to detailed view and AI explanations ### Log Levels Each log level is displayed with distinct visual indicators: - **Info**: Blue badge for informational messages - **Warn**: Orange badge for warnings - **Error**: Red badge for errors - **Critical**: Dark red badge for critical issues ## Detailed Log View Click on any log entry to see comprehensive details in a modal window. ![Log Details](/images/dotnet/logs/dashboard/log-details.png) ### Details Panel The details panel shows: - **Time**: Exact timestamp - **Level**: Log severity level - **Hostname**: Source machine name - **Tags**: Associated tags for categorization ### User Information When available, authenticated user details are displayed: - **ID**: User identifier - **Email**: User email address - **Token**: Authentication token (masked for security) ### Multiple Tabs The detail view organizes information into tabs: - **Log message**: The main log content - **Context**: Additional context data - **Metadata**: Technical metadata and caller information - **Exception**: Exception details if applicable - **Location**: Source code location - **Stacktrace**: Full stack trace for errors ![Log Tabs](/images/dotnet/logs/dashboard/log-tabs.png) ## Context Information The Context tab shows structured data passed with the log: ```json { "ERROR": { "message": "Database connection failed: timeout after 30 seconds" }, "REQUEST_ID": "req_98f5d4e2a1", "USER_ID": "user_12345" } ``` ## Metadata View The Metadata tab displays technical information: - **CallerInfo**: Method, file, and line number - **StackTrace**: Full call stack - **Context**: Additional application context like version ![Log Metadata](/images/dotnet/logs/dashboard/log-metadata.png) ### Example Metadata Structure ```json { "metadata": { "CallerInfo": { "method": "ProcessPayment", "file": "/src/Services/PaymentService.cs", "line": 142, "stackTrace": "at PaymentService.ProcessPayment() in /src/Services/PaymentService.cs:line 142\n at OrderController.CreateOrder() in /src/Controllers/OrderController.cs:line 87" }, "Context": { "AppVersion": "2.1.4", "Environment": "Production", "CorrelationId": "order_abc123" } } } ``` ## Location Details Shows the exact source code location where the log was generated: - File path - Line numbers - Method names - Stack trace navigation ![Log Location](/images/dotnet/logs/dashboard/log-location.png) ## Real-time Updates Logs appear in real-time as your application generates them, allowing for: - Live monitoring during development - Real-time debugging of production issues - Immediate visibility into application behavior ## Pagination Navigate through large log volumes with: - **Rows per page**: Configurable (10, 20, 50, etc.) - **Page navigation**: Previous/next controls - **Total count**: Display of current range (e.g., "11-20 of 28") ![Log Pagination](/images/dotnet/logs/dashboard/log-pagination.png) ## Quick Actions Each log entry provides instant access to: - **View Details**: Expand full log information - **AI Explanation**: Get AI-powered analysis of the log - **Copy**: Copy log details to clipboard ## Visual Indicators The interface uses clear visual cues: - **Color-coded levels**: Instant recognition of log severity - **Expandable rows**: Click to see more details - **Status badges**: Clear identification of log types - **Timestamps**: Easy time-based log correlation ## Next Steps - [Filtering & Search](/platforms/javascript/products/logs/web-panel/filtering-search) - Learn how to filter and search logs - [AI Assistant](/platforms/javascript/products/logs/web-panel/ai-assistant) - Get AI-powered log analysis - [Comments & Collaboration](/platforms/javascript/products/logs/web-panel/comments-collaboration) - Collaborate on log analysis --- # Security Settings ByteHide provides comprehensive security settings to protect your log data and control access to your logging infrastructure. {% .lead %} ## Project Token Management Your project token is the primary authentication mechanism for ByteHide Logger. ![Project Token](/images/dotnet/logs/dashboard/log-security-reset-token.png) ### Current Token - **Token Display**: Project token shown as `bh_rD13Y...` (partially masked for security) - **Copy Function**: "Copy this token into your project configuration file" button - **Secure Storage**: Store token securely in your application configuration ### Token Security - **Unique Identifier**: Each project has a unique token - **Authentication**: Required for all logging operations - **Rotation**: Tokens can be reset when compromised ## Project Usage Monitoring Track your project's logging usage and data consumption. ![Project Usage](/images/dotnet/logs/dashboard/log-security-usage.png) ### Usage Metrics - **Month**: Monthly usage tracking (e.g., "2025-06") - **Stored Data (MB)**: Amount of log data stored (e.g., "0.38 MB") - **Total Data Scanned (MB)**: Total data processed (e.g., "28.54 MB") ### Data Management - Monitor storage consumption - Track data processing volumes - Plan capacity based on usage trends ## Custom Headers Configure custom headers for secure API requests and additional authentication. ![Custom Headers](/images/dotnet/logs/dashboard/log-security-headers.png) ### Header Configuration - **Add Header**: Button to add new custom headers - **Security Enhancement**: Add custom headers to secure your requests - **API Integration**: Support for custom API authentication ### Use Cases - **Additional Authentication**: Layer extra security on API calls - **Request Identification**: Add unique identifiers to requests - **Compliance**: Meet specific security compliance requirements ## IP Whitelist Control access to your logging infrastructure by restricting allowed IP addresses. ![IP Whitelist](/images/dotnet/logs/dashboard/log-security-ip.png) ### Whitelist Configuration - **IP Entry**: Text area for entering allowed IP addresses - **One Per Line**: Enter one complete IP address per line - **IPv4 Support**: Currently supports IPv4 addresses only - **Save IPs**: Button to apply whitelist changes ### Security Benefits - **Access Control**: Limit which networks can send logs - **Threat Reduction**: Prevent unauthorized log submissions - **Compliance**: Meet network security requirements ### Example Configuration ``` 192.168.1.100 10.0.0.50 203.0.113.25 ``` ## Token Reset Reset your project token when security is compromised or for routine security maintenance. ![Reset Token](/images/dotnet/logs/dashboard/log-security-reset-token.png) ### Reset Process - **Reset Button**: Red "Reset project Token" button - **Immediate Effect**: Token reset takes effect immediately - **Update Required**: Update all applications with new token after reset ### When to Reset - **Security Breach**: When token may be compromised - **Team Changes**: When team members leave - **Routine Security**: As part of regular security practices - **Compliance**: To meet security audit requirements ## Security Best Practices ### Token Management - **Secure Storage**: Store tokens in secure configuration systems - **Environment Variables**: Use environment variables, not hard-coded values - **Regular Rotation**: Rotate tokens periodically - **Access Limitation**: Limit who has access to tokens ### Network Security - **IP Restrictions**: Use IP whitelist for production environments - **VPN Access**: Consider VPN requirements for log access - **Network Monitoring**: Monitor for unusual network activity ### Access Control - **Team Permissions**: Control who can access security settings - **Audit Logging**: Track changes to security configurations - **Regular Reviews**: Periodically review access permissions ## Configuration Steps ### Initial Setup 1. **Copy Token**: Copy project token from settings 2. **Configure Application**: Add token to your .NET application 3. **Test Connection**: Verify logging works correctly 4. **Set IP Whitelist**: Add your application server IPs ### Security Hardening 1. **Enable IP Whitelist**: Restrict access to known IPs 2. **Add Custom Headers**: Implement additional authentication 3. **Monitor Usage**: Regularly check usage metrics 4. **Schedule Token Rotation**: Plan regular token updates ## Compliance Features ### Data Protection - **Encryption**: All data encrypted in transit and at rest - **Access Logging**: Track all access to log data - **Retention Controls**: Configure data retention periods - **Geographic Controls**: Control data processing locations ### Audit Trail - **Configuration Changes**: Log all security setting changes - **Access Records**: Maintain records of data access - **Token Usage**: Track token usage patterns - **IP Access**: Log IP address access attempts ## Troubleshooting ### Common Issues - **Authentication Failures**: Verify token is correct and active - **IP Blocking**: Check if IP is in whitelist - **Custom Headers**: Ensure headers are properly configured - **Token Expiry**: Confirm token hasn't been reset ### Diagnostic Steps 1. **Verify Token**: Check token matches settings 2. **Test Network**: Confirm IP is whitelisted 3. **Check Headers**: Validate custom header configuration 4. **Review Logs**: Check for authentication error messages ## Next Steps - [Log Visualization](/platforms/javascript/products/logs/web-panel/log-visualization) - View logs with proper security settings - [Alerts & Workflows](/platforms/javascript/products/logs/web-panel/alerts-workflows) - Set up security-related alerts - [Project Token Configuration](/platforms/javascript/products/logs/configuration/project-token) - Learn more about token configuration --- ## Logs — Python # Console Output # Console Output Enable and configure console logging for immediate visibility of log messages during development and debugging. ## Enable Console Logging Enable console output with a simple flag: ```python from bytehide_logs import Log, LogSettings settings = LogSettings(console_enabled=True) Log.initialize(settings) Log.info("This message appears in console") ``` ## Disable Console Logging Turn off console output while keeping other logging active: ```python settings = LogSettings(console_enabled=False) Log.initialize(settings) Log.info("This message is NOT shown in console") ``` ## Console with File Logging Log to both console and file simultaneously: ```python from bytehide_logs import Log, LogSettings, RollingInterval settings = LogSettings( console_enabled=True, # Output to console persist=True, # Also write to file file_path="./logs/app.log", rolling_interval=RollingInterval.DAY ) Log.initialize(settings) Log.info("Logged to both console and file") ``` ## Console Output Examples ### Basic Output ```python Log.info("Application started") Log.warn("High memory usage detected") Log.error("Failed to connect to database") ``` Output: ``` [INFO] Application started [WARN] High memory usage detected [ERROR] Failed to connect to database ``` ### With Caller Information Include filename and line number in console output: ```python settings = LogSettings( console_enabled=True, include_caller_info=True ) Log.initialize(settings) Log.info("Request received") ``` Output: ``` [INFO] app.py:42 Request received ``` ### Colored Output by Level ByteHide automatically colors console output by log level: ```python Log.trace("Trace message") # Gray Log.debug("Debug message") # Cyan Log.info("Info message") # Green Log.warn("Warning message") # Yellow Log.error("Error message") # Red Log.critical("Critical message") # Bright Red ``` ## Console Output with Context ### Tags Add tags to organize console output: ```python Log.with_tags("auth").info("User login successful") Log.with_tags("api", "v2").warn("Deprecated endpoint used") ``` Output: ``` [INFO] [auth] User login successful [WARN] [api][v2] Deprecated endpoint used ``` ### Custom Context Add key-value pairs to console output: ```python Log.with_context("user_id", "123").info("User action recorded") Log.with_context("endpoint", "/api/users").with_context("status", 200).info("Request completed") ``` Output: ``` [INFO] user_id=123 User action recorded [INFO] endpoint=/api/users status=200 Request completed ``` ### Correlation ID Track related log messages in console: ```python request_id = "req-abc123" Log.with_correlation_id(request_id).info("Request started") Log.with_correlation_id(request_id).debug("Processing user data") Log.with_correlation_id(request_id).info("Request completed") ``` Output: ``` [INFO] (req-abc123) Request started [DEBUG] (req-abc123) Processing user data [INFO] (req-abc123) Request completed ``` ## Console Output Configuration ### Development Configuration ```python settings = LogSettings( console_enabled=True, minimum_level=LogLevel.DEBUG, include_caller_info=True ) Log.initialize(settings) ``` Output style: - Shows all messages (DEBUG and above) - Includes source file and line number - Colored by level - Visible immediately ### Production Configuration ```python settings = LogSettings( console_enabled=False, # Usually disabled in production persist=True, minimum_level=LogLevel.WARN ) Log.initialize(settings) ``` ### Interactive Development ```python settings = LogSettings( console_enabled=True, minimum_level=LogLevel.TRACE, include_caller_info=True ) Log.initialize(settings) # Now see detailed execution flow for i in range(3): Log.trace(f"Loop iteration {i}") Log.debug(f"Processing item {i}") Log.info(f"Item {i} completed") ``` ## Redirecting Console Output ### To File (Operating System Level) ```bash # Redirect to file python app.py > logs.txt 2>&1 # Append to file python app.py >> logs.txt 2>&1 ``` ### In Python Code ```python import sys # Redirect stdout to file with open("console_output.log", "w") as f: original_stdout = sys.stdout sys.stdout = f try: Log.info("This is redirected") finally: sys.stdout = original_stdout ``` ## Console Formatting ### Include Timestamps While ByteHide doesn't format timestamps by default, you can add them: ```python from datetime import datetime import time Log.info(f"[{datetime.now().isoformat()}] Application started") ``` ### Pretty Printing Objects ```python import json user_data = {"id": 123, "name": "John", "email": "john@example.com"} Log.info(f"User data: {json.dumps(user_data, indent=2)}") ``` ### Multiline Output ```python error_details = """ Database Error Details: - Host: localhost:5432 - Database: myapp - Error: Connection timeout """ Log.error(f"Database connection failed:{error_details}") ``` ## Combining with File Logging Write detailed logs to file while showing summary in console: ```python from bytehide_logs import Log, LogSettings, LogLevel settings = LogSettings( # Console: high level only console_enabled=True, # File: all details persist=True, file_path="./logs/detailed.log", # Different minimum levels minimum_level=LogLevel.WARN # File gets all levels via persist ) Log.initialize(settings) Log.trace("Trace - only in file") Log.debug("Debug - only in file") Log.info("Info - only in file") Log.warn("Warning - in console and file") Log.error("Error - in console and file") ``` ## Sensitive Data in Console Protect sensitive data from appearing in console: ```python settings = LogSettings( console_enabled=True, mask_sensitive_data=["password", "token", "api_key"] ) Log.initialize(settings) password = "secret123" Log.info(f"Login attempt with password: {password}") # Output: [INFO] Login attempt with password: *** ``` ## Environment-Based Console Configuration ```python import os from bytehide_logs import Log, LogSettings, LogLevel def setup_console(): env = os.getenv("ENV", "development") config = { "development": { "console_enabled": True, "minimum_level": LogLevel.DEBUG, "include_caller_info": True }, "staging": { "console_enabled": True, "minimum_level": LogLevel.INFO, "include_caller_info": False }, "production": { "console_enabled": False, "minimum_level": LogLevel.WARN } } cfg = config.get(env, config["development"]) Log.initialize(LogSettings(**cfg)) if __name__ == "__main__": setup_console() ``` ## Performance Impact Console logging is asynchronous and has minimal performance impact. For high-throughput applications: ```python # Reduce console verbosity settings = LogSettings( console_enabled=True, minimum_level=LogLevel.WARN # Only important messages ) Log.initialize(settings) ``` ## Troubleshooting ### Console Output Not Appearing ```python # Ensure console is enabled settings = LogSettings(console_enabled=True) Log.initialize(settings) # Check the log level filter from bytehide_logs import LogLevel settings = LogSettings( console_enabled=True, minimum_level=LogLevel.TRACE ) ``` ### Colors Not Working Colors should work on most terminals. If not: ```python # Verify basic output is working Log.info("Testing console output") # Check your terminal supports colors # Try a different terminal or configure SSH with: ssh -t hostname ``` ## Next Steps - [Quick Start](/platforms/python/core/quick-start/) - Get started with logging - [Log Levels](/platforms/python/configuration/levels/) - Filter messages by severity - [File Logging](/platforms/python/configuration/file-logging/) - Log to files with rotation --- # Disable Logging # Disable Logging Control logging behavior at runtime with the ability to enable, disable, and selectively manage log output. ## Disable All Logging Completely disable logging for performance-critical sections: ```python from bytehide_logs import Log Log.info("This message is logged") Log.disable() Log.info("This message is NOT logged") Log.enable() Log.info("This message is logged again") ``` ## Enable Logging Re-enable logging after it has been disabled: ```python Log.disable() # ... perform logging-intensive operations ... Log.enable() ``` ## Disabling in Development vs Production ### Development Scenario Keep full logging enabled for debugging: ```python import os if os.getenv("ENV") != "production": # Development: keep logging enabled pass else: # Production: may disable logging for specific operations Log.disable() ``` ### Production Scenario Disable logging during performance-critical operations: ```python def performance_critical_operation(): """Operation that shouldn't be logged for performance reasons""" Log.disable() try: # High-throughput operations for i in range(1000000): process_data(i) finally: Log.enable() ``` ## Conditional Logging ### Based on Environment ```python import os from bytehide_logs import Log, LogSettings, LogLevel def setup_logging(): env = os.getenv("ENV", "development") if env == "production": # Minimal logging Log.initialize(LogSettings( minimum_level=LogLevel.CRITICAL, console_enabled=False )) elif env == "staging": # Moderate logging Log.initialize(LogSettings( minimum_level=LogLevel.INFO, console_enabled=True )) else: # Full logging Log.initialize(LogSettings( minimum_level=LogLevel.DEBUG, console_enabled=True )) ``` ### Based on Feature Flags ```python from bytehide_logs import Log FEATURE_FLAGS = { "debug_mode": False, "verbose_logging": False } def log_if_enabled(message, level="info"): if FEATURE_FLAGS["verbose_logging"]: getattr(Log, level)(message) elif FEATURE_FLAGS["debug_mode"]: Log.debug(message) log_if_enabled("Detailed operation info") ``` ## Disabling Specific Log Levels ### Filter by Minimum Level Instead of disabling completely, filter by level: ```python from bytehide_logs import Log, LogSettings, LogLevel # Only WARN and above settings = LogSettings(minimum_level=LogLevel.WARN) Log.initialize(settings) Log.debug("Not logged") Log.info("Not logged") Log.warn("Logged") Log.error("Logged") Log.critical("Logged") ``` ### Suppress Console, Keep File Disable console output while keeping file persistence: ```python settings = LogSettings( console_enabled=False, # Disable console persist=True, # Keep file logging file_path="./logs/app.log" ) Log.initialize(settings) ``` ### Suppress File, Keep Console ```python settings = LogSettings( console_enabled=True, # Keep console persist=False # Disable file ) Log.initialize(settings) ``` ## Performance Optimization ### Disable Logging During Batch Operations ```python def process_large_dataset(): """Process data without logging overhead""" Log.info("Starting batch processing") Log.disable() try: for item in large_dataset: expensive_operation(item) # No logging, better performance finally: Log.enable() Log.info("Batch processing completed") ``` ### Use Higher Log Levels for High-Throughput ```python from bytehide_logs import Log, LogSettings, LogLevel # For high-throughput applications settings = LogSettings( minimum_level=LogLevel.ERROR, # Only errors and above console_enabled=False, persist=True, file_path="./logs/app.log" ) Log.initialize(settings) ``` ## Selective Logging ### Log Only Errors and Critical ```python settings = LogSettings(minimum_level=LogLevel.ERROR) Log.initialize(settings) # Only these are logged: Log.error("Error occurred") Log.critical("Critical issue") # These are not logged: Log.info("Operation completed") Log.warn("Performance degraded") ``` ### Contextual Disabling ```python class DatabaseConnection: def __init__(self, verbose=False): self.verbose = verbose def execute_query(self, query): if self.verbose: Log.debug(f"Executing: {query}") result = self._run_query(query) if self.verbose: Log.debug(f"Result rows: {len(result)}") return result ``` ## Toggle Logging at Runtime ### Simple Toggle Function ```python class LoggingManager: _enabled = True @classmethod def disable(cls): cls._enabled = False Log.disable() @classmethod def enable(cls): cls._enabled = True Log.enable() @classmethod def is_enabled(cls): return cls._enabled # Usage LoggingManager.disable() # ... performance-critical section ... LoggingManager.enable() ``` ### With Context Manager ```python from contextlib import contextmanager @contextmanager def logging_disabled(): """Context manager to temporarily disable logging""" Log.disable() try: yield finally: Log.enable() # Usage with logging_disabled(): expensive_operation() another_expensive_operation() # Logging is automatically re-enabled Log.info("Operations completed") ``` ## HTTP Request Logging Control ```python from flask import Flask from bytehide_logs import Log app = Flask(__name__) # List of endpoints that shouldn't log requests QUIET_ENDPOINTS = ["/health", "/metrics", "/status"] @app.before_request def log_request(): if request.path not in QUIET_ENDPOINTS: Log.info(f"Request: {request.method} {request.path}") else: # Disable logging for health checks Log.disable() @app.after_request def log_response(response): if request.path in QUIET_ENDPOINTS: Log.enable() else: Log.info(f"Response: {response.status_code}") return response ``` ## Database Query Logging Control ```python from bytehide_logs import Log class DatabaseLogger: def __init__(self, log_queries=True): self.log_queries = log_queries def execute(self, query): if self.log_queries: Log.debug(f"Executing query: {query}") result = self._db_execute(query) if self.log_queries: Log.debug(f"Query completed, rows affected: {len(result)}") return result ``` ## Background Task Logging ```python import asyncio from bytehide_logs import Log async def background_task(verbose=False): """Background task with optional logging""" if not verbose: Log.disable() try: # Perform background work result = await perform_work() if verbose: Log.info(f"Background task completed: {result}") finally: Log.enable() ``` ## Flush Before Disabling Ensure logs are written before disabling: ```python from bytehide_logs import Log # Flush any pending logs Log.flush() # Now disable Log.disable() # Perform operations # ... # Enable and flush again Log.enable() Log.flush() ``` ## Testing Configuration ### Disable Logging in Tests ```python import pytest from bytehide_logs import Log @pytest.fixture(autouse=True) def disable_logging(): """Disable logging for all tests""" Log.disable() yield Log.enable() def test_something(): # Logging is disabled during test pass ``` ### Enable Only Errors in Tests ```python import pytest from bytehide_logs import Log, LogSettings, LogLevel @pytest.fixture(scope="session", autouse=True) def configure_logging(): """Configure minimal logging for tests""" Log.initialize(LogSettings( minimum_level=LogLevel.ERROR, console_enabled=False )) ``` ## Disable Caller Information Reduce logging overhead by disabling caller info: ```python settings = LogSettings( console_enabled=True, include_caller_info=False # Faster, no file/line info ) Log.initialize(settings) ``` ## Monitoring Logging Status ```python def get_logging_status(): """Get current logging configuration""" return { "console_enabled": settings.console_enabled, "persist_enabled": settings.persist, "minimum_level": settings.minimum_level.name, "include_caller_info": settings.include_caller_info } # Usage status = get_logging_status() Log.info(f"Logging status: {status}") ``` ## Best Practices 1. **Temporary Disabling** - Use context managers for temporary disabling 2. **Always Re-enable** - Use try/finally to ensure logging is re-enabled 3. **Test Impact** - Verify performance improvements from disabling 4. **Documentation** - Document why logging is disabled for sections 5. **Monitoring** - Log when logging is disabled/enabled for debugging ## Complete Example ```python from bytehide_logs import Log, LogSettings, LogLevel from contextlib import contextmanager @contextmanager def temporary_logging_disabled(): """Temporarily disable logging""" Log.disable() try: yield finally: Log.enable() def setup_application(): settings = LogSettings( console_enabled=True, minimum_level=LogLevel.INFO ) Log.initialize(settings) if __name__ == "__main__": setup_application() Log.info("Application started") # Performance-critical section with temporary_logging_disabled(): for i in range(1000): expensive_operation(i) Log.info("Processing completed") Log.flush() ``` ## Next Steps - [Quick Start](/platforms/python/core/quick-start/) - Initialize logging - [Log Levels](/platforms/python/configuration/levels/) - Filter by severity - [Configuration](/platforms/python/core/configuration/) - All options --- # Environment Variables # Environment Variables Configure ByteHide Logs entirely through environment variables for seamless deployment across Docker, Kubernetes, and cloud platforms. ## Core Variables ### PROJECT_TOKEN Your ByteHide project token - first checked by the SDK: ```bash export PROJECT_TOKEN="bh_your_token_here" ``` Usage in Python: ```python import os from bytehide_logs import Log # Automatically loaded if set token = os.getenv("PROJECT_TOKEN") if token: Log.set_project_token(token) ``` ### BYTEHIDE_PROJECT_TOKEN Alternative environment variable for project token: ```bash export BYTEHIDE_PROJECT_TOKEN="bh_your_token_here" ``` The SDK checks variables in order: 1. `PROJECT_TOKEN` 2. `BYTEHIDE_PROJECT_TOKEN` ## Logging Configuration ### BYTEHIDE_CONSOLE_ENABLED Enable console output: ```bash export BYTEHIDE_CONSOLE_ENABLED=true export BYTEHIDE_CONSOLE_ENABLED=false ``` ### BYTEHIDE_LOG_LEVEL Set minimum log level (TRACE, DEBUG, INFO, WARN, ERROR, CRITICAL): ```bash export BYTEHIDE_LOG_LEVEL=INFO export BYTEHIDE_LOG_LEVEL=DEBUG export BYTEHIDE_LOG_LEVEL=WARN ``` ### BYTEHIDE_FILE_PATH Path to log file: ```bash export BYTEHIDE_FILE_PATH=/var/log/myapp/app.log export BYTEHIDE_FILE_PATH=./logs/app.log ``` ### BYTEHIDE_PERSIST Enable file persistence: ```bash export BYTEHIDE_PERSIST=true export BYTEHIDE_PERSIST=false ``` ### BYTEHIDE_ROLLING_INTERVAL Log file rotation interval (MINUTE, HOUR, DAY, WEEK, MONTH, YEAR): ```bash export BYTEHIDE_ROLLING_INTERVAL=DAY export BYTEHIDE_ROLLING_INTERVAL=HOUR ``` ### BYTEHIDE_FILE_SIZE_LIMIT Maximum file size in bytes before rotation: ```bash # 10MB export BYTEHIDE_FILE_SIZE_LIMIT=10485760 # 50MB export BYTEHIDE_FILE_SIZE_LIMIT=52428800 # 100MB export BYTEHIDE_FILE_SIZE_LIMIT=104857600 ``` ### BYTEHIDE_ROLL_ON_SIZE Enable size-based rotation: ```bash export BYTEHIDE_ROLL_ON_SIZE=true export BYTEHIDE_ROLL_ON_SIZE=false ``` ### BYTEHIDE_INCLUDE_CALLER_INFO Include filename and line number in logs: ```bash export BYTEHIDE_INCLUDE_CALLER_INFO=true ``` ### BYTEHIDE_SENSITIVE_DATA Comma-separated list of keywords to mask: ```bash export BYTEHIDE_SENSITIVE_DATA="password,token,api_key,secret" ``` ## Docker Configuration ### Basic Docker Usage ```dockerfile FROM python:3.9 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . ENV PROJECT_TOKEN=bh_your_token CMD ["python", "app.py"] ``` Build and run: ```bash docker build -t myapp . docker run -e PROJECT_TOKEN="bh_token" myapp ``` ### Docker Compose ```yaml version: '3.8' services: app: build: . environment: - PROJECT_TOKEN=${PROJECT_TOKEN} - BYTEHIDE_CONSOLE_ENABLED=true - BYTEHIDE_LOG_LEVEL=INFO - BYTEHIDE_PERSIST=true - BYTEHIDE_FILE_PATH=/var/log/myapp/app.log volumes: - ./logs:/var/log/myapp ``` Run with: ```bash PROJECT_TOKEN="bh_token" docker-compose up ``` ### Docker with .env File Create `.env` file: ``` PROJECT_TOKEN=bh_your_token BYTEHIDE_CONSOLE_ENABLED=true BYTEHIDE_LOG_LEVEL=DEBUG BYTEHIDE_PERSIST=true BYTEHIDE_FILE_PATH=/var/log/myapp/app.log ``` Docker Compose will automatically load it: ```bash docker-compose up ``` ## Kubernetes Configuration ### Basic Deployment with Env Vars ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: myapp spec: replicas: 3 selector: matchLabels: app: myapp template: metadata: labels: app: myapp spec: containers: - name: myapp image: myapp:latest env: - name: PROJECT_TOKEN value: "bh_your_token" - name: BYTEHIDE_CONSOLE_ENABLED value: "true" - name: BYTEHIDE_LOG_LEVEL value: "INFO" - name: BYTEHIDE_PERSIST value: "true" - name: BYTEHIDE_FILE_PATH value: "/var/log/myapp/app.log" ``` ### Using Kubernetes Secrets Create secret: ```bash kubectl create secret generic bytehide-secret --from-literal=project-token=bh_your_token ``` Reference in deployment: ```yaml env: - name: PROJECT_TOKEN valueFrom: secretKeyRef: name: bytehide-secret key: project-token ``` ### ConfigMap for Settings Create ConfigMap: ```yaml apiVersion: v1 kind: ConfigMap metadata: name: bytehide-config data: BYTEHIDE_CONSOLE_ENABLED: "true" BYTEHIDE_LOG_LEVEL: "INFO" BYTEHIDE_PERSIST: "true" BYTEHIDE_ROLLING_INTERVAL: "DAY" ``` Use in Deployment: ```yaml envFrom: - configMapRef: name: bytehide-config env: - name: PROJECT_TOKEN valueFrom: secretKeyRef: name: bytehide-secret key: project-token ``` ## Cloud Platform Configuration ### AWS Lambda ```python import os from bytehide_logs import Log, LogSettings, LogLevel def lambda_handler(event, context): # Load configuration from environment token = os.getenv("PROJECT_TOKEN") console = os.getenv("BYTEHIDE_CONSOLE_ENABLED", "true") == "true" level = os.getenv("BYTEHIDE_LOG_LEVEL", "INFO") Log.set_project_token(token) Log.initialize(LogSettings( console_enabled=console, minimum_level=LogLevel[level] )) Log.info("Lambda function invoked") return {"statusCode": 200} ``` ### Google Cloud Run ```bash gcloud run deploy myapp \ --set-env-vars PROJECT_TOKEN=bh_your_token \ --set-env-vars BYTEHIDE_CONSOLE_ENABLED=true \ --set-env-vars BYTEHIDE_LOG_LEVEL=INFO ``` ### Azure Container Instances ```bash az container create \ --resource-group mygroup \ --name myapp \ --image myapp:latest \ --environment-variables PROJECT_TOKEN=bh_token BYTEHIDE_CONSOLE_ENABLED=true ``` ## Local Development Setup ### Using .env File Create `.env`: ```bash PROJECT_TOKEN=bh_dev_token BYTEHIDE_CONSOLE_ENABLED=true BYTEHIDE_LOG_LEVEL=DEBUG BYTEHIDE_PERSIST=true BYTEHIDE_FILE_PATH=./logs/app.log BYTEHIDE_INCLUDE_CALLER_INFO=true ``` Load in your application: ```python import os from dotenv import load_dotenv load_dotenv() # Load from .env from bytehide_logs import Log, LogSettings, LogLevel # Configuration automatically loaded Log.set_project_token(os.getenv("PROJECT_TOKEN")) console = os.getenv("BYTEHIDE_CONSOLE_ENABLED", "true") == "true" level = os.getenv("BYTEHIDE_LOG_LEVEL", "INFO") Log.initialize(LogSettings( console_enabled=console, minimum_level=LogLevel[level] )) ``` ## Environment-Based Configuration ### Development ```bash export ENV=development export PROJECT_TOKEN=bh_dev_token export BYTEHIDE_CONSOLE_ENABLED=true export BYTEHIDE_LOG_LEVEL=DEBUG export BYTEHIDE_PERSIST=true export BYTEHIDE_INCLUDE_CALLER_INFO=true ``` ### Staging ```bash export ENV=staging export PROJECT_TOKEN=bh_staging_token export BYTEHIDE_CONSOLE_ENABLED=true export BYTEHIDE_LOG_LEVEL=INFO export BYTEHIDE_PERSIST=true export BYTEHIDE_FILE_PATH=/var/log/myapp/app.log ``` ### Production ```bash export ENV=production export PROJECT_TOKEN=bh_prod_token export BYTEHIDE_CONSOLE_ENABLED=false export BYTEHIDE_LOG_LEVEL=WARN export BYTEHIDE_PERSIST=true export BYTEHIDE_FILE_PATH=/var/log/myapp/app.log export BYTEHIDE_ROLLING_INTERVAL=DAY export BYTEHIDE_ROLL_ON_SIZE=true export BYTEHIDE_FILE_SIZE_LIMIT=52428800 export BYTEHIDE_SENSITIVE_DATA="password,token,api_key,secret" ``` ## Python Helper for Env Config ```python import os from bytehide_logs import Log, LogSettings, LogLevel, RollingInterval def setup_from_env(): """Initialize ByteHide Logs from environment variables""" # Token token = os.getenv("PROJECT_TOKEN") or os.getenv("BYTEHIDE_PROJECT_TOKEN") if not token: raise ValueError("PROJECT_TOKEN not set") Log.set_project_token(token) # Convert string env vars to appropriate types console = os.getenv("BYTEHIDE_CONSOLE_ENABLED", "true").lower() == "true" persist = os.getenv("BYTEHIDE_PERSIST", "false").lower() == "true" caller_info = os.getenv("BYTEHIDE_INCLUDE_CALLER_INFO", "false").lower() == "true" roll_on_size = os.getenv("BYTEHIDE_ROLL_ON_SIZE", "false").lower() == "true" level_str = os.getenv("BYTEHIDE_LOG_LEVEL", "INFO") minimum_level = LogLevel[level_str] interval_str = os.getenv("BYTEHIDE_ROLLING_INTERVAL", "DAY") rolling_interval = RollingInterval[interval_str] file_size = int(os.getenv("BYTEHIDE_FILE_SIZE_LIMIT", "104857600")) mask_str = os.getenv("BYTEHIDE_SENSITIVE_DATA", "") mask_list = [m.strip() for m in mask_str.split(",") if m.strip()] settings = LogSettings( console_enabled=console, minimum_level=minimum_level, include_caller_info=caller_info, persist=persist, file_path=os.getenv("BYTEHIDE_FILE_PATH"), rolling_interval=rolling_interval, roll_on_file_size_limit=roll_on_size, file_size_limit_bytes=file_size, mask_sensitive_data=mask_list ) Log.initialize(settings) if __name__ == "__main__": setup_from_env() Log.info("Logging configured from environment") ``` ## Verifying Environment Variables ```bash # Check if variables are set echo $PROJECT_TOKEN echo $BYTEHIDE_CONSOLE_ENABLED echo $BYTEHIDE_LOG_LEVEL # In Python import os print(f"PROJECT_TOKEN: {os.getenv('PROJECT_TOKEN')}") print(f"BYTEHIDE_CONSOLE_ENABLED: {os.getenv('BYTEHIDE_CONSOLE_ENABLED')}") ``` ## Troubleshooting ### Variables Not Being Read Ensure variables are exported: ```bash # Not set BYTEHIDE_CONSOLE_ENABLED=true python app.py # Properly exported export BYTEHIDE_CONSOLE_ENABLED=true python app.py ``` ### Case Sensitivity Environment variable names are case-sensitive. Use uppercase: ```bash # Correct export BYTEHIDE_LOG_LEVEL=INFO # Incorrect - won't work export bytehide_log_level=INFO ``` ## Next Steps - [Quick Start](/platforms/python/core/quick-start/) - Initialize logging - [Project Token](/platforms/python/configuration/project-token/) - Token management - [Configuration](/platforms/python/core/configuration/) - All configuration options --- # File Logging # File Logging Persist application logs to files with automatic rotation by time and size. ## Enable File Logging Enable persistence to write logs to disk: ```python from bytehide_logs import Log, LogSettings settings = LogSettings( persist=True, file_path="./logs/app.log" ) Log.initialize(settings) Log.info("This message is written to file") ``` ## File Path Configuration ### Absolute Path Use absolute paths for reliability: ```python settings = LogSettings( persist=True, file_path="/var/log/myapp/app.log" ) ``` ### Relative Path Relative to the current working directory: ```python settings = LogSettings( persist=True, file_path="./logs/app.log" ) ``` ### Dynamic Path Create paths based on environment or timestamp: ```python import os from datetime import datetime app_name = "myapp" env = os.getenv("ENV", "dev") log_file = f"./logs/{app_name}_{env}_{datetime.now().strftime('%Y%m%d')}.log" settings = LogSettings( persist=True, file_path=log_file ) ``` ### Directory Creation Ensure the log directory exists: ```python import os log_dir = "./logs" os.makedirs(log_dir, exist_ok=True) settings = LogSettings( persist=True, file_path=os.path.join(log_dir, "app.log") ) ``` ## Rolling Intervals Automatically rotate log files at regular time intervals. ### Daily Rotation (Default) ```python from bytehide_logs import Log, LogSettings, RollingInterval settings = LogSettings( persist=True, file_path="./logs/app.log", rolling_interval=RollingInterval.DAY ) Log.initialize(settings) # New file created: app_2026-03-02.log # Next day: app_2026-03-03.log ``` ### Hourly Rotation ```python settings = LogSettings( persist=True, file_path="./logs/app.log", rolling_interval=RollingInterval.HOUR ) # File names: app_2026-03-02_14.log, app_2026-03-02_15.log ``` ### Weekly Rotation ```python settings = LogSettings( persist=True, file_path="./logs/app.log", rolling_interval=RollingInterval.WEEK ) # New file every Monday ``` ### Monthly Rotation ```python settings = LogSettings( persist=True, file_path="./logs/app.log", rolling_interval=RollingInterval.MONTH ) # New file every month ``` ### Yearly Rotation ```python settings = LogSettings( persist=True, file_path="./logs/app.log", rolling_interval=RollingInterval.YEAR ) # New file every January 1st ``` ### Minute Rotation (Testing) ```python settings = LogSettings( persist=True, file_path="./logs/app.log", rolling_interval=RollingInterval.MINUTE ) # Creates new file every minute (useful for testing) ``` ## Size-Based Rotation Rotate files when they exceed a size limit. ### Enable Size-Based Rotation ```python settings = LogSettings( persist=True, file_path="./logs/app.log", roll_on_file_size_limit=True, file_size_limit_bytes=10485760 # 10MB ) Log.initialize(settings) ``` ### Size Limits Common file size limits: ```python # 1 MB file_size_limit_bytes = 1048576 # 10 MB file_size_limit_bytes = 10485760 # 50 MB file_size_limit_bytes = 52428800 # 100 MB (default) file_size_limit_bytes = 104857600 # 500 MB file_size_limit_bytes = 524288000 ``` ## Combined Rotation Rotate by both time and size: ```python from bytehide_logs import Log, LogSettings, RollingInterval settings = LogSettings( persist=True, file_path="./logs/app.log", # Time-based rotation rolling_interval=RollingInterval.DAY, # Size-based rotation roll_on_file_size_limit=True, file_size_limit_bytes=52428800 # 50MB ) Log.initialize(settings) # Rotates at midnight OR when file exceeds 50MB ``` ## Production Configuration ```python import os from bytehide_logs import Log, LogSettings, LogLevel, RollingInterval settings = LogSettings( # No console in production console_enabled=False, # Write to persistent storage persist=True, file_path="/var/log/myapp/app.log", # Only important messages minimum_level=LogLevel.WARN, # Daily rotation rolling_interval=RollingInterval.DAY, # Also rotate on size roll_on_file_size_limit=True, file_size_limit_bytes=52428800, # 50MB # Include source info for debugging include_caller_info=True, # Mask sensitive data mask_sensitive_data=["password", "api_key", "token"] ) Log.set_project_token(os.getenv("PROJECT_TOKEN")) Log.initialize(settings) ``` ## Development Configuration ```python from bytehide_logs import Log, LogSettings, LogLevel, RollingInterval settings = LogSettings( # See output immediately console_enabled=True, # Also save to file persist=True, file_path="./logs/dev.log", # All messages minimum_level=LogLevel.DEBUG, # Simple rotation rolling_interval=RollingInterval.DAY, # Include debugging info include_caller_info=True ) Log.initialize(settings) ``` ## High-Volume Logging Configure for applications with high log volume: ```python from bytehide_logs import Log, LogSettings, LogLevel, RollingInterval settings = LogSettings( persist=True, file_path="./logs/app.log", # Hourly rotation for frequent rolling rolling_interval=RollingInterval.HOUR, # Rotate at 100MB to prevent huge files roll_on_file_size_limit=True, file_size_limit_bytes=104857600, # Reduce console overhead console_enabled=False, # Only important messages minimum_level=LogLevel.WARN ) Log.initialize(settings) ``` ## Log File Naming ByteHide automatically generates file names with timestamps: ``` app.log # Base name app_2026-03-02.log # Daily rotation app_2026-03-02_14.log # Hourly rotation ``` ## Managing Log Files ### View Recent Logs ```bash # Tail last 50 lines tail -50 /var/log/myapp/app.log # Real-time monitoring tail -f /var/log/myapp/app.log ``` ### Compress Old Logs ```bash # Compress files older than 7 days find /var/log/myapp -name "*.log" -mtime +7 -exec gzip {} \; ``` ### Clean Up Old Logs ```bash # Remove logs older than 30 days find /var/log/myapp -name "*.log*" -mtime +30 -delete ``` ## Log File Permissions Set appropriate permissions for log files: ```bash # Create log directory with restricted permissions mkdir -p /var/log/myapp chmod 755 /var/log/myapp # Restrict log file access chmod 644 /var/log/myapp/app.log ``` ## Troubleshooting ### Log Files Not Created Ensure the directory exists and is writable: ```python import os log_dir = "./logs" if not os.path.exists(log_dir): os.makedirs(log_dir) print(f"Created directory: {log_dir}") settings = LogSettings( persist=True, file_path=os.path.join(log_dir, "app.log") ) Log.initialize(settings) Log.info("Testing file logging") ``` ### Permission Denied Change the file path to a writable location: ```python # Instead of /var/log (requires root) # Use current directory settings = LogSettings( persist=True, file_path="./logs/app.log" # Writable by current user ) ``` ### Disk Space Issues Monitor and manage disk space for log files: ```bash # Check disk usage du -sh /var/log/myapp # Check available space df -h /var/log # List files by size ls -lhS /var/log/myapp/*.log ``` ## Combining Console and File ```python from bytehide_logs import Log, LogSettings, LogLevel settings = LogSettings( # Show in console console_enabled=True, # Also save to file persist=True, file_path="./logs/app.log", # File includes everything rolling_interval=RollingInterval.DAY, roll_on_file_size_limit=True, file_size_limit_bytes=52428800 ) Log.initialize(settings) Log.info("This appears in console and file") ``` ## Flush Logs Ensure all logs are written to disk: ```python Log.info("Application shutting down") Log.flush() # Ensure all logs are written ``` Use in shutdown handlers: ```python import signal def shutdown_handler(signum, frame): Log.info("Shutdown signal received") Log.flush() exit(0) signal.signal(signal.SIGTERM, shutdown_handler) ``` ## Next Steps - [Quick Start](/platforms/python/core/quick-start/) - Initialize logging - [Log Levels](/platforms/python/configuration/levels/) - Control verbosity - [Console Output](/platforms/python/configuration/console-output/) - Configure console display - [Environment Variables](/platforms/python/configuration/environment-variables/) - Configure via environment --- # Log Levels # Log Levels ByteHide Logs supports six severity levels for controlling log output and filtering messages. ## Log Level Hierarchy From least to most severe: ``` TRACE < DEBUG < INFO < WARN < ERROR < CRITICAL ``` ## Level Reference ### TRACE Most detailed logging level for in-depth debugging: ```python from bytehide_logs import Log, LogLevel Log.set_project_token("your-token") Log.initialize(LogSettings(minimum_level=LogLevel.TRACE)) Log.trace("Variable x = 42") Log.trace("Entering function calculate()") ``` **Use cases:** - Variable inspection - Function entry/exit - Detailed flow tracking - Performance profiling ### DEBUG Diagnostic information for development: ```python Log.debug("Cache key not found, fetching from database") Log.debug(f"Request headers: {headers}") Log.debug("Database connection established") ``` **Use cases:** - Diagnostics - Method parameters - State changes - Configuration details ### INFO General informational messages about application operation: ```python Log.info("Application started") Log.info(f"User {user_id} logged in") Log.info("Background job completed") ``` **Use cases:** - Application lifecycle events - User actions - Business operations - Job completions ### WARN Warning messages indicating potential issues: ```python Log.warn("Database query took 5 seconds") Log.warn("Configuration value missing, using default") Log.warn("Disk space running low") ``` **Use cases:** - Non-critical issues - Degraded performance - Deprecated features - Resource warnings ### ERROR Error messages indicating failures: ```python try: result = database.query("SELECT * FROM users") except Exception as e: Log.error("Database query failed", exception=e) ``` **Use cases:** - Operation failures - Exception handling - Recoverable errors - Validation failures ### CRITICAL Critical messages indicating system failure: ```python Log.critical("Out of memory error - system shutdown imminent") Log.critical("Security violation detected") Log.critical("Database unavailable - cannot continue") ``` **Use cases:** - System failures - Security issues - Data corruption - Complete loss of functionality ## Filtering by Level Use `minimum_level` in settings to filter log messages: ```python from bytehide_logs import Log, LogSettings, LogLevel settings = LogSettings(minimum_level=LogLevel.WARN) Log.initialize(settings) Log.trace("Not logged") # Filtered out Log.debug("Not logged") # Filtered out Log.info("Not logged") # Filtered out Log.warn("Logged") # Displayed Log.error("Logged") # Displayed Log.critical("Logged") # Displayed ``` ## Environment-Based Filtering Choose different log levels per environment: ```python import os from bytehide_logs import Log, LogSettings, LogLevel def setup_logging(): env = os.getenv("ENV", "development") level_map = { "development": LogLevel.DEBUG, "staging": LogLevel.INFO, "production": LogLevel.WARN } settings = LogSettings( minimum_level=level_map.get(env, LogLevel.INFO) ) Log.initialize(settings) if __name__ == "__main__": setup_logging() ``` ## Log Level Examples ### Development Configuration ```python settings = LogSettings( minimum_level=LogLevel.DEBUG, # See everything console_enabled=True, include_caller_info=True ) ``` Output: ``` [DEBUG] app.py:42 Database query started [DEBUG] app.py:43 Query parameters: {'id': 123} [INFO] app.py:45 Query completed [DEBUG] app.py:46 Result: {'name': 'John', 'email': 'john@example.com'} ``` ### Production Configuration ```python settings = LogSettings( minimum_level=LogLevel.WARN, # Only important issues console_enabled=False, persist=True ) ``` Output: ``` [WARN] Cache miss, fetching from database [ERROR] Failed to process payment [CRITICAL] Database connection lost ``` ### Staging Configuration ```python settings = LogSettings( minimum_level=LogLevel.INFO, # Balance of detail console_enabled=True, include_caller_info=False ) ``` ## Logging with Exceptions Include exception details with ERROR and CRITICAL: ```python try: user = database.get_user(user_id) except ValueError as e: Log.error(f"Invalid user ID: {user_id}", exception=e) except Exception as e: Log.critical("Unexpected error retrieving user", exception=e) ``` The exception stack trace is automatically included. ## Contextual Logging Combine levels with context for better insights: ```python def process_payment(payment_id, amount): context = {"payment_id": payment_id, "amount": amount} Log.with_context("operation", "payment").debug( f"Processing payment: {amount}" ) try: result = stripe.charge(amount) Log.with_context("operation", "payment").info( f"Payment processed: {result}" ) except stripe.StripeError as e: Log.with_context("operation", "payment").error( f"Payment failed: {e}", exception=e ) ``` ## Filtering Patterns ### Log Errors and Critical Only ```python settings = LogSettings(minimum_level=LogLevel.ERROR) Log.initialize(settings) ``` ### Log Warnings and Above ```python settings = LogSettings(minimum_level=LogLevel.WARN) Log.initialize(settings) ``` ### Log Everything ```python settings = LogSettings(minimum_level=LogLevel.TRACE) Log.initialize(settings) ``` ## Performance Considerations Log level filtering happens before sending logs, reducing network and storage overhead: ```python # Expensive operations only log in DEBUG if settings.minimum_level <= LogLevel.DEBUG: Log.debug(f"Heavy computation: {expensive_function()}") ``` Better approach - ByteHide handles this: ```python # Always safe - only executed if DEBUG level is enabled Log.debug(f"Expensive debug info: {data}") ``` ## Best Practices 1. **Development** - Use `DEBUG` to see all operation details 2. **Staging** - Use `INFO` for normal operations, catch issues before production 3. **Production** - Use `WARN` to focus on important issues only 4. **Debugging** - Temporarily lower level to `TRACE` when investigating 5. **Performance** - Use higher levels (`WARN`, `ERROR`) to reduce log volume ## Dynamic Level Adjustment Adjust log levels at runtime: ```python def set_debug_mode(enabled): if enabled: Log.initialize(LogSettings(minimum_level=LogLevel.DEBUG)) else: Log.initialize(LogSettings(minimum_level=LogLevel.INFO)) ``` ## Next Steps - [Quick Start](/platforms/python/core/quick-start/) - Start logging - [Configuration](/platforms/python/core/configuration/) - All configuration options - [Console Output](/platforms/python/configuration/console-output/) - Customize console display --- # Project Token # Project Token Your project token is the authentication credential that connects your Python application to your ByteHide Logs project. ## Getting Your Token 1. Log in to the [ByteHide Dashboard](https://dashboard.bytehide.com) 2. Navigate to your Logs project 3. Go to **Settings** → **Project Token** 4. Copy your token (starts with `bh_` prefix) ## Setting the Project Token ### Direct Configuration Set the token directly in your code: ```python from bytehide_logs import Log Log.set_project_token("bh_your_project_token_here") ``` **Note:** This approach should only be used in development. For production, use environment variables. ### Environment Variables ByteHide Logs checks two environment variables in order: 1. `PROJECT_TOKEN` - Custom environment variable 2. `BYTEHIDE_PROJECT_TOKEN` - Standard ByteHide variable ```bash # Using PROJECT_TOKEN export PROJECT_TOKEN="bh_your_token" # Or using BYTEHIDE_PROJECT_TOKEN export BYTEHIDE_PROJECT_TOKEN="bh_your_token" # Run your application python app.py ``` Your application code: ```python from bytehide_logs import Log, LogSettings # Token will be automatically loaded from environment Log.initialize(LogSettings(console_enabled=True)) ``` ### In Python Code Read the token from environment if set: ```python import os from bytehide_logs import Log, LogSettings token = os.getenv("PROJECT_TOKEN") or os.getenv("BYTEHIDE_PROJECT_TOKEN") if not token: raise ValueError("Project token not found in environment variables") Log.set_project_token(token) Log.initialize(LogSettings(console_enabled=True)) ``` ## Security Best Practices ### Never Hardcode Tokens Avoid committing tokens to version control: ```python # Bad - Never do this Log.set_project_token("bh_abc123def456") # Good - Use environment variables Log.set_project_token(os.getenv("PROJECT_TOKEN")) ``` ### Use `.env` Files in Development Create a `.env` file locally (never commit it): ```bash # .env PROJECT_TOKEN=bh_your_development_token # .gitignore .env ``` Load it in your development environment: ```bash source .env python app.py ``` ### Environment-Specific Tokens Use different tokens for different environments: ```python import os def get_project_token(): """Get appropriate token based on environment""" env = os.getenv("ENV", "development") if env == "production": return os.getenv("PRODUCTION_TOKEN") elif env == "staging": return os.getenv("STAGING_TOKEN") else: return os.getenv("DEVELOPMENT_TOKEN") Log.set_project_token(get_project_token()) ``` ### Rotate Tokens Regularly Periodically rotate your project tokens for security: 1. Generate a new token in the ByteHide Dashboard 2. Update all applications with the new token 3. Verify the new token is working 4. Revoke the old token ## Docker Configuration Pass the token as an environment variable to your container: ```dockerfile FROM python:3.9 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . CMD ["python", "app.py"] ``` Run with token: ```bash docker run -e PROJECT_TOKEN="bh_your_token" myapp ``` Or in `docker-compose.yml`: ```yaml version: '3' services: app: build: . environment: - PROJECT_TOKEN=${PROJECT_TOKEN} ``` Run with: ```bash PROJECT_TOKEN="bh_your_token" docker-compose up ``` ## Kubernetes Configuration Store the token in a Kubernetes Secret: ```bash kubectl create secret generic bytehide-secret --from-literal=project-token=bh_your_token ``` Reference in your deployment: ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: myapp spec: template: spec: containers: - name: app image: myapp:latest env: - name: PROJECT_TOKEN valueFrom: secretKeyRef: name: bytehide-secret key: project-token ``` ## Token Validation Verify your token is correctly set and working: ```python from bytehide_logs import Log, LogSettings try: Log.set_project_token("bh_your_token") settings = LogSettings(console_enabled=True) Log.initialize(settings) Log.info("Token validation successful") except Exception as e: print(f"Token validation failed: {e}") ``` ## Troubleshooting ### "Invalid project token" - Verify the token is copied correctly from the dashboard - Ensure the token format matches (should start with `bh_`) - Check that the project hasn't been deleted ### Token not loading from environment ```python import os print(f"PROJECT_TOKEN: {os.getenv('PROJECT_TOKEN')}") print(f"BYTEHIDE_PROJECT_TOKEN: {os.getenv('BYTEHIDE_PROJECT_TOKEN')}") ``` ### Multiple environments Use configuration files or separate settings by environment: ```python import os from pathlib import Path def load_config(): env = os.getenv("ENV", "development") config_file = Path(f"config.{env}.py") if config_file.exists(): exec(config_file.read_text()) return PROJECT_TOKEN ``` ## Next Steps - [Quick Start](/platforms/python/core/quick-start/) - Initialize logging - [Configuration](/platforms/python/core/configuration/) - Configure all settings - [Environment Variables](/platforms/python/configuration/environment-variables/) - Learn about all env vars --- # Configuration # Configuration Configure ByteHide Logs using the `LogSettings` class to customize logging behavior across your application. ## LogSettings Class The `LogSettings` class provides a comprehensive configuration interface for all logging features: ```python from bytehide_logs import LogSettings, LogLevel, RollingInterval from datetime import timedelta settings = LogSettings( console_enabled=True, minimum_level=LogLevel.INFO, include_caller_info=True, persist=False, file_path="/var/log/app.log", rolling_interval=RollingInterval.DAY, roll_on_file_size_limit=True, file_size_limit_bytes=10485760, # 10MB mask_sensitive_data=["password", "token", "api_key"], duplicate_suppression_window=timedelta(seconds=5) ) ``` ## Properties Reference | Property | Type | Default | Description | |---|---|---|---| | `console_enabled` | `bool` | `True` | Enable logging to console | | `minimum_level` | `LogLevel` | `LogLevel.INFO` | Minimum log level to record | | `include_caller_info` | `bool` | `False` | Include filename and line number | | `persist` | `bool` | `False` | Persist logs to file | | `file_path` | `str` | `None` | Path to log file | | `rolling_interval` | `RollingInterval` | `RollingInterval.DAY` | Rotation interval for log files | | `roll_on_file_size_limit` | `bool` | `False` | Rotate when file size exceeded | | `file_size_limit_bytes` | `int` | `104857600` | Maximum file size (100MB) | | `mask_sensitive_data` | `list` | `[]` | Keywords to mask in logs | | `duplicate_suppression_window` | `timedelta` | `None` | Suppress duplicate messages window | ## Usage Examples ### Minimal Configuration ```python from bytehide_logs import Log, LogSettings settings = LogSettings(console_enabled=True) Log.initialize(settings) ``` ### Production Configuration ```python from bytehide_logs import Log, LogSettings, LogLevel, RollingInterval from datetime import timedelta settings = LogSettings( console_enabled=False, # Disable console output persist=True, # Enable file logging file_path="/var/log/myapp/app.log", minimum_level=LogLevel.WARN, # Only WARN and above include_caller_info=True, # Include source information rolling_interval=RollingInterval.DAY, # Rotate daily roll_on_file_size_limit=True, # Also rotate on size file_size_limit_bytes=52428800, # 50MB mask_sensitive_data=["password", "token", "api_key", "secret"], duplicate_suppression_window=timedelta(seconds=10) ) Log.set_project_token("your-project-token") Log.initialize(settings) ``` ### Development Configuration ```python from bytehide_logs import Log, LogSettings, LogLevel settings = LogSettings( console_enabled=True, # See logs in console minimum_level=LogLevel.DEBUG, # All messages include_caller_info=True, # Know where logs come from persist=False # No file persistence ) Log.initialize(settings) ``` ### Combined Console and File ```python from bytehide_logs import Log, LogSettings, LogLevel, RollingInterval settings = LogSettings( console_enabled=True, # Output to console persist=True, # Also write to file file_path="./logs/app.log", minimum_level=LogLevel.INFO, rolling_interval=RollingInterval.HOUR, include_caller_info=True ) Log.initialize(settings) ``` ## Log Levels ByteHide Logs supports six severity levels: ```python from bytehide_logs import LogLevel LogLevel.TRACE # Detailed debugging information LogLevel.DEBUG # Diagnostic information LogLevel.INFO # General informational messages LogLevel.WARN # Warning messages LogLevel.ERROR # Error messages LogLevel.CRITICAL # Critical system failures ``` ## Sensitive Data Masking Protect sensitive information by specifying keywords that should be masked: ```python settings = LogSettings( mask_sensitive_data=[ "password", "api_key", "token", "secret", "credit_card", "ssn" ] ) ``` Any log message containing these keywords will have the values masked with `***`. ## Duplicate Suppression Suppress identical log messages within a time window: ```python from datetime import timedelta settings = LogSettings( duplicate_suppression_window=timedelta(seconds=5) ) Log.initialize(settings) Log.warn("Database timeout") # Logged Log.warn("Database timeout") # Suppressed (within 5 seconds) Log.warn("Database timeout") # Logged (after 5 second window) ``` ## Caller Information Include the filename and line number in logs: ```python settings = LogSettings(include_caller_info=True) # Output will include: app.py:42 [INFO] Message ``` ## Rolling Intervals Control how log files rotate with `RollingInterval`: ```python from bytehide_logs import RollingInterval RollingInterval.MINUTE # Rotate every minute RollingInterval.HOUR # Rotate every hour RollingInterval.DAY # Rotate daily RollingInterval.WEEK # Rotate weekly RollingInterval.MONTH # Rotate monthly RollingInterval.YEAR # Rotate yearly ``` ## Next Steps - [Quick Start](/platforms/python/core/quick-start/) - Initialize logging in your app - [Project Token](/platforms/python/configuration/project-token/) - Configure credentials - [File Logging](/platforms/python/configuration/file-logging/) - Advanced file configuration --- # Installation # Installation Get up and running with ByteHide Logs for Python in minutes. ## Requirements - **Python 3.7 or higher** - Ensure you have a compatible Python version - **pip** - Python package manager (usually included with Python) Check your Python version: ```bash python --version ``` ## Install the SDK Install the `bytehide-logs` package using pip: ```bash pip install bytehide-logs ``` For a specific version: ```bash pip install bytehide-logs==1.0.0 ``` ## Verify Installation Create a test script to verify the installation: ```python from bytehide_logs import Log, LogSettings, LogLevel # Verify imports work print("ByteHide Logs installed successfully!") # Initialize with basic settings Log.set_project_token("test-token") Log.initialize(LogSettings( console_enabled=True, minimum_level=LogLevel.INFO )) # Test logging Log.info("Verification successful - ready to log!") ``` Run the verification script: ```bash python verify_installation.py ``` Expected output: ``` ByteHide Logs installed successfully! Verification successful - ready to log! ``` ## Installation Variations ### Using Requirements File Add to `requirements.txt`: ``` bytehide-logs>=1.0.0 ``` Then install: ```bash pip install -r requirements.txt ``` ### Development Installation Clone the repository and install in editable mode: ```bash git clone https://github.com/bytehide/bytehide-logs-python.git cd bytehide-logs-python pip install -e . ``` ### With Optional Dependencies Install with extra features: ```bash # Development dependencies pip install bytehide-logs[dev] # All extras pip install bytehide-logs[all] ``` ## Python Version Compatibility ByteHide Logs supports Python 3.7 and later: | Python Version | Supported | |---|---| | Python 3.7 | ✓ | | Python 3.8 | ✓ | | Python 3.9 | ✓ | | Python 3.10 | ✓ | | Python 3.11 | ✓ | | Python 3.12 | ✓ | ## Next Steps After installation, proceed to: 1. [Quick Start](/platforms/python/core/quick-start/) - Get logging running in your application 2. [Configuration](/platforms/python/core/configuration/) - Configure logging behavior 3. [Set Project Token](/platforms/python/configuration/project-token/) - Configure your credentials ## Troubleshooting ### "No module named 'bytehide_logs'" Make sure the package is installed in the correct Python environment: ```bash pip install bytehide-logs python -c "import bytehide_logs; print(bytehide_logs.__version__)" ``` ### Version Compatibility Issues If you encounter compatibility issues, try installing a specific version: ```bash pip install bytehide-logs==1.0.0 --force-reinstall ``` ### Virtual Environment Recommendation Always use a virtual environment to avoid dependency conflicts: ```bash # Create virtual environment python -m venv venv # Activate source venv/bin/activate # On Windows: venv\Scripts\activate # Install pip install bytehide-logs ``` ## Support For installation issues, visit the [Support Portal](https://support.bytehide.com). --- # Quick Start # Quick Start Get logging running in your Python application in under 5 minutes. ## Step 1: Set Your Project Token Get your project token from the [ByteHide Dashboard](https://dashboard.bytehide.com) and set it in your application: ```python from bytehide_logs import Log Log.set_project_token("your-project-token-here") ``` ## Step 2: Initialize Logging Create and configure a `LogSettings` object, then initialize: ```python from bytehide_logs import Log, LogSettings settings = LogSettings(console_enabled=True) Log.initialize(settings) ``` ## Step 3: Start Logging Use any of the six log levels: ```python Log.trace("Detailed trace information") Log.debug("Debug message") Log.info("Information message") Log.warn("Warning message") Log.error("Error message") Log.critical("Critical error") ``` ## Complete Example ```python from bytehide_logs import Log, LogSettings, LogLevel if __name__ == "__main__": # 1. Configure token Log.set_project_token("your-project-token") # 2. Initialize settings settings = LogSettings( console_enabled=True, minimum_level=LogLevel.INFO, include_caller_info=True ) Log.initialize(settings) # 3. Start logging Log.info("Application starting") try: # Your application code result = 10 / 2 Log.info(f"Calculation result: {result}") except Exception as e: Log.error("Calculation failed", exception=e) finally: Log.info("Application shutdown") Log.flush() ``` ## Adding Context Make your logs more useful with contextual information: ### Tags Tag logs for easy filtering: ```python Log.with_tags("auth", "user").info("User logged in") ``` ### Custom Context Add key-value data to logs: ```python Log.with_context("user_id", "12345").info("Action performed") ``` ### Correlation ID Track requests across multiple logs: ```python Log.with_correlation_id("req-789").info("Request started") ``` ### Chaining Combine multiple contexts: ```python Log.with_tags("api").with_context("endpoint", "/users").with_correlation_id("req-123").info("API call") ``` ## User Identification Track logs by authenticated users: ```python from bytehide_logs import AuthUser user = AuthUser( id="user-123", email="user@example.com", token="user-token" ) Log.identify(user, update_previous_logs=True) Log.info("User action logged") # Later, when user logs out Log.logout() ``` ## File Logging Enable file persistence with rotation: ```python from bytehide_logs import Log, LogSettings, RollingInterval settings = LogSettings( console_enabled=True, persist=True, file_path="./logs/app.log", rolling_interval=RollingInterval.DAY ) Log.initialize(settings) ``` ## Production Setup ```python from bytehide_logs import Log, LogSettings, LogLevel, RollingInterval import os if __name__ == "__main__": # Get token from environment token = os.getenv("PROJECT_TOKEN") if not token: raise ValueError("PROJECT_TOKEN environment variable not set") Log.set_project_token(token) # Production settings settings = LogSettings( console_enabled=False, # Disable console in production persist=True, file_path="/var/log/myapp/app.log", minimum_level=LogLevel.INFO, include_caller_info=True, rolling_interval=RollingInterval.DAY, roll_on_file_size_limit=True, file_size_limit_bytes=52428800, # 50MB mask_sensitive_data=["password", "api_key", "token"] ) Log.initialize(settings) try: # Application code Log.info("Application started") # ... your application logic ... except Exception as e: Log.error("Application error", exception=e) finally: Log.flush() ``` ## Environment-Based Configuration ```python import os from bytehide_logs import Log, LogSettings, LogLevel def setup_logging(): env = os.getenv("ENV", "development") Log.set_project_token(os.getenv("PROJECT_TOKEN")) if env == "production": settings = LogSettings( console_enabled=False, persist=True, minimum_level=LogLevel.WARN ) else: settings = LogSettings( console_enabled=True, persist=False, minimum_level=LogLevel.DEBUG ) Log.initialize(settings) if __name__ == "__main__": setup_logging() Log.info("Running in production" if os.getenv("ENV") == "production" else "Running in development") ``` ## Common Patterns ### Exception Logging with Context ```python try: user_id = "user-123" result = process_user(user_id) except Exception as e: Log.error( "Failed to process user", exception=e, context={ "user_id": user_id, "operation": "process_user" } ) ``` ### Sensitive Data Protection ```python settings = LogSettings( mask_sensitive_data=["password", "token", "api_key"] ) # This will be automatically masked Log.info(f"Login attempt with password: {user_password}") # Output: Login attempt with password: *** ``` ### Request Tracking ```python def handle_request(request_id, user_id): with_correlation_id = Log.with_correlation_id(request_id) with_correlation_id.info("Request received") with_correlation_id.with_context("user_id", user_id).info("Processing") with_correlation_id.info("Request completed") ``` ## Next Steps - [Configuration](/platforms/python/core/configuration/) - Customize all settings - [Project Token](/platforms/python/configuration/project-token/) - Learn about token management - [Log Levels](/platforms/python/configuration/levels/) - Understand log filtering - [File Logging](/platforms/python/configuration/file-logging/) - Advanced file configuration --- # Create a Logs Project # Create a Logs Project ByteHide Logs helps you capture, analyze, and manage application logs in Python with enterprise-grade features like log rotation, filtering, and sensitive data masking. ## Getting Started To start logging in your Python application: 1. **Create a Project** - Sign up on the [ByteHide Dashboard](https://dashboard.bytehide.com) and create a new Logs project 2. **Get Your Token** - Copy your project token from the project settings 3. **Install the SDK** - Add the `bytehide-logs` package to your application 4. **Configure Logging** - Set up logging with your project token and desired outputs ## Quick Setup ```python from bytehide_logs import Log, LogSettings # Set your project token Log.set_project_token("your-project-token") # Initialize with default settings Log.initialize(LogSettings(console_enabled=True)) # Start logging Log.info("Application started successfully") ``` ## Key Features - **Multiple Output Targets** - Log to console, files, or both - **Intelligent Rotation** - Automatic log file rotation by time or size - **Log Levels** - Control verbosity with DEBUG, INFO, WARN, ERROR, and CRITICAL levels - **Sensitive Data Protection** - Automatically mask credentials and PII - **Contextual Logging** - Add tags, correlation IDs, and custom context - **User Identification** - Track logs by authenticated users - **Performance** - Minimal overhead with async operations - **Environment Integration** - Works with Docker, Kubernetes, and cloud platforms ## Documentation Structure - [Installation](/platforms/python/core/installation/) - Add bytehide-logs to your project - [Configuration](/platforms/python/core/configuration/) - Configure LogSettings and behavior - [Quick Start](/platforms/python/core/quick-start/) - Get logging running in minutes - [Project Token](/platforms/python/configuration/project-token/) - Securely manage your credentials - [Log Levels](/platforms/python/configuration/levels/) - Filter logs by severity - [Console Output](/platforms/python/configuration/console-output/) - Direct logging to console - [File Logging](/platforms/python/configuration/file-logging/) - Write logs to rotating files - [Environment Variables](/platforms/python/configuration/environment-variables/) - Configure via environment - [Disable Logging](/platforms/python/configuration/disable-logging/) - Control logging at runtime ## What's Next? Choose your next step based on your needs: - **New to ByteHide Logs?** Start with [Installation](/platforms/python/core/installation/) - **Ready to log?** Jump to [Quick Start](/platforms/python/core/quick-start/) - **Need specific features?** Check out the configuration guides ## Support For issues, questions, or feature requests, visit the [ByteHide Support Portal](https://support.bytehide.com). --- # Basic Logging # Basic Logging The ByteHide Logs SDK for Python provides six logging levels that cover the full spectrum of application events, from debug information to critical errors. ## Logging Levels The SDK supports the standard logging levels: ```python from bytehide_logs import Log, LogLevel # Debug level - detailed information for debugging Log.debug("Application started in development mode") # Info level - general informational messages Log.info("User login successful") # Warning level - warning messages about potential issues Log.warning("API rate limit approaching: 95% used") # Error level - error messages for recoverable errors Log.error("Failed to connect to database") # Critical level - critical messages for severe errors Log.critical("Payment processing service unavailable") # Trace level - extremely detailed diagnostic information Log.trace("Processing request in authentication middleware") ``` ## Logging with Exception Handling Capture exception details automatically using the `exception` parameter: ```python try: result = perform_payment() except Exception as e: Log.error("Payment processing failed", exception=e) ``` The SDK automatically captures: - Exception type and message - Full stack trace - Exception chain (if applicable) ## Logging with Context Add contextual data to your log entries using the `context` parameter: ```python Log.error( "Database query failed", exception=query_exception, context={ "query": "SELECT * FROM users WHERE id = ?", "database": "production", "retry_count": 3 } ) ``` Context helps with: - Debugging specific issues - Correlating related logs - Understanding the state when an error occurred ## Fluent Syntax Chain multiple configuration methods together for expressive logging: ```python Log.with_tags("payment", "stripe") \ .with_context("transaction_id", "txn_123456") \ .with_context("amount_cents", 9999) \ .info("Payment processed successfully") ``` Fluent syntax allows you to: - Add multiple tags in a single call - Build up context progressively - Write readable, self-documenting logs ## Fluent vs Direct Methods Choose the style that fits your workflow: ```python # Fluent style - method chaining Log.with_tags("auth").with_context("user_id", 42).info("Login successful") # Direct style - straightforward Log.info("Login successful", context={"user_id": 42}) ``` Both approaches are equally supported and produce identical log entries. ## Complete Example ```python from bytehide_logs import Log def process_order(order_id, user_id): """Process a customer order with comprehensive logging.""" try: Log.info(f"Starting order processing for order {order_id}") # Perform order validation validate_order(order_id) # Process payment payment_result = process_payment(order_id) Log.with_tags("order", "payment") \ .with_context("order_id", order_id) \ .with_context("payment_id", payment_result.id) \ .info("Order processed successfully") except ValidationError as e: Log.warning( f"Order validation failed for order {order_id}", exception=e, context={"order_id": order_id} ) raise except PaymentError as e: Log.error( f"Payment processing failed for order {order_id}", exception=e, context={ "order_id": order_id, "user_id": user_id, "retry_attempt": 1 } ) raise ``` ## Next Steps - Learn about [exception handling](/platforms/python/products/logs/exception-handling/) for comprehensive error logging - Explore [tags](/platforms/python/products/logs/tags/) to organize logs by categories - Discover [correlation IDs](/platforms/python/products/logs/correlation-ids/) for request tracking --- # Correlation IDs # Correlation IDs Correlation IDs link related logs across requests, services, and time boundaries. They are essential for understanding the flow of a transaction through your entire system. ## What Are Correlation IDs? A correlation ID is a unique identifier that tracks a single logical operation (like a user request) as it flows through multiple services, threads, or time periods. Instead of searching for scattered logs with common attributes, you can track a single ID. ## Adding Correlation IDs Use `with_correlation_id()` to associate logs with a tracking ID: ```python from bytehide_logs import Log correlation_id = "req_12345_xyz" Log.with_correlation_id(correlation_id).info("Request started") Log.with_correlation_id(correlation_id).info("Processing request") Log.with_correlation_id(correlation_id).info("Request completed") ``` All logs with the same correlation ID can be queried together: ``` correlation_id:req_12345_xyz ``` ## Generating Correlation IDs Create correlation IDs at the entry point of your application: ```python import uuid from bytehide_logs import Log def handle_http_request(request): """Handle incoming HTTP request with correlation ID.""" # Generate unique ID for this request correlation_id = str(uuid.uuid4()) Log.with_correlation_id(correlation_id).info( "Request received", context={ "method": request.method, "path": request.path, "client_ip": request.remote_addr } ) try: result = process_request(request, correlation_id) Log.with_correlation_id(correlation_id).info("Request completed successfully") return result except Exception as e: Log.with_correlation_id(correlation_id).error( "Request failed", exception=e ) raise ``` ## Request Tracking Flow Track a request through multiple services: ```python from bytehide_logs import Log def api_endpoint(request): """API endpoint that calls multiple services.""" correlation_id = request.headers.get("X-Correlation-ID", generate_id()) # Log receiving request Log.with_correlation_id(correlation_id).info("API request received") # Call authentication service user = auth_service.authenticate(correlation_id) Log.with_correlation_id(correlation_id).info("User authenticated") # Call business logic service result = business_service.process(user.id, correlation_id) Log.with_correlation_id(correlation_id).info("Business logic completed") # Return response return {"data": result} def auth_service_authenticate(correlation_id): """Authentication service logs with correlation ID.""" Log.with_correlation_id(correlation_id).info("Verifying credentials") # ... authentication logic ... Log.with_correlation_id(correlation_id).info("Authentication successful") def business_service_process(user_id, correlation_id): """Business service logs with correlation ID.""" Log.with_correlation_id(correlation_id).info(f"Processing request for user {user_id}") # ... business logic ... Log.with_correlation_id(correlation_id).info("Processing complete") ``` ## Combining with Other Context Use correlation IDs alongside tags, user context, and other metadata: ```python Log.identify(user) \ .with_tags("order", "processing") \ .with_correlation_id("req_98765") \ .with_context("order_id", "ord_42") \ .info("Order processing started") ``` ## Correlation IDs in Microservices Pass correlation IDs between services: ```python from bytehide_logs import Log import requests def call_downstream_service(service_url, correlation_id, data): """Call another service with correlation ID.""" headers = { "X-Correlation-ID": correlation_id, "Content-Type": "application/json" } Log.with_correlation_id(correlation_id).info( f"Calling downstream service: {service_url}" ) try: response = requests.post(service_url, json=data, headers=headers) Log.with_correlation_id(correlation_id).info( "Downstream service responded", context={"status_code": response.status_code} ) return response.json() except Exception as e: Log.with_correlation_id(correlation_id).error( "Downstream service call failed", exception=e ) raise ``` Ensure downstream services extract and use the correlation ID: ```python def downstream_endpoint(request): """Downstream service endpoint.""" # Extract correlation ID from request header correlation_id = request.headers.get("X-Correlation-ID") Log.with_correlation_id(correlation_id).info("Processing request") # Process request... Log.with_correlation_id(correlation_id).info("Request processing complete") return response ``` ## Correlation IDs with Asynchronous Operations Track asynchronous tasks with correlation IDs: ```python from bytehide_logs import Log import asyncio async def process_order_async(order_id, correlation_id): """Process order asynchronously with correlation tracking.""" Log.with_correlation_id(correlation_id).info("Starting async order processing") try: # Validate order Log.with_correlation_id(correlation_id).info("Validating order") await validate_order_async(order_id) # Process payment Log.with_correlation_id(correlation_id).info("Processing payment") payment_result = await process_payment_async(order_id) # Ship order Log.with_correlation_id(correlation_id).info("Shipping order") await ship_order_async(order_id) Log.with_correlation_id(correlation_id).info("Order processing complete") except Exception as e: Log.with_correlation_id(correlation_id).error( "Async order processing failed", exception=e ) raise ``` ## Correlation ID Format Use consistent formats for correlation IDs: ```python import uuid from datetime import datetime # UUID-based (recommended) correlation_id = str(uuid.uuid4()) # "550e8400-e29b-41d4-a716-446655440000" # Request-based with timestamp correlation_id = f"req_{datetime.utcnow().timestamp()}_{random_string()}" # Service-based identifier correlation_id = f"svc_payment_{order_id}_{uuid.uuid4().hex[:8]}" # Simple incrementing ID (in high-throughput systems, use UUID instead) correlation_id = f"req_{request_counter}" ``` ## Best Practices **Generate correlation IDs early:** ```python # Good - generate at application entry point def handle_request(request): correlation_id = generate_or_extract_correlation_id(request) # ... rest of processing ... ``` **Pass correlation IDs to all downstream calls:** ```python # Good - explicit passing result = downstream_service(data, correlation_id=correlation_id) # Avoid - implicit global state (harder to test) global CURRENT_CORRELATION_ID CURRENT_CORRELATION_ID = correlation_id ``` **Use consistent header names:** ```python # Good - standard header name correlation_id = request.headers.get("X-Correlation-ID") # Document your convention """ Standard headers: - X-Correlation-ID: Unique request identifier - X-Request-ID: Alias for X-Correlation-ID """ ``` **Include correlation ID in error responses:** ```python def error_response(error, correlation_id): """Return error response with correlation ID for support.""" return { "error": str(error), "correlation_id": correlation_id, "message": "Please reference this ID when contacting support" } ``` ## Complete Example ```python from bytehide_logs import Log import uuid def handle_checkout(request): """Complete checkout flow with correlation ID tracking.""" # Generate correlation ID correlation_id = request.headers.get("X-Correlation-ID", str(uuid.uuid4())) Log.with_correlation_id(correlation_id).info("Checkout initiated") try: # Identify user user = authenticate_user(request) Log.identify(user) # Start transaction Log.with_correlation_id(correlation_id).info("Starting payment transaction") transaction = start_transaction() # Validate cart Log.with_correlation_id(correlation_id).info("Validating shopping cart") cart = validate_cart(request) # Process payment Log.with_correlation_id(correlation_id).info("Processing payment") payment = process_payment(user, cart, transaction) # Fulfill order Log.with_correlation_id(correlation_id).info("Fulfilling order") order = create_order(user, cart, payment) Log.with_correlation_id(correlation_id).info("Checkout completed successfully") return { "order_id": order.id, "correlation_id": correlation_id } except Exception as e: Log.with_correlation_id(correlation_id).error( "Checkout failed", exception=e, context={"step": "payment"} ) return {"error": "Checkout failed", "correlation_id": correlation_id} ``` ## Next Steps - Learn about [user identification](/platforms/python/products/logs/user-identification/) to track which users are affected - Explore [tags](/platforms/python/products/logs/tags/) to categorize operations - Discover [metadata context](/platforms/python/products/logs/metadata-context/) to add operational details --- # Data Masking # Data Masking Protect sensitive information by automatically masking fields like passwords, tokens, API keys, and credit card numbers. Data masking ensures compliance and prevents accidental exposure of secrets in logs. ## Configuring Sensitive Fields Use `LogSettings` to specify which fields should be masked: ```python from bytehide_logs import Log, LogSettings # Configure masking for sensitive fields settings = LogSettings( mask_sensitive_data=["password", "token", "api_key", "secret"] ) Log.configure(settings) # Now these fields are automatically masked Log.info("User authentication", context={ "username": "alice@example.com", "password": "super_secret_123", # Will be masked "api_key": "sk_live_abc123xyz" # Will be masked }) ``` ## Common Sensitive Fields Standard fields to mask in most applications: ```python settings = LogSettings( mask_sensitive_data=[ # Authentication "password", "token", "refresh_token", "session_token", "auth_token", # API & Services "api_key", "secret_key", "secret", "api_secret", # Payment "credit_card", "card_number", "cvv", "routing_number", "account_number", # Personal "ssn", "social_security_number", "passport_number", # Keys & Certificates "private_key", "signing_key", "certificate", ] ) Log.configure(settings) ``` ## Masking Examples Before and after masking: ```python # Before masking is applied Log.info("Payment processing", context={ "card_number": "4532-1234-5678-9010", "cvv": "123", "amount": 99.99 }) # Output (with mask_sensitive_data=["card_number", "cvv"]): # { # "message": "Payment processing", # "card_number": "****", # "cvv": "****", # "amount": 99.99 # } ``` ## Nested Sensitive Data Masking works with nested context objects: ```python Log.info("Creating API key", context={ "user_id": "user_123", "api_key": "sk_test_4eC39HqLyjWDarhtT657L0df", # Masked "permissions": ["read", "write"], "auth": { "token": "super_secret_xyz", # Masked even in nested objects "expires_at": "2026-12-31" } }) ``` ## Exception Masking Sensitive data in exceptions is also masked: ```python try: authenticate(password="user_secret_pass") except AuthenticationError as e: Log.error( "Authentication failed", exception=e, # Exception message with password is masked context={ "password_attempt": "bad_secret" # Masked } ) ``` ## User Tokens Are Automatically Masked The `AuthUser` token field is automatically masked without explicit configuration: ```python from bytehide_logs import AuthUser user = AuthUser( id="user_123", email="alice@example.com", token="secret_session_token_xyz" # Automatically masked ) Log.identify(user) Log.info("User identified") # Token is masked even without mask_sensitive_data configuration ``` ## Custom Masking Patterns Configure masking for fields with specific patterns: ```python settings = LogSettings( mask_sensitive_data=[ "password", "api_*", # Matches api_key, api_secret, api_token, etc. "*_token", # Matches refresh_token, session_token, auth_token, etc. "*_key", # Matches private_key, public_key, etc. ] ) Log.configure(settings) # All matching fields are masked Log.info("Configuration loaded", context={ "api_key": "secret_key", # Masked by "api_*" "api_secret": "secret_secret", # Masked by "api_*" "refresh_token": "xyz", # Masked by "*_token" "private_key": "abc", # Masked by "*_key" "app_name": "MyApp" # Not masked }) ``` ## Partial Masking Show partial information while masking sensitive data: ```python # Log with partially visible token for debugging Log.info("Token usage", context={ "token": "sk_live_abc123xyz...", # Last part visible "token_prefix": "sk_live", "user_id": "user_456" }) # Query logs with prefix to debug token issues # Query: token_prefix:"sk_live" AND level:error ``` ## Environment Variable Protection Mask environment variables that contain secrets: ```python import os from bytehide_logs import Log, LogSettings # Mask environment-sourced sensitive data api_key = os.environ.get("API_KEY") # From environment settings = LogSettings( mask_sensitive_data=[ "api_key", "database_password", "oauth_secret" ] ) Log.configure(settings) Log.info("Connecting to service", context={ "api_key": api_key, # Masked automatically "service": "external_api" }) ``` ## Database Connection Masking Mask database credentials: ```python settings = LogSettings( mask_sensitive_data=[ "password", "connection_string", "database_url" ] ) Log.configure(settings) Log.info("Database connected", context={ "database_url": "postgresql://user:password@localhost/dbname", # Masked "host": "localhost", "database": "mydb" }) ``` ## API Request/Response Masking Mask sensitive API data: ```python from bytehide_logs import Log, LogSettings settings = LogSettings( mask_sensitive_data=[ "authorization", "bearer_token", "api_key", "credit_card", "sensitive_field" ] ) Log.configure(settings) def make_api_call(api_endpoint, headers, body): """Make API call with sensitive data masking.""" Log.info("Making API request", context={ "endpoint": api_endpoint, "headers": { "authorization": headers.get("Authorization"), # Masked "content_type": "application/json" }, "body_fields": list(body.keys()) # Keys visible, sensitive values masked }) response = requests.post(api_endpoint, json=body, headers=headers) Log.info("API response received", context={ "status_code": response.status_code, "response": response.json() # Sensitive fields masked }) ``` ## Compliance & Security Data masking helps meet compliance requirements: ```python # GDPR & CCPA Compliance # - Protect personally identifiable information # - Prevent accidental exposure in logs # - Simplify log retention policies # Security Best Practices # - Never log plaintext passwords # - Mask authentication credentials # - Protect API keys and secrets # - Redact payment information settings = LogSettings( mask_sensitive_data=[ # GDPR: Personal Information "password", "email_address", "phone_number", # CCPA: Consumer Privacy "credit_card", "ssn", # Security: Credentials "api_key", "secret", "token", ] ) Log.configure(settings) ``` ## Complete Example ```python from bytehide_logs import Log, LogSettings import os # Configure masking for your application settings = LogSettings( mask_sensitive_data=[ "password", "token", "api_key", "secret", "credit_card", "cvv", "authorization", "database_password" ] ) Log.configure(settings) def handle_payment(payment_data): """Handle payment with secure logging.""" # Log operation without exposing sensitive data Log.info("Payment processing initiated", context={ "user_id": payment_data["user_id"], "amount": payment_data["amount"], "credit_card": "****1234", # Safe partial info "card_number": payment_data["card_number"] # Automatically masked }) try: result = process_payment(payment_data) Log.info("Payment successful", context={ "user_id": payment_data["user_id"], "transaction_id": result["transaction_id"] }) except Exception as e: Log.error( "Payment failed", exception=e, context={ "user_id": payment_data["user_id"], "error_details": str(e) # Masked if contains sensitive data } ) def authenticate_api(api_key): """Authenticate with API key (safely logged).""" Log.info("Authenticating with API", context={ "api_key": api_key, # Automatically masked "service": "payment_gateway" }) return authenticate(api_key) ``` ## Next Steps - Learn about [exception handling](/platforms/python/products/logs/exception-handling/) to safely log errors - Explore [user identification](/platforms/python/products/logs/user-identification/) for secure user tracking - Discover [metadata context](/platforms/python/products/logs/metadata-context/) for detailed context management --- # Duplicate Suppression # Duplicate Suppression Prevent log spam by automatically suppressing duplicate log entries within a configurable time window. This is especially useful for repeated errors, warnings, or status messages that would otherwise clutter your logs. ## Understanding Duplicate Suppression Duplicate suppression automatically suppresses identical log messages that occur within a specified time window. Instead of logging the same message 100 times in quick succession, only the first message is logged, with a note about suppressed duplicates. ## Configuring Duplicate Suppression Window Use `LogSettings` to configure the duplicate suppression window with `timedelta`: ```python from bytehide_logs import Log, LogSettings from datetime import timedelta # Suppress duplicate logs within 5-second window settings = LogSettings( duplicate_suppression_window=timedelta(seconds=5) ) Log.configure(settings) # Logging the same message multiple times for i in range(10): Log.warning("Database connection pool at capacity") # Result: First message logged, subsequent 9 messages suppressed within 5 seconds ``` ## Time Window Examples Configure different suppression windows based on your needs: ```python from datetime import timedelta from bytehide_logs import Log, LogSettings # Short window - 1 second (for high-frequency errors) settings = LogSettings(duplicate_suppression_window=timedelta(seconds=1)) Log.configure(settings) # Medium window - 5 seconds (default, recommended) settings = LogSettings(duplicate_suppression_window=timedelta(seconds=5)) Log.configure(settings) # Long window - 1 minute (for infrequent operations) settings = LogSettings(duplicate_suppression_window=timedelta(minutes=1)) Log.configure(settings) # Very long window - 1 hour settings = LogSettings(duplicate_suppression_window=timedelta(hours=1)) Log.configure(settings) # No suppression - infinite window means all duplicates logged settings = LogSettings(duplicate_suppression_window=timedelta(seconds=0)) Log.configure(settings) ``` ## Real-World Examples ### High-Frequency Loop Errors ```python from bytehide_logs import Log, LogSettings from datetime import timedelta settings = LogSettings(duplicate_suppression_window=timedelta(seconds=5)) Log.configure(settings) # Processing many items, some fail for item in items: try: process_item(item) except ProcessingError as e: Log.error("Item processing failed", exception=e) # Without suppression: 1000 identical error messages # With suppression: 1 error message + suppression count ``` ### Monitoring Status Checks ```python import time from bytehide_logs import Log, LogSettings from datetime import timedelta settings = LogSettings(duplicate_suppression_window=timedelta(seconds=10)) Log.configure(settings) # Health check running every second while True: if not service_healthy(): Log.warning("Service health check failed") time.sleep(1) # Without suppression: warning every second (60/minute) # With suppression: warning every 10 seconds + count ``` ### Retry Loop Suppression ```python from bytehide_logs import Log, LogSettings from datetime import timedelta import time settings = LogSettings(duplicate_suppression_window=timedelta(seconds=5)) Log.configure(settings) def retry_operation(max_retries=10): """Retry operation with suppressed duplicate logs.""" for attempt in range(max_retries): try: return perform_operation() except TemporaryError as e: Log.warning("Operation failed, retrying", context={ "attempt": attempt + 1, "max_retries": max_retries }) time.sleep(0.5) # Without suppression: warning for each retry attempt # With suppression: warning logged once, others suppressed ``` ### Resource Availability Checks ```python from bytehide_logs import Log, LogSettings from datetime import timedelta settings = LogSettings(duplicate_suppression_window=timedelta(seconds=30)) Log.configure(settings) def check_resources(): """Check system resources with duplicate suppression.""" if get_memory_usage() > 90: Log.warning("Memory usage critical", context={ "usage_percent": get_memory_usage() }) if get_disk_usage() > 90: Log.warning("Disk usage critical", context={ "usage_percent": get_disk_usage() }) if get_cpu_usage() > 80: Log.warning("CPU usage high", context={ "usage_percent": get_cpu_usage() }) # Without suppression: continuous warnings every check # With suppression: warning every 30 seconds while condition persists ``` ## Suppression with Tags and Context Different combinations of message, tags, and context are treated as different log entries: ```python from bytehide_logs import Log, LogSettings from datetime import timedelta settings = LogSettings(duplicate_suppression_window=timedelta(seconds=5)) Log.configure(settings) # These are different log entries (not suppressed together) Log.warning("Payment failed", context={"user_id": "user_1"}) Log.warning("Payment failed", context={"user_id": "user_2"}) # These are identical (will be suppressed) Log.warning("Payment failed", context={"user_id": "user_1"}) Log.warning("Payment failed", context={"user_id": "user_1"}) ``` Tags help distinguish different types of repeated messages: ```python # Different tags = different entries Log.with_tags("auth", "failed").warning("Authentication failed") Log.with_tags("payment", "failed").warning("Payment failed") # Same tags = potential duplicates Log.with_tags("auth", "failed").warning("Authentication failed") Log.with_tags("auth", "failed").warning("Authentication failed") # Suppressed ``` ## Monitoring Suppression Track suppressed log counts: ```python from bytehide_logs import Log # Get suppression statistics stats = Log.get_suppression_stats() print(f"Total duplicates suppressed: {stats.total_suppressed}") print(f"Suppression rate: {stats.suppression_rate}%") print(f"Most suppressed message: {stats.most_suppressed_message}") ``` Check if a specific message was suppressed: ```python if Log.was_suppressed("Payment failed", context={"user_id": "123"}): print("This message was suppressed due to duplicates") ``` ## Balancing Information and Noise Choose suppression windows based on: - **Short windows (1-2 seconds)**: High-frequency operations where detailed logging is important - **Medium windows (5-10 seconds)**: Standard applications with periodic checks - **Long windows (30+ seconds)**: Low-frequency operations or background tasks ```python from bytehide_logs import Log, LogSettings from datetime import timedelta # API server - medium suppression api_settings = LogSettings(duplicate_suppression_window=timedelta(seconds=5)) # Background job - long suppression job_settings = LogSettings(duplicate_suppression_window=timedelta(minutes=1)) # Real-time processing - short suppression realtime_settings = LogSettings(duplicate_suppression_window=timedelta(seconds=1)) ``` ## Disabling Suppression Disable duplicate suppression if needed: ```python from bytehide_logs import Log, LogSettings from datetime import timedelta # Disable suppression with zero or None settings = LogSettings(duplicate_suppression_window=timedelta(seconds=0)) Log.configure(settings) # Or use None settings = LogSettings(duplicate_suppression_window=None) Log.configure(settings) ``` ## Complete Example ```python from bytehide_logs import Log, LogSettings from datetime import timedelta import time # Configure suppression for 5 seconds settings = LogSettings( duplicate_suppression_window=timedelta(seconds=5), mask_sensitive_data=["password", "token"] ) Log.configure(settings) def batch_process_records(records): """Process batch of records with intelligent duplicate suppression.""" failed_records = [] for record in records: try: # Process each record validate_record(record) process_record(record) Log.with_tags("batch", "success").info( f"Record {record.id} processed", context={"record_id": record.id} ) except ValidationError as e: # This might happen for many records - will be suppressed Log.warning( "Record validation failed", exception=e, context={"record_id": record.id} ) failed_records.append(record) except ProcessingError as e: # Different error type - not suppressed with validation errors Log.error( "Record processing failed", exception=e, context={"record_id": record.id} ) failed_records.append(record) # Summary Log.info( f"Batch processing complete", context={ "total_records": len(records), "failed_records": len(failed_records), "success_rate": f"{((len(records) - len(failed_records)) / len(records) * 100):.1f}%" } ) return failed_records # Usage records = load_records() failed = batch_process_records(records) ``` ## Best Practices **Use suppression for repeated status messages:** ```python # Good - prevents log spam from repeated status Log.info("Processing batch", context={"batch_id": batch_id}) # Suppressed after first # Avoid - if you need to log each occurrence, use context variations Log.info("Processing item", context={"item_id": item.id}) # Different each time ``` **Set appropriate windows for your system:** ```python # For a typical web server settings = LogSettings(duplicate_suppression_window=timedelta(seconds=5)) # For batch processing settings = LogSettings(duplicate_suppression_window=timedelta(minutes=1)) # For real-time systems settings = LogSettings(duplicate_suppression_window=timedelta(seconds=1)) ``` **Monitor suppression rates:** ```python # If suppression rate is too high, consider: # 1. Longer suppression window # 2. More specific context to differentiate logs # 3. Reducing log frequency at the source ``` ## Next Steps - Learn about [basic logging](/platforms/python/products/logs/basic-logging/) for effective message construction - Explore [tags](/platforms/python/products/logs/tags/) to categorize similar operations - Discover [metadata context](/platforms/python/products/logs/metadata-context/) to make logs more meaningful --- # Exception Handling # Exception Handling Proper exception logging is critical for diagnosing production issues. The ByteHide Logs SDK captures exception details automatically and provides context to understand what went wrong. ## Basic Exception Logging Use the `exception` parameter to log exceptions with full details: ```python from bytehide_logs import Log try: file = open("/path/to/file.txt") except FileNotFoundError as e: Log.error("Configuration file not found", exception=e) ``` The SDK automatically captures: - Exception type (`FileNotFoundError`) - Error message - Complete stack trace - Exception chain (nested exceptions) ## Exception Logging with Context Combine exception information with contextual data: ```python try: database.connect(host=db_host, port=db_port) except ConnectionError as e: Log.error( "Database connection failed", exception=e, context={ "host": db_host, "port": db_port, "timeout_seconds": 30, "environment": "production" } ) ``` Context is essential for understanding: - What operation was being performed - Which resources were involved - Environmental factors that may have contributed ## Try-Except Pattern with Logging Handle exceptions while providing diagnostic information: ```python def fetch_user_data(user_id): """Fetch user from API with error handling and logging.""" try: response = api.get(f"/users/{user_id}") user_data = response.json() Log.info(f"User data retrieved for user {user_id}") return user_data except requests.Timeout as e: Log.warning( f"API timeout retrieving user {user_id}", exception=e, context={"user_id": user_id, "timeout": "30s"} ) return None except requests.HTTPError as e: if e.response.status_code == 404: Log.warning(f"User not found: {user_id}", exception=e) else: Log.error( f"API error retrieving user {user_id}", exception=e, context={"status_code": e.response.status_code} ) return None ``` ## Exception Chaining Log exceptions that cause other exceptions: ```python try: try: result = risky_operation() except OperationError as original_error: raise ProcessingException("Failed to process data") from original_error except ProcessingException as e: Log.error( "Processing failed with chained exceptions", exception=e, context={"operation": "data_processing"} ) ``` The SDK preserves the full exception chain for debugging. ## Selective Error Handling Log different exception types with appropriate levels: ```python def process_payment(payment_data): """Process payment with appropriate error logging levels.""" try: return payment_processor.charge(payment_data) except CardDeclinedError as e: # User error - warning level Log.warning( "Payment card declined", exception=e, context={ "card_last_four": payment_data.get("card_last_four"), "amount": payment_data.get("amount") } ) except InvalidCardError as e: # Validation error - warning level Log.warning( "Invalid card details provided", exception=e, context={"field": e.field} ) except PaymentGatewayError as e: # System error - error level Log.error( "Payment gateway error", exception=e, context={ "gateway": "stripe", "retry_available": True } ) ``` ## Traceback Information Exception tracebacks are automatically included: ```python import traceback try: deeply_nested_function() except Exception as e: # Full traceback is captured automatically Log.error("Unexpected error in nested function call", exception=e) # No need to manually capture traceback ``` The SDK captures: - Function names and line numbers - Local variables (where applicable) - File paths and code context - Complete call stack ## Best Practices **Always include context** when logging exceptions: ```python # Good - includes context try: user = fetch_user(user_id) except Exception as e: Log.error("User fetch failed", exception=e, context={"user_id": user_id}) # Avoid - no context try: user = fetch_user(user_id) except Exception as e: Log.error("User fetch failed", exception=e) ``` **Use appropriate log levels** based on severity: ```python # Recoverable errors - use warning or info Log.warning("Retrying failed request", exception=retry_error) # Unexpected system errors - use error Log.error("Unhandled database error", exception=db_error) # Critical failures - use critical Log.critical("Payment system offline", exception=critical_error) ``` **Log early and specifically** rather than catching broadly: ```python # Good - specific exception with details try: database.execute(query) except DatabaseError as e: Log.error("Query execution failed", exception=e, context={"query_id": query.id}) raise # Avoid - catching everything vaguely try: entire_request_handler() except Exception as e: Log.error("Something went wrong", exception=e) ``` ## Next Steps - Learn about [user identification](/platforms/python/products/logs/user-identification/) to track which users experience errors - Explore [data masking](/platforms/python/products/logs/data-masking/) to protect sensitive information in exception details - Discover [correlation IDs](/platforms/python/products/logs/correlation-ids/) to trace errors across services --- # Fluent Syntax # Fluent Syntax The fluent interface allows you to chain method calls together for expressive, readable logging code. Python's method chaining creates a natural, self-documenting style. ## Method Chaining Basics Chain methods together for elegant code: ```python from bytehide_logs import Log # Fluent chaining Log.with_tags("payment") \ .with_context("transaction_id", "txn_123") \ .with_correlation_id("req_456") \ .info("Payment processed") ``` Each method returns the same Log instance, allowing further method calls: - `Log.with_tags()` - Add tags - `Log.with_context()` - Add context data - `Log.with_correlation_id()` - Add correlation ID - Final logging method - `info()`, `error()`, `warning()`, etc. ## Line Continuation with Backslash Use backslash for line continuation in fluent chains: ```python Log.with_tags("auth", "login") \ .with_context("user_id", "user_123") \ .with_context("ip_address", "192.168.1.1") \ .with_context("timestamp", "2026-03-02T15:30:00Z") \ .info("User login successful") ``` The backslash tells Python the statement continues on the next line. This keeps each method call clear and readable. ## Formatting Chain Patterns Different formatting styles for fluent chains: ### Narrow Column Format (for files with width constraints) ```python Log \ .with_tags("payment") \ .with_context("user_id", "u123") \ .info("Payment complete") ``` ### Indented Format (most readable) ```python Log.with_tags("order") \ .with_context("order_id", "ord_456") \ .with_context("total", 99.99) \ .info("Order placed") ``` ### Compact Format (for simple chains) ```python Log.with_tags("api").with_context("endpoint", "/users").info("API called") ``` ## Building Complex Context Build rich context through fluent chaining: ```python Log.with_tags("checkout", "payment", "card") \ .with_context("customer_id", "cust_789") \ .with_context("amount_cents", 2999) \ .with_context("currency", "USD") \ .with_context("card_last_four", "4242") \ .with_correlation_id("checkout_req_123") \ .info("Credit card processed successfully") ``` ## Multiple Tags in Fluent Style Add multiple tags in a single call: ```python # All tags in one call Log.with_tags("user", "profile", "update").info("Profile updated") # Tags in separate calls (also works) Log.with_tags("user") \ .with_tags("profile") \ .with_tags("update") \ .info("Profile updated") ``` ## Error Logging with Fluent Syntax Build detailed error logs fluently: ```python Log.with_tags("database", "query", "error") \ .with_context("query_id", "q_abc123") \ .with_context("table", "users") \ .with_context("retry_attempt", 2) \ .with_context("max_retries", 3) \ .error("Database query failed", exception=db_error) ``` ## Fluent vs Non-Fluent Styles Both approaches produce identical results: ```python # Fluent style - expressive chaining Log.with_tags("auth") \ .with_context("method", "oauth") \ .with_correlation_id("req_xyz") \ .info("OAuth authentication successful") # Direct style - all at once (if using exception= or context= parameters) Log.info("OAuth authentication successful", context={ "method": "oauth", "tags": ["auth"], "correlation_id": "req_xyz" }) # Mixed style - some methods, some parameters Log.with_tags("auth").info("OAuth authentication successful", context={ "method": "oauth" }) ``` Choose the style that fits your code. The fluent style is often preferred for: - Long chains with many attributes - Progressive building of log entries - Readability in complex operations ## Fluent Syntax in Functions Write helper functions using fluent syntax: ```python from bytehide_logs import Log def log_payment_event(event_type, transaction_id, amount, status="pending"): """Log payment events with fluent syntax.""" return Log.with_tags("payment", event_type) \ .with_context("transaction_id", transaction_id) \ .with_context("amount_cents", amount) \ .with_context("status", status) \ .with_correlation_id(get_current_correlation_id()) # Usage log_payment_event("charge", "txn_123", 5999).info("Payment initiated") log_payment_event("charge", "txn_123", 5999).info("Payment completed") log_payment_event("refund", "txn_123", 5999).warning("Payment refunded") ``` ## Conditional Fluent Chains Build chains conditionally: ```python from bytehide_logs import Log def log_user_action(action, user, **metadata): """Log user action with optional context.""" log_entry = Log.with_tags("user", action) # Add user context if authenticated if user: log_entry = log_entry.with_context("user_id", user.id) if hasattr(user, "email"): log_entry = log_entry.with_context("email", user.email) # Add optional metadata for key, value in metadata.items(): log_entry = log_entry.with_context(key, value) return log_entry # Usage user = get_current_user() log_user_action("login", user, ip="192.168.1.1").info("User logged in") log_user_action("logout", user).info("User logged out") ``` ## Fluent Syntax with Context Manager Combine fluent syntax with Python's context managers: ```python from contextlib import contextmanager from bytehide_logs import Log import time @contextmanager def log_operation(operation_name, **tags): """Log operation start and completion with timing.""" log = Log.with_tags(operation_name, *tags.keys()) \ .with_context("operation", operation_name) for key, value in tags.items(): log = log.with_context(key, value) log.info("Operation started") start_time = time.time() try: yield log finally: elapsed = time.time() - start_time log.with_context("elapsed_ms", int(elapsed * 1000)).info("Operation completed") # Usage with log_operation("data_import", source="csv", count=1000) as log: import_data_from_csv() ``` ## Fluent Syntax with Exceptions Chain methods while logging exceptions: ```python from bytehide_logs import Log try: risky_operation() except PaymentError as e: Log.with_tags("payment", "error") \ .with_context("error_code", e.code) \ .with_context("retry_available", e.retry_available) \ .with_correlation_id(get_correlation_id()) \ .error("Payment processing failed", exception=e) except Exception as e: Log.with_tags("error", "unexpected") \ .with_context("error_type", type(e).__name__) \ .error("Unexpected error occurred", exception=e) ``` ## Fluent Syntax in Loops Log repetitive operations fluently: ```python from bytehide_logs import Log for item in items: try: result = process_item(item) Log.with_tags("batch", "item") \ .with_context("item_id", item.id) \ .with_context("batch_id", batch_id) \ .with_context("result", result) \ .info("Item processed successfully") except Exception as e: Log.with_tags("batch", "item", "error") \ .with_context("item_id", item.id) \ .with_context("batch_id", batch_id) \ .error("Item processing failed", exception=e) ``` ## Formatting Guidelines For consistent fluent syntax formatting: **Use backslash continuation for clarity:** ```python # Good - clear method order Log.with_tags("operation") \ .with_context("key", value) \ .with_correlation_id("id") \ .info("Message") ``` **Keep lines within reasonable width (80-100 characters):** ```python # Good - readable line length Log.with_tags("auth") \ .with_context("user_id", user_id) \ .info("Authentication successful") # Avoid - very long single line Log.with_tags("auth").with_context("user_id", user_id).with_context("auth_method", "oauth").with_context("timestamp", current_time).info("Authentication successful") ``` **Align continuations for readability:** ```python # Good - aligned indentation Log.with_tags("payment", "stripe") \ .with_context("amount", 9999) \ .with_context("currency", "USD") \ .info("Charge created") ``` ## Complete Example ```python from bytehide_logs import Log, LogSettings, AuthUser from datetime import timedelta import uuid # Configure logging settings = LogSettings( duplicate_suppression_window=timedelta(seconds=5), mask_sensitive_data=["password", "token", "api_key"] ) Log.configure(settings) def process_user_order(order_id, user_email, payment_token): """Process user order with fluent logging.""" # Generate tracking IDs correlation_id = str(uuid.uuid4()) user = AuthUser(id=order_id, email=user_email, token=payment_token) # Identify user Log.identify(user) # Log order start Log.with_tags("order", "processing") \ .with_context("order_id", order_id) \ .with_context("user_email", user_email) \ .with_correlation_id(correlation_id) \ .info("Order processing initiated") try: # Validate order Log.with_tags("order", "validation") \ .with_context("order_id", order_id) \ .with_correlation_id(correlation_id) \ .info("Validating order details") validate_order(order_id) # Process payment Log.with_tags("order", "payment", "stripe") \ .with_context("order_id", order_id) \ .with_context("amount_cents", get_order_total(order_id)) \ .with_correlation_id(correlation_id) \ .info("Processing payment with Stripe") payment_result = process_stripe_payment(order_id) # Create shipment Log.with_tags("order", "fulfillment") \ .with_context("order_id", order_id) \ .with_context("transaction_id", payment_result.id) \ .with_correlation_id(correlation_id) \ .info("Creating shipment") shipment = create_shipment(order_id) # Success Log.with_tags("order", "complete") \ .with_context("order_id", order_id) \ .with_context("shipment_id", shipment.id) \ .with_context("transaction_id", payment_result.id) \ .with_correlation_id(correlation_id) \ .info("Order processed successfully") return shipment except Exception as e: Log.with_tags("order", "error") \ .with_context("order_id", order_id) \ .with_context("error_message", str(e)) \ .with_correlation_id(correlation_id) \ .error("Order processing failed", exception=e) raise finally: Log.logout() # Usage try: shipment = process_user_order("ord_123", "user@example.com", "token_xyz") except Exception as e: print(f"Order processing failed: {e}") ``` ## Next Steps - Learn about [basic logging](/platforms/python/products/logs/basic-logging/) for foundational concepts - Explore [tags](/platforms/python/products/logs/tags/) for effective categorization - Discover [metadata context](/platforms/python/products/logs/metadata-context/) for rich information --- # Metadata Context # Metadata Context Add rich contextual information to your logs to understand the state of your application when events occur. Metadata helps correlate related information and makes debugging easier. ## Adding Context with with_context() The `with_context()` method adds data to individual log entries: ```python from bytehide_logs import Log # Single context value Log.with_context("user_id", "user_123").info("User action performed") # Multiple context values (chain multiple calls) Log.with_context("user_id", "user_123") \ .with_context("action", "profile_update") \ .with_context("timestamp", "2026-03-02T14:30:00Z") \ .info("User profile updated") ``` ## Global Metadata Context The `add_meta_context()` method adds metadata that applies to all subsequent logs: ```python from bytehide_logs import Log # Set application-wide context Log.add_meta_context("service", "payment-service") Log.add_meta_context("environment", "production") Log.add_meta_context("version", "2.1.0") # All subsequent logs include this context Log.info("Service started") # Output includes: service=payment-service, environment=production, version=2.1.0 Log.info("Processing payment") # Output includes: service=payment-service, environment=production, version=2.1.0 ``` ## Request-Level Context Add context that applies to all logs within a request: ```python from bytehide_logs import Log def handle_request(request): """Handle HTTP request with request context.""" # Add request-level context Log.add_meta_context("request_id", request.id) Log.add_meta_context("client_ip", request.remote_addr) Log.add_meta_context("user_agent", request.headers.get("User-Agent")) # All logs in this request include this context Log.info("Request received") Log.info("Validating request") Log.info("Processing request") # Clean up after request Log.clear_meta_context() ``` ## Application-Level Metadata Set metadata once at application startup: ```python from bytehide_logs import Log import os def initialize_logging(): """Initialize logging with application metadata.""" Log.add_meta_context("app_name", "ecommerce-api") Log.add_meta_context("environment", os.environ.get("ENV", "development")) Log.add_meta_context("region", os.environ.get("REGION", "us-east-1")) Log.add_meta_context("version", "1.2.3") Log.add_meta_context("start_time", get_current_timestamp()) # Call during application initialization initialize_logging() # Now all logs include this metadata Log.info("Application started") ``` ## Context Types Add different types of context data: ```python # Strings Log.with_context("status", "active").info("User status") # Numbers Log.with_context("response_time_ms", 145).info("Request completed") # Booleans Log.with_context("is_cached", True).info("Response from cache") # Lists Log.with_context("tags", ["important", "urgent"]).info("Task created") # Dictionaries (nested) Log.with_context("metadata", { "priority": "high", "assigned_to": "team-backend" }).info("Ticket created") # None (absence of value) Log.with_context("optional_field", None).info("Optional field not provided") ``` ## Request Tracking Context Track requests through your system: ```python from bytehide_logs import Log import uuid import time def middleware_before_request(request): """Track request context.""" request_id = str(uuid.uuid4()) start_time = time.time() Log.add_meta_context("request_id", request_id) Log.add_meta_context("start_time", start_time) Log.add_meta_context("method", request.method) Log.add_meta_context("path", request.path) Log.info("Request started") def middleware_after_request(response): """Log request completion with timing.""" elapsed_time = time.time() - get_start_time() Log.with_context("status_code", response.status_code) \ .with_context("elapsed_time_ms", int(elapsed_time * 1000)) \ .info("Request completed") Log.clear_meta_context() ``` ## Database Operation Context Add context for database queries: ```python from bytehide_logs import Log def execute_query(query, params): """Execute database query with context.""" Log.with_context("query_type", query.type) \ .with_context("table", query.table) \ .with_context("param_count", len(params)) \ .with_context("query_id", generate_query_id()) \ .info("Executing database query") try: result = database.execute(query, params) Log.with_context("rows_affected", len(result)).info("Query executed") return result except Exception as e: Log.error("Query failed", exception=e) raise ``` ## API Call Context Track external API interactions: ```python from bytehide_logs import Log import requests def call_external_api(endpoint, method="GET", **kwargs): """Call external API with detailed context.""" request_id = generate_request_id() Log.with_context("api_endpoint", endpoint) \ .with_context("http_method", method) \ .with_context("api_request_id", request_id) \ .info("Calling external API") try: headers = {**kwargs.get("headers", {}), "X-Request-ID": request_id} response = requests.request(method, endpoint, headers=headers, **kwargs) Log.with_context("status_code", response.status_code) \ .with_context("response_time_ms", response.elapsed.total_seconds() * 1000) \ .with_context("response_size_bytes", len(response.content)) \ .info("API call successful") return response.json() except Exception as e: Log.error("API call failed", exception=e) raise ``` ## Business Logic Context Add context specific to your business domain: ```python from bytehide_logs import Log def process_order(order): """Process order with business context.""" Log.add_meta_context("order_id", order.id) Log.add_meta_context("customer_id", order.customer_id) Log.add_meta_context("order_total", order.total) Log.info("Order processing started") try: # Validate inventory Log.with_context("step", "inventory_check").info("Checking inventory") validate_inventory(order) # Process payment Log.with_context("step", "payment") \ .with_context("payment_method", order.payment_method) \ .info("Processing payment") process_payment(order) # Create shipment Log.with_context("step", "fulfillment").info("Creating shipment") shipment = create_shipment(order) Log.with_context("shipment_id", shipment.id).info("Shipment created") Log.info("Order processing completed") finally: Log.clear_meta_context() ``` ## Performance Monitoring Context Track performance metrics: ```python from bytehide_logs import Log import time class PerformanceMonitor: """Monitor operation performance with logging context.""" def __init__(self, operation_name): self.operation_name = operation_name self.start_time = time.time() def __enter__(self): Log.add_meta_context("operation", self.operation_name) Log.add_meta_context("start_time", self.start_time) return self def __exit__(self, exc_type, exc_val, exc_tb): elapsed = time.time() - self.start_time Log.with_context("elapsed_ms", int(elapsed * 1000)).info( f"Operation {self.operation_name} completed" ) Log.clear_meta_context() # Usage with PerformanceMonitor("data_import"): import_data_from_csv() ``` ## Combining Context Methods Mix `with_context()` and `add_meta_context()`: ```python from bytehide_logs import Log # Global metadata (applies to all logs) Log.add_meta_context("service", "user-service") Log.add_meta_context("environment", "production") # Request-specific context Log.with_context("request_id", "req_123") \ .with_context("user_id", "user_456") \ .info("Processing user request") # Output includes both global and request-specific context # service=user-service, environment=production, request_id=req_123, user_id=user_456 ``` ## Context Hierarchy Context flows through your application hierarchy: ```python from bytehide_logs import Log # Application level Log.add_meta_context("app", "api-server") def handle_request(request): # Request level Log.add_meta_context("request_id", request.id) def process_item(item): # Item level Log.with_context("item_id", item.id) \ .with_context("item_type", item.type) \ .info("Processing item") for item in request.items: process_item(item) Log.clear_meta_context() ``` ## Clearing Context Remove metadata context when no longer needed: ```python from bytehide_logs import Log # Add context Log.add_meta_context("request_id", "req_789") Log.info("Processing request") # Clear all metadata Log.clear_meta_context() # Clear specific metadata Log.remove_meta_context("request_id") # Subsequent logs don't include cleared context Log.info("Processing complete") ``` ## Complete Example ```python from bytehide_logs import Log, LogSettings from datetime import timedelta import uuid # Initialize application logging settings = LogSettings( duplicate_suppression_window=timedelta(seconds=5), mask_sensitive_data=["password", "token"] ) Log.configure(settings) # Application metadata Log.add_meta_context("service", "payment-api") Log.add_meta_context("version", "1.0.0") Log.add_meta_context("environment", "production") def handle_payment_request(request): """Handle payment request with comprehensive context.""" # Request context request_id = str(uuid.uuid4()) Log.add_meta_context("request_id", request_id) Log.add_meta_context("client_ip", request.remote_addr) Log.info("Payment request received") try: # Identify user user = authenticate(request) Log.identify(user) # Add business context Log.add_meta_context("order_id", request.order_id) Log.add_meta_context("amount_cents", request.amount) # Validate request Log.with_context("step", "validation").info("Validating payment details") validate_payment(request) # Process payment Log.with_context("step", "processing") \ .with_context("gateway", "stripe") \ .info("Processing payment") result = process_payment(request) # Return result Log.with_context("step", "complete") \ .with_context("transaction_id", result.id) \ .info("Payment processed successfully") return result except Exception as e: Log.error("Payment processing failed", exception=e) raise finally: # Clean up context Log.clear_meta_context() ``` ## Next Steps - Learn about [user identification](/platforms/python/products/logs/user-identification/) for tracking user actions - Explore [correlation IDs](/platforms/python/products/logs/correlation-ids/) for request tracing - Discover [tags](/platforms/python/products/logs/tags/) for categorizing log entries --- # Tags # Tags Tags allow you to organize and categorize logs by feature, component, or domain. They make it easy to filter logs and understand which parts of your application are involved in specific operations. ## Adding Tags Use the `with_tags()` method to add one or more tags to a log entry: ```python from bytehide_logs import Log # Single tag Log.with_tags("payment").info("Payment processing started") # Multiple tags Log.with_tags("payment", "stripe").info("Charging card via Stripe") # Tags with context Log.with_tags("database", "query") \ .with_context("table", "users") \ .info("User record fetched") ``` ## Tag Categories Organize your application using consistent tag categories: ### Authentication & Authorization ```python # Login/logout operations Log.with_tags("auth", "login").info("User login attempt") Log.with_tags("auth", "logout").info("User session terminated") # Permission checks Log.with_tags("auth", "permission").warning("Insufficient permissions for operation") Log.with_tags("auth", "token").info("Token refreshed") ``` ### Payment Processing ```python Log.with_tags("payment", "checkout").info("Checkout initiated") Log.with_tags("payment", "card").info("Card validated") Log.with_tags("payment", "stripe").info("Payment submitted to Stripe") Log.with_tags("payment", "refund").info("Refund processed") ``` ### Data Operations ```python Log.with_tags("database", "query").info("SELECT executed") Log.with_tags("database", "migration").info("Schema migration completed") Log.with_tags("cache", "redis").info("Cache invalidated") Log.with_tags("search", "elasticsearch").info("Index updated") ``` ### External Services ```python Log.with_tags("service", "email").info("Welcome email sent") Log.with_tags("service", "sms").warning("SMS delivery failed") Log.with_tags("service", "api").info("Third-party API called") Log.with_tags("service", "webhook").info("Webhook received and processed") ``` ### Business Domain ```python Log.with_tags("order", "fulfilled").info("Order shipped") Log.with_tags("inventory", "stock").info("Inventory updated") Log.with_tags("customer", "profile").info("Customer profile modified") Log.with_tags("reporting", "analytics").info("Analytics event recorded") ``` ## Multiple Tags for Complex Operations Combine tags to describe operations spanning multiple domains: ```python def process_order(order_id): """Process an order involving multiple systems.""" # Validate order Log.with_tags("order", "validation").info(f"Validating order {order_id}") validate_order(order_id) # Update inventory Log.with_tags("order", "inventory").info(f"Reducing inventory for order {order_id}") reduce_inventory(order_id) # Process payment Log.with_tags("order", "payment", "stripe") \ .with_context("order_id", order_id) \ .info("Processing payment") process_payment(order_id) # Send confirmation Log.with_tags("order", "notification", "email") \ .info("Order confirmation email sent") send_confirmation_email(order_id) Log.with_tags("order", "complete") \ .info(f"Order {order_id} processed successfully") ``` ## Fluent Tag Chaining Chain multiple operations with consistent tags: ```python base_log = Log.with_tags("user_profile") base_log.info("Loading user profile") base_log.with_context("field", "name").info("Updating name") base_log.with_context("field", "email").info("Updating email") base_log.info("Profile changes saved") ``` ## Tag-Based Filtering and Analysis Tags enable powerful log queries: ```python # Find all payment-related operations # Query: tag:payment # Find failed stripe operations # Query: tag:stripe AND level:error # Find slow database queries # Query: tag:database tag:query AND duration > 1000 ``` ## Recommended Tag Conventions Use lowercase and hyphens for consistency: ```python # Good - lowercase, descriptive Log.with_tags("payment-gateway", "card-validation").info("Card validated") # Avoid - mixed case Log.with_tags("PaymentGateway", "CardValidation").info("Card validated") # Good - specific categories Log.with_tags("auth", "oauth").info("OAuth token received") # Avoid - vague tags Log.with_tags("stuff").info("Something happened") ``` ## Tag Patterns Establish tag patterns for your organization: ```python # Pattern: [domain]-[action] Log.with_tags("user-create").info("New user registered") Log.with_tags("user-delete").info("User account deleted") Log.with_tags("post-publish").info("Blog post published") Log.with_tags("post-archive").info("Blog post archived") # Pattern: [service]-[operation] Log.with_tags("email-send").info("Email queued") Log.with_tags("email-bounce").warning("Email bounced") Log.with_tags("sms-send").info("SMS delivered") # Pattern: [component]-[event] Log.with_tags("middleware-request").info("Request received") Log.with_tags("middleware-response").info("Response sent") ``` ## Tags with Error Handling Use tags to categorize errors: ```python def fetch_external_data(url): """Fetch data with categorized error logging.""" try: response = requests.get(url, timeout=5) Log.with_tags("external-api", "success").info(f"Data fetched from {url}") return response.json() except requests.Timeout: Log.with_tags("external-api", "timeout").warning(f"Timeout fetching {url}") except requests.ConnectionError as e: Log.with_tags("external-api", "connection").error(f"Connection failed", exception=e) except Exception as e: Log.with_tags("external-api", "error").error(f"Unexpected error", exception=e) ``` ## Complete Example ```python from bytehide_logs import Log def handle_payment_webhook(payload): """Handle payment webhook with comprehensive tagging.""" Log.with_tags("webhook", "payment").info("Payment webhook received") try: # Verify webhook signature Log.with_tags("webhook", "payment", "verification") \ .info("Verifying webhook signature") verify_webhook_signature(payload) # Find associated order Log.with_tags("webhook", "payment", "lookup") \ .info("Looking up order for payment") order = find_order(payload["order_id"]) # Update order status Log.with_tags("webhook", "payment", "order-status") \ .info("Updating order status") order.status = "paid" order.save() # Trigger fulfillment Log.with_tags("webhook", "payment", "fulfillment") \ .info("Triggering order fulfillment") trigger_fulfillment(order.id) Log.with_tags("webhook", "payment", "complete") \ .info("Payment webhook processed successfully") except Exception as e: Log.with_tags("webhook", "payment", "error") \ .error("Payment webhook processing failed", exception=e) raise ``` ## Next Steps - Learn about [correlation IDs](/platforms/python/products/logs/correlation-ids/) to track operations across requests - Explore [metadata context](/platforms/python/products/logs/metadata-context/) to add rich contextual information - Discover [fluent syntax](/platforms/python/products/logs/fluent-syntax/) for elegant log chaining --- # User Identification # User Identification Track which users are performing actions and experiencing errors by identifying them in your logs. This enables powerful filtering, debugging, and user impact analysis. ## AuthUser Structure Create an `AuthUser` instance with user information: ```python from bytehide_logs import AuthUser user = AuthUser( id="user_12345", email="alice@company.com", token="token_abc123xyz" ) ``` The `AuthUser` constructor accepts: - `id` (required) - Unique identifier for the user - `email` (optional) - User's email address - `token` (optional) - Authentication token (will be masked) ## Identifying Users Use `Log.identify()` to associate subsequent logs with a user: ```python from bytehide_logs import Log, AuthUser user = AuthUser( id="user_42", email="bob@example.com", token="secret_token_xyz" ) Log.identify(user) # All subsequent logs are now associated with user_42 Log.info("User session created") Log.info("Processing user preferences") Log.info("Saving profile changes") ``` ## Updating Previous Logs The `update_previous_logs` parameter allows you to retroactively associate a user with earlier logs: ```python # Initial logs without user context Log.info("Request received") Log.info("Validating credentials") # User identified after initial logs user = AuthUser(id="user_789", email="charlie@example.com") Log.identify(user, update_previous_logs=True) # Now earlier logs are associated with this user Log.info("User authenticated successfully") ``` Set `update_previous_logs=False` (default) to only identify the current and future logs: ```python # Initial logs Log.info("Processing request") # Identify user for current and future logs only Log.identify(user, update_previous_logs=False) # This log is associated with the user Log.info("Request completed successfully") ``` ## User Logout End a user session with `Log.logout()`: ```python Log.logout() # Subsequent logs are no longer associated with the previous user Log.info("User session ended") ``` Use logout when: - User explicitly logs out - Session expires or is revoked - User switches accounts - Cleaning up after user operations ## Complete Authentication Flow ```python from bytehide_logs import Log, AuthUser def handle_login(credentials): """Handle user login with comprehensive logging.""" Log.info("Login attempt", context={"email": credentials.email}) try: # Validate credentials user_data = authenticate(credentials) # Create AuthUser user = AuthUser( id=user_data.id, email=user_data.email, token=user_data.session_token ) # Identify user for all subsequent logs Log.identify(user) Log.info("User authentication successful") return user_data except AuthenticationError as e: Log.warning( "Login failed", exception=e, context={"email": credentials.email} ) raise def handle_logout(): """Handle user logout.""" Log.info("User logout initiated") # Perform logout operations clear_session() # Disassociate user from logs Log.logout() Log.info("User session terminated") ``` ## Identifying Different Users Switch between users by calling `identify()` again: ```python # Initial user user_alice = AuthUser(id="alice_001", email="alice@example.com") Log.identify(user_alice) Log.info("Alice performed action") # Switch to different user user_bob = AuthUser(id="bob_001", email="bob@example.com") Log.identify(user_bob) Log.info("Bob performed action") # Logout Log.logout() Log.info("No user context") ``` ## Using User Context with Tags and Correlation IDs Combine user identification with other context: ```python user = AuthUser(id="user_456", email="dave@example.com") Log.identify(user) Log.with_tags("user_action", "profile") \ .with_context("action", "update_bio") \ .with_correlation_id("req_78910") \ .info("User profile updated successfully") ``` ## Privacy and Security The token field is automatically masked: ```python user = AuthUser( id="user_999", email="secure@example.com", token="super_secret_token_12345" ) Log.identify(user) Log.info("User identified") # Token is masked in logs automatically ``` See [data masking](/platforms/python/products/logs/data-masking/) for more information about protecting sensitive data. ## Accessing Current User Query the currently identified user: ```python from bytehide_logs import Log # Get current user context current_user = Log.get_current_user() if current_user: print(f"Logged in as: {current_user.email}") else: print("No user identified") ``` ## Best Practices **Identify users early** in your request handling: ```python # Good - identify before processing def handle_request(request): user = get_user_from_token(request.headers["Authorization"]) Log.identify(user) # All downstream logs have user context process_request(request) ``` **Use `update_previous_logs` carefully**: ```python # Use update_previous_logs=True for: # - Deferred authentication (identify after logging begins) # - Retry loops with late authentication # Use update_previous_logs=False (default) for: # - Standard authentication before processing # - Avoiding re-indexing large log sets ``` **Always logout when appropriate**: ```python # Good - explicit logout try: handle_request(request) finally: Log.logout() ``` ## Next Steps - Learn about [tags](/platforms/python/products/logs/tags/) to categorize user actions - Explore [correlation IDs](/platforms/python/products/logs/correlation-ids/) to track user requests across services - Discover [data masking](/platforms/python/products/logs/data-masking/) to protect user tokens and sensitive data --- # Django Integration # Django Integration Integrate ByteHide Logs with Django using middleware to automatically track requests, user actions, and errors across your entire application. ## Setup Install the Django integration: ```bash pip install bytehide-logs[django] ``` Add the ByteHide logging middleware to your Django settings: ```python # settings.py MIDDLEWARE = [ # ... other middleware ... 'bytehide_logs.django.ByteHideLoggingMiddleware', ] # Configure ByteHide Logs from bytehide_logs import Log, LogSettings from datetime import timedelta settings = LogSettings( duplicate_suppression_window=timedelta(seconds=5), mask_sensitive_data=["password", "token", "api_key"] ) Log.configure(settings) # Application metadata Log.add_meta_context("service", "django-app") Log.add_meta_context("environment", os.environ.get("ENVIRONMENT", "development")) ``` ## Middleware Setup The middleware automatically: - Tracks incoming requests with correlation IDs - Logs request processing time - Captures user information - Handles errors and exceptions - Cleans up context after request ```python # settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', # ... other apps ... ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'bytehide_logs.django.ByteHideLoggingMiddleware', # Add here 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ] ``` ## Request Tracking The middleware automatically logs all requests: ```python # Middleware automatically logs: # - Request method and path # - Client IP address # - Correlation ID # - Response status code # - Request duration ``` To access the correlation ID in your views: ```python from django.http import JsonResponse from bytehide_logs import Log def my_view(request): """View with access to correlation ID.""" # Correlation ID is available from request correlation_id = getattr(request, 'correlation_id', None) Log.with_context("view", "my_view") \ .with_correlation_id(correlation_id) \ .info("Processing view") return JsonResponse({"message": "Success"}) ``` ## User Identification Identify authenticated Django users automatically: ```python # views.py from django.contrib.auth.decorators import login_required from django.http import JsonResponse from bytehide_logs import Log, AuthUser @login_required def user_profile(request): """View with authenticated user tracking.""" user = request.user # Identify user in logs auth_user = AuthUser( id=str(user.id), email=user.email ) Log.identify(auth_user) Log.with_tags("user", "profile").info("Viewing user profile") return JsonResponse({ "user_id": user.id, "email": user.email }) ``` ## Model Operations Logging Log database operations: ```python # models.py from django.db import models from bytehide_logs import Log class User(models.Model): """User model with logging.""" email = models.EmailField(unique=True) username = models.CharField(max_length=100) def save(self, *args, **kwargs): """Save with logging.""" is_new = not self.pk if is_new: Log.with_tags("model", "user", "create") \ .with_context("email", self.email) \ .info("Creating user") else: Log.with_tags("model", "user", "update") \ .with_context("user_id", self.id) \ .with_context("email", self.email) \ .info("Updating user") super().save(*args, **kwargs) if is_new: Log.with_tags("model", "user", "create", "success") \ .with_context("user_id", self.id) \ .info("User created") def delete(self, *args, **kwargs): """Delete with logging.""" Log.with_tags("model", "user", "delete") \ .with_context("user_id", self.id) \ .info("Deleting user") super().delete(*args, **kwargs) Log.with_tags("model", "user", "delete", "success") \ .info("User deleted") ``` ## Signal Handling Use Django signals with logging: ```python # signals.py from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django.contrib.auth.models import User from bytehide_logs import Log @receiver(post_save, sender=User) def user_created(sender, instance, created, **kwargs): """Log user creation.""" if created: Log.with_tags("user", "created") \ .with_context("user_id", instance.id) \ .with_context("email", instance.email) \ .info("User created via signal") @receiver(post_delete, sender=User) def user_deleted(sender, instance, **kwargs): """Log user deletion.""" Log.with_tags("user", "deleted") \ .with_context("user_id", instance.id) \ .info("User deleted via signal") ``` ## Exception Handling Log exceptions in views: ```python # views.py from django.http import JsonResponse from bytehide_logs import Log from django.views.decorators.http import require_http_methods @require_http_methods(["POST"]) def process_payment(request): """Process payment with error handling.""" try: data = request.POST Log.with_tags("payment", "process").info("Processing payment") # Validate data if not data.get("amount"): raise ValueError("Amount is required") # Process payment result = charge_card( card_token=data.get("token"), amount=int(data.get("amount")) ) Log.with_tags("payment", "success") \ .with_context("transaction_id", result.id) \ .with_context("amount", data.get("amount")) \ .info("Payment processed successfully") return JsonResponse({ "transaction_id": result.id, "status": "success" }) except ValueError as e: Log.warning("Payment validation failed", exception=e) return JsonResponse({"error": str(e)}, status=400) except Exception as e: Log.error("Payment processing failed", exception=e) return JsonResponse({"error": "Payment failed"}, status=500) ``` ## Complete Django Example ```python # views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import JsonResponse from django.views.decorators.http import require_http_methods from bytehide_logs import Log, AuthUser import uuid @require_http_methods(["POST"]) def user_login(request): """User login view with logging.""" try: username = request.POST.get("username") password = request.POST.get("password") Log.with_tags("auth", "login") \ .with_context("username", username) \ .info("Login attempt") # Authenticate user user = authenticate(request, username=username, password=password) if user is not None: # Login successful login(request, user) # Identify user in logs auth_user = AuthUser( id=str(user.id), email=user.email ) Log.identify(auth_user) Log.with_tags("auth", "login", "success").info("Login successful") return redirect('dashboard') else: # Login failed Log.with_tags("auth", "login", "failed") \ .with_context("username", username) \ .warning("Login failed - invalid credentials") return JsonResponse({"error": "Invalid credentials"}, status=401) except Exception as e: Log.with_tags("auth", "login", "error") \ .error("Login error", exception=e) return JsonResponse({"error": "Login error"}, status=500) @require_http_methods(["POST"]) def user_logout(request): """User logout view.""" Log.with_tags("auth", "logout").info("Logout initiated") logout(request) Log.with_tags("auth", "logout", "success").info("Logout completed") Log.logout() return redirect('login') @login_required def user_profile(request): """User profile view.""" user = request.user # Identify user auth_user = AuthUser(id=str(user.id), email=user.email) Log.identify(auth_user) Log.with_tags("user", "profile") \ .with_context("user_id", user.id) \ .info("Accessing user profile") return render(request, 'profile.html', { 'user': user }) @login_required @require_http_methods(["PUT"]) def update_profile(request): """Update user profile.""" try: import json data = json.loads(request.body) user = request.user Log.with_tags("user", "profile", "update") \ .with_context("user_id", user.id) \ .with_context("fields", list(data.keys())) \ .info("Updating user profile") # Update user fields if 'email' in data: user.email = data['email'] if 'first_name' in data: user.first_name = data['first_name'] if 'last_name' in data: user.last_name = data['last_name'] user.save() Log.with_tags("user", "profile", "update", "success") \ .with_context("user_id", user.id) \ .info("User profile updated") return JsonResponse({"status": "success"}) except Exception as e: Log.error("Profile update failed", exception=e) return JsonResponse({"error": "Update failed"}, status=500) @login_required @require_http_methods(["POST"]) def process_order(request): """Process user order.""" try: import json data = json.loads(request.body) user = request.user correlation_id = str(uuid.uuid4()) Log.with_tags("order", "process") \ .with_context("user_id", user.id) \ .with_context("order_total", data.get("total")) \ .with_correlation_id(correlation_id) \ .info("Processing order") # Validate cart Log.with_tags("order", "validation") \ .with_correlation_id(correlation_id) \ .info("Validating order") validate_order(data) # Process payment Log.with_tags("order", "payment") \ .with_correlation_id(correlation_id) \ .info("Processing payment") payment = process_payment(data) # Create order record Log.with_tags("order", "create") \ .with_context("order_id", payment.id) \ .with_correlation_id(correlation_id) \ .info("Creating order record") Log.with_tags("order", "complete") \ .with_context("order_id", payment.id) \ .with_correlation_id(correlation_id) \ .info("Order processed successfully") return JsonResponse({ "order_id": payment.id, "correlation_id": correlation_id }) except Exception as e: Log.error("Order processing failed", exception=e) return JsonResponse({"error": "Order failed"}, status=500) ``` ## URL Configuration Log API endpoints: ```python # urls.py from django.contrib import admin from django.urls import path from bytehide_logs import Log # Log URL configuration Log.info("Configuring Django URLs") urlpatterns = [ path('admin/', admin.site.urls), path('auth/login/', views.user_login, name='login'), path('auth/logout/', views.user_logout, name='logout'), path('api/profile/', views.user_profile, name='profile'), path('api/profile/update/', views.update_profile, name='update_profile'), path('api/order/process/', views.process_order, name='process_order'), ] ``` ## Best Practices **Always identify authenticated users:** ```python user = request.user if user.is_authenticated: auth_user = AuthUser(id=str(user.id), email=user.email) Log.identify(auth_user) ``` **Use correlation IDs for multi-step operations:** ```python correlation_id = getattr(request, 'correlation_id', None) Log.with_correlation_id(correlation_id).info("Processing step") ``` **Log model operations for audit trails:** ```python def save(self, *args, **kwargs): Log.with_tags("model", self.__class__.__name__).info("Saving model") super().save(*args, **kwargs) ``` ## Next Steps - Learn about [user identification](/platforms/python/products/logs/user-identification/) - Explore [correlation IDs](/platforms/python/products/logs/correlation-ids/) - Discover [Flask integration](/platforms/python/products/logs/flask/) --- # FastAPI Integration # FastAPI Integration Integrate ByteHide Logs with FastAPI using middleware to track requests, user actions, and errors with minimal configuration. ## Setup Install the FastAPI integration: ```bash pip install bytehide-logs[fastapi] ``` Add the ByteHide logging middleware to your FastAPI app: ```python from fastapi import FastAPI from bytehide_logs import Log, LogSettings from bytehide_logs.fastapi import ByteHideLoggingMiddleware from datetime import timedelta app = FastAPI() # Configure logging settings = LogSettings( duplicate_suppression_window=timedelta(seconds=5), mask_sensitive_data=["password", "token", "api_key"] ) Log.configure(settings) # Add middleware app.add_middleware(ByteHideLoggingMiddleware) # Application metadata Log.add_meta_context("service", "fastapi-app") Log.add_meta_context("version", "1.0.0") ``` ## Middleware Configuration The middleware automatically: - Generates and tracks correlation IDs - Logs incoming requests - Captures response times and status codes - Handles exceptions and errors - Cleans up context after request ```python from fastapi import FastAPI from bytehide_logs.fastapi import ByteHideLoggingMiddleware app = FastAPI( title="My API", version="1.0.0", description="API with ByteHide Logs" ) # Add ByteHide logging middleware app.add_middleware(ByteHideLoggingMiddleware) # Middleware configuration options # - include_request_body: Include request body in logs (default: False for security) # - include_response_body: Include response body in logs (default: False for security) # - skip_paths: List of paths to exclude from logging (default: ["/health", "/docs"]) ``` ## Request Tracking Access the correlation ID in your endpoints: ```python from fastapi import FastAPI, Request from bytehide_logs import Log app = FastAPI() @app.get("/items/{item_id}") async def get_item(item_id: int, request: Request): """Get item by ID with correlation tracking.""" correlation_id = request.state.correlation_id Log.with_tags("item", "fetch") \ .with_context("item_id", item_id) \ .with_correlation_id(correlation_id) \ .info("Fetching item") return {"item_id": item_id, "name": "Item Name"} ``` ## User Authentication Track authenticated users with FastAPI security: ```python from fastapi import FastAPI, Depends, HTTPException from fastapi.security import HTTPBearer from bytehide_logs import Log, AuthUser app = FastAPI() security = HTTPBearer() async def get_current_user(credentials = Depends(security)): """Get current authenticated user.""" try: # Decode and verify token user_data = decode_token(credentials.credentials) # Identify user in logs user = AuthUser( id=user_data["user_id"], email=user_data["email"] ) Log.identify(user) return user_data except Exception as e: Log.warning("Authentication failed", exception=e) raise HTTPException(status_code=401, detail="Not authenticated") @app.get("/profile") async def get_profile(user = Depends(get_current_user)): """Get user profile.""" Log.with_tags("user", "profile").info("Fetching user profile") return { "user_id": user["user_id"], "email": user["email"] } ``` ## Exception Handling Add custom exception handlers with logging: ```python from fastapi import FastAPI, HTTPException from bytehide_logs import Log app = FastAPI() @app.exception_handler(HTTPException) async def http_exception_handler(request, exc): """Handle HTTP exceptions with logging.""" Log.with_tags("error", "http_exception") \ .with_context("status_code", exc.status_code) \ .with_context("detail", exc.detail) \ .warning("HTTP exception occurred") return { "error": exc.detail, "status_code": exc.status_code, "correlation_id": request.state.get("correlation_id") } @app.exception_handler(Exception) async def general_exception_handler(request, exc): """Handle unhandled exceptions with logging.""" Log.with_tags("error", "unhandled") \ .with_context("error_type", type(exc).__name__) \ .error("Unhandled exception", exception=exc) return { "error": "Internal server error", "correlation_id": request.state.get("correlation_id") }, 500 ``` ## Complete FastAPI Example ```python from fastapi import FastAPI, Depends, HTTPException, Request from fastapi.security import HTTPBearer, HTTPAuthenticationCredentials from bytehide_logs import Log, LogSettings, AuthUser from datetime import timedelta import uuid from typing import Optional # Initialize FastAPI app app = FastAPI( title="User API", version="1.0.0" ) # Configure logging settings = LogSettings( duplicate_suppression_window=timedelta(seconds=5), mask_sensitive_data=["password", "token", "api_key"] ) Log.configure(settings) # Add middleware from bytehide_logs.fastapi import ByteHideLoggingMiddleware app.add_middleware(ByteHideLoggingMiddleware) # Application metadata Log.add_meta_context("service", "user-api") Log.add_meta_context("environment", "production") # Security security = HTTPBearer() # ============== Helper Functions ============== async def get_current_user( credentials: Optional[HTTPAuthenticationCredentials] = Depends(security) ): """Get current authenticated user.""" if not credentials: return None try: # Decode token (example) user_data = decode_jwt_token(credentials.credentials) # Identify user in logs user = AuthUser( id=user_data["user_id"], email=user_data["email"] ) Log.identify(user) return user_data except Exception as e: Log.with_tags("auth", "decode_error").warning("Token decode failed", exception=e) raise HTTPException(status_code=401, detail="Not authenticated") # ============== Exception Handlers ============== @app.exception_handler(HTTPException) async def http_exception_handler(request: Request, exc: HTTPException): """Handle HTTP exceptions.""" Log.with_tags("error", "http") \ .with_context("status_code", exc.status_code) \ .with_context("detail", exc.detail) \ .warning("HTTP exception") return { "error": exc.detail, "correlation_id": request.state.get("correlation_id") } @app.exception_handler(Exception) async def general_exception_handler(request: Request, exc: Exception): """Handle unhandled exceptions.""" Log.with_tags("error", "unhandled") \ .with_context("error_type", type(exc).__name__) \ .error("Unhandled exception", exception=exc) return { "error": "Internal server error", "correlation_id": request.state.get("correlation_id") }, 500 # ============== Startup/Shutdown ============== @app.on_event("startup") async def startup_event(): """Log application startup.""" Log.info("FastAPI application starting") @app.on_event("shutdown") async def shutdown_event(): """Log application shutdown.""" Log.info("FastAPI application shutting down") # ============== Auth Endpoints ============== @app.post("/auth/login") async def login(request: Request, email: str, password: str): """User login endpoint.""" try: Log.with_tags("auth", "login") \ .with_context("email", email) \ .info("Login attempt") # Authenticate user (example) user_data = authenticate_user(email, password) # Generate token token = generate_jwt_token(user_data) # Identify user user = AuthUser(id=user_data["id"], email=user_data["email"]) Log.identify(user) Log.with_tags("auth", "login", "success") \ .with_context("user_id", user_data["id"]) \ .info("Login successful") return { "token": token, "user_id": user_data["id"], "email": user_data["email"] } except Exception as e: Log.with_tags("auth", "login", "error") \ .error("Login failed", exception=e) raise HTTPException(status_code=401, detail="Login failed") @app.post("/auth/logout") async def logout(request: Request): """User logout endpoint.""" Log.with_tags("auth", "logout").info("Logout initiated") # Logout user Log.logout() Log.with_tags("auth", "logout", "success").info("Logout completed") return {"message": "Logged out"} # ============== User Endpoints ============== @app.get("/users/{user_id}") async def get_user(user_id: str, request: Request): """Get user by ID.""" correlation_id = request.state.correlation_id try: Log.with_tags("user", "fetch") \ .with_context("user_id", user_id) \ .with_correlation_id(correlation_id) \ .info("Fetching user") user = fetch_user_from_db(user_id) Log.with_tags("user", "fetch", "success") \ .with_context("user_id", user_id) \ .with_correlation_id(correlation_id) \ .info("User fetched") return user except Exception as e: Log.with_tags("user", "fetch", "error") \ .with_context("user_id", user_id) \ .with_correlation_id(correlation_id) \ .error("Failed to fetch user", exception=e) raise HTTPException(status_code=404, detail="User not found") @app.get("/profile") async def get_profile( request: Request, user = Depends(get_current_user) ): """Get current user profile.""" correlation_id = request.state.correlation_id Log.with_tags("user", "profile") \ .with_context("user_id", user["user_id"]) \ .with_correlation_id(correlation_id) \ .info("Fetching profile") return { "user_id": user["user_id"], "email": user["email"], "name": user.get("name", "") } @app.put("/profile") async def update_profile( request: Request, user = Depends(get_current_user), name: Optional[str] = None, email: Optional[str] = None ): """Update current user profile.""" correlation_id = request.state.correlation_id try: updates = {} if name: updates["name"] = name if email: updates["email"] = email Log.with_tags("user", "profile", "update") \ .with_context("user_id", user["user_id"]) \ .with_context("fields", list(updates.keys())) \ .with_correlation_id(correlation_id) \ .info("Updating profile") updated_user = update_user_in_db(user["user_id"], updates) Log.with_tags("user", "profile", "update", "success") \ .with_context("user_id", user["user_id"]) \ .with_correlation_id(correlation_id) \ .info("Profile updated") return updated_user except Exception as e: Log.with_tags("user", "profile", "update", "error") \ .with_context("user_id", user["user_id"]) \ .with_correlation_id(correlation_id) \ .error("Profile update failed", exception=e) raise HTTPException(status_code=500, detail="Update failed") # ============== Order Endpoints ============== @app.post("/orders") async def create_order( request: Request, user = Depends(get_current_user), items: list = [], total: float = 0 ): """Create new order.""" correlation_id = request.state.correlation_id try: Log.with_tags("order", "create") \ .with_context("user_id", user["user_id"]) \ .with_context("item_count", len(items)) \ .with_context("total", total) \ .with_correlation_id(correlation_id) \ .info("Creating order") # Validate order Log.with_tags("order", "validation") \ .with_correlation_id(correlation_id) \ .info("Validating order") validate_order({"items": items, "total": total}) # Process payment Log.with_tags("order", "payment") \ .with_context("total", total) \ .with_correlation_id(correlation_id) \ .info("Processing payment") payment = process_payment(total) # Create order order = create_order_in_db( user_id=user["user_id"], items=items, total=total, payment_id=payment["id"] ) Log.with_tags("order", "create", "success") \ .with_context("order_id", order["id"]) \ .with_context("user_id", user["user_id"]) \ .with_correlation_id(correlation_id) \ .info("Order created") return { "order_id": order["id"], "status": "created", "correlation_id": correlation_id } except Exception as e: Log.with_tags("order", "create", "error") \ .with_context("user_id", user["user_id"]) \ .with_correlation_id(correlation_id) \ .error("Order creation failed", exception=e) raise HTTPException(status_code=500, detail="Order creation failed") # ============== Health Check ============== @app.get("/health") async def health_check(): """Health check endpoint.""" return {"status": "healthy"} # ============== Startup ============== if __name__ == "__main__": import uvicorn Log.info("Starting FastAPI application") uvicorn.run(app, host="0.0.0.0", port=8000) ``` ## Best Practices **Always use correlation IDs for request tracking:** ```python @app.get("/api/endpoint") async def endpoint(request: Request): correlation_id = request.state.correlation_id Log.with_correlation_id(correlation_id).info("Processing request") ``` **Identify authenticated users:** ```python async def get_current_user(credentials = Depends(security)): user = decode_token(credentials.credentials) Log.identify(AuthUser(id=user["id"], email=user["email"])) return user ``` **Use exception handlers for consistent error logging:** ```python @app.exception_handler(Exception) async def exception_handler(request: Request, exc: Exception): Log.error("Unhandled exception", exception=exc) return error_response(str(exc)) ``` ## Next Steps - Learn about [user identification](/platforms/python/products/logs/user-identification/) - Explore [correlation IDs](/platforms/python/products/logs/correlation-ids/) - Discover [Flask integration](/platforms/python/products/logs/flask/) --- # Flask Integration # Flask Integration Integrate ByteHide Logs seamlessly with Flask to track requests, errors, and user actions throughout your application lifecycle. ## Setup Install the Flask integration: ```bash pip install bytehide-logs[flask] ``` Import and initialize logging in your Flask app: ```python from flask import Flask from bytehide_logs import Log, LogSettings, AuthUser from datetime import timedelta app = Flask(__name__) # Configure logging settings = LogSettings( duplicate_suppression_window=timedelta(seconds=5), mask_sensitive_data=["password", "token", "api_key"] ) Log.configure(settings) # Set application metadata Log.add_meta_context("service", "flask-app") Log.add_meta_context("environment", app.config.get("ENV", "development")) ``` ## Request Tracking with before_request Log incoming requests using the `before_request` decorator: ```python from flask import Flask, request, g import uuid app = Flask(__name__) @app.before_request def log_request_start(): """Log incoming request.""" # Generate correlation ID correlation_id = request.headers.get( "X-Correlation-ID", str(uuid.uuid4()) ) g.correlation_id = correlation_id # Add request context Log.add_meta_context("request_id", correlation_id) Log.add_meta_context("method", request.method) Log.add_meta_context("path", request.path) Log.add_meta_context("client_ip", request.remote_addr) Log.with_tags("request", "start").info( f"{request.method} {request.path}" ) ``` ## Response Tracking with after_request Log responses using the `after_request` decorator: ```python from flask import Flask import time app = Flask(__name__) @app.before_request def track_request_start(): """Track request timing.""" g.start_time = time.time() @app.after_request def log_request_end(response): """Log request completion.""" if hasattr(g, 'start_time'): elapsed = time.time() - g.start_time Log.with_tags("request", "end") \ .with_context("status_code", response.status_code) \ .with_context("elapsed_ms", int(elapsed * 1000)) \ .with_context("content_length", len(response.data)) \ .info("Request completed") # Clear request context Log.clear_meta_context() return response ``` ## Error Handling with errorhandler Log exceptions using the `errorhandler` decorator: ```python from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(Exception) def handle_exception(error): """Handle all exceptions with logging.""" Log.with_tags("error", "unhandled") \ .with_context("error_type", type(error).__name__) \ .with_context("error_message", str(error)) \ .error("Unhandled exception", exception=error) # Return error response return jsonify({ "error": "Internal server error", "correlation_id": g.get("correlation_id") }), 500 @app.errorhandler(404) def handle_not_found(error): """Handle 404 errors.""" Log.with_tags("error", "not_found") \ .with_context("path", request.path) \ .warning("Resource not found") return jsonify({"error": "Not found"}), 404 @app.errorhandler(400) def handle_bad_request(error): """Handle 400 errors.""" Log.with_tags("error", "bad_request") \ .with_context("path", request.path) \ .warning("Bad request") return jsonify({"error": "Bad request"}), 400 ``` ## User Authentication Tracking Track authenticated users with Flask session: ```python from flask import Flask, request, session, g from bytehide_logs import Log, AuthUser app = Flask(__name__) @app.before_request def identify_user(): """Identify authenticated user.""" if "user_id" in session: # Create AuthUser from session user = AuthUser( id=session["user_id"], email=session.get("email"), token=session.get("session_token") ) # Identify user for logs Log.identify(user) g.current_user = user @app.after_request def logout_user(response): """Logout user after request.""" if hasattr(g, 'current_user'): Log.logout() return response ``` ## Complete Flask Example ```python from flask import Flask, request, session, g, jsonify from bytehide_logs import Log, LogSettings, AuthUser from datetime import timedelta import uuid import time # Initialize Flask app app = Flask(__name__) app.secret_key = "your-secret-key" # Configure logging settings = LogSettings( duplicate_suppression_window=timedelta(seconds=5), mask_sensitive_data=["password", "token", "api_key"] ) Log.configure(settings) # Application metadata Log.add_meta_context("service", "user-api") Log.add_meta_context("version", "1.0.0") # ============== Before Request ============== @app.before_request def before_request(): """Setup request context and logging.""" # Generate correlation ID correlation_id = request.headers.get( "X-Correlation-ID", str(uuid.uuid4()) ) g.correlation_id = correlation_id g.start_time = time.time() # Add request context Log.add_meta_context("correlation_id", correlation_id) Log.add_meta_context("method", request.method) Log.add_meta_context("path", request.path) Log.add_meta_context("client_ip", request.remote_addr) # Identify user if authenticated if "user_id" in session: user = AuthUser( id=session["user_id"], email=session.get("email"), token=session.get("session_token") ) Log.identify(user) Log.with_tags("request", "received").info( f"{request.method} {request.path}" ) # ============== After Request ============== @app.after_request def after_request(response): """Log request completion and cleanup.""" # Calculate request duration if hasattr(g, 'start_time'): elapsed = time.time() - g.start_time Log.with_tags("request", "completed") \ .with_context("status_code", response.status_code) \ .with_context("elapsed_ms", int(elapsed * 1000)) \ .with_context("response_size", len(response.data)) \ .info("Request processed") # Logout user Log.logout() # Clear request context Log.clear_meta_context() return response # ============== Error Handlers ============== @app.errorhandler(Exception) def handle_exception(error): """Handle unhandled exceptions.""" Log.with_tags("error", "exception") \ .with_context("error_type", type(error).__name__) \ .error("Unhandled exception", exception=error) return jsonify({ "error": "Internal server error", "correlation_id": g.correlation_id }), 500 @app.errorhandler(404) def handle_not_found(error): """Handle 404 errors.""" Log.with_tags("error", "not_found").warning("Resource not found") return jsonify({"error": "Not found"}), 404 # ============== Routes ============== @app.route("/login", methods=["POST"]) def login(): """User login endpoint.""" try: data = request.get_json() email = data.get("email") password = data.get("password") Log.with_tags("auth", "login") \ .with_context("email", email) \ .info("Login attempt") # Authenticate user (example) user_data = authenticate_user(email, password) # Set session session["user_id"] = user_data["id"] session["email"] = user_data["email"] session["session_token"] = generate_token() Log.with_tags("auth", "login", "success") \ .with_context("user_id", user_data["id"]) \ .info("User login successful") return jsonify({ "user_id": user_data["id"], "email": user_data["email"] }) except Exception as e: Log.with_tags("auth", "login", "error") \ .error("Login failed", exception=e) return jsonify({"error": "Login failed"}), 401 @app.route("/logout", methods=["POST"]) def logout(): """User logout endpoint.""" Log.with_tags("auth", "logout").info("User logout initiated") # Clear session session.clear() Log.with_tags("auth", "logout", "success").info("User logout completed") return jsonify({"message": "Logged out"}) @app.route("/users/", methods=["GET"]) def get_user(user_id): """Get user profile.""" Log.with_tags("user", "profile", "fetch") \ .with_context("user_id", user_id) \ .info("Fetching user profile") try: user = fetch_user_from_db(user_id) Log.with_tags("user", "profile", "success") \ .with_context("user_id", user_id) \ .info("User profile retrieved") return jsonify(user) except Exception as e: Log.with_tags("user", "profile", "error") \ .with_context("user_id", user_id) \ .error("Failed to fetch user profile", exception=e) return jsonify({"error": "User not found"}), 404 @app.route("/users/", methods=["PUT"]) def update_user(user_id): """Update user profile.""" try: data = request.get_json() Log.with_tags("user", "profile", "update") \ .with_context("user_id", user_id) \ .with_context("fields", list(data.keys())) \ .info("Updating user profile") updated_user = update_user_in_db(user_id, data) Log.with_tags("user", "profile", "update", "success") \ .with_context("user_id", user_id) \ .info("User profile updated") return jsonify(updated_user) except Exception as e: Log.with_tags("user", "profile", "update", "error") \ .with_context("user_id", user_id) \ .error("Failed to update user profile", exception=e) return jsonify({"error": "Update failed"}), 500 if __name__ == "__main__": Log.info("Flask application starting") app.run(debug=True) ``` ## Best Practices **Always clean up context after request:** ```python @app.after_request def cleanup(response): """Cleanup request context.""" Log.logout() # Logout user Log.clear_meta_context() # Clear request context return response ``` **Use correlation IDs for tracking:** ```python correlation_id = request.headers.get("X-Correlation-ID", str(uuid.uuid4())) g.correlation_id = correlation_id Log.add_meta_context("correlation_id", correlation_id) ``` **Handle all error types:** ```python @app.errorhandler(Exception) def handle_all_errors(error): """Catch and log all exceptions.""" Log.error("Unhandled exception", exception=error) return error_response(str(error)) ``` ## Next Steps - Learn about [user identification](/platforms/python/products/logs/user-identification/) - Explore [correlation IDs](/platforms/python/products/logs/correlation-ids/) - Discover [Django integration](/platforms/python/products/logs/django/) --- # AI Assistant ByteHide's AI Assistant provides intelligent analysis of your logs, helping you understand issues, identify patterns, and resolve problems faster. {% .lead %} ## AI Explanation Feature Every log entry includes an "AI Explanation" button that provides instant analysis. ![AI Assistant Button](/images/dotnet/logs/dashboard/log-ia-button.png) ## How It Works 1. **Click AI Explanation**: Select the sparkle icon next to any log entry 2. **Instant Analysis**: The AI analyzes the log content, context, and metadata 3. **Detailed Explanation**: Get a comprehensive breakdown of the log entry ![AI Analysis Panel](/images/dotnet/logs/dashboard/log-ia-panel.png) ## AI Analysis Content The AI provides detailed explanations including: ### Log Classification - **Log Type**: Identifies the type of log (warning, error, info, etc.) - **Severity Assessment**: Evaluates the importance and urgency - **Context Understanding**: Interprets the business meaning ### Technical Details - **Source Information**: Where the log was generated - **Method Context**: What method or process created the log - **Application Context**: Relevant application information like version ### Example AI Analysis For a database connection error, the AI provides: ``` The log message 'Database connection timeout after 30 seconds' is a critical error. • It was generated by the ConnectionManager method in /src/Services/DatabaseService.cs at line 145. • The application version is 2.1.4. • The log level is Critical, indicating a system failure that requires immediate attention. • This suggests the database server may be overloaded or experiencing connectivity issues. ``` ## When to Use AI Assistant ### Debugging Errors - Get explanations for complex error messages - Understand exception stack traces - Identify root causes of failures ### Performance Analysis - Interpret performance-related logs - Understand timing and resource usage - Identify bottlenecks and optimization opportunities ### Security Investigations - Analyze security-related warnings - Understand authentication failures - Identify potential security threats ### Business Logic Understanding - Interpret application-specific log messages - Understand workflow and process logs - Correlate business events with technical logs ## AI Analysis Benefits ### Faster Problem Resolution - **Instant Understanding**: No need to research error codes manually - **Context Awareness**: AI understands your application context - **Pattern Recognition**: Identifies common issues and solutions ### Knowledge Transfer - **Team Education**: Helps junior developers understand complex logs - **Documentation**: Creates instant documentation for log entries - **Best Practices**: Suggests improvements and best practices ### Comprehensive Analysis - **Multi-faceted View**: Considers technical and business aspects - **Correlation**: Links related information across log entries - **Recommendations**: Provides actionable next steps ## AI Features ### Intelligent Parsing - Automatically extracts key information - Identifies patterns and anomalies - Understands log structure and format ### Context Awareness - Considers application metadata - Incorporates user and session information - Understands business domain context ### Natural Language Explanations - Clear, human-readable explanations - Technical details in accessible language - Actionable recommendations ## Access Methods ### Individual Log Analysis - Click "AI Explanation" on any log entry - Get instant analysis in a popup modal - Copy explanations for sharing ### Bulk Analysis - Select multiple logs for pattern analysis - Identify common issues across log groups - Generate summary reports ## Tips for Better AI Analysis ### Provide Rich Context - Use descriptive log messages - Include relevant metadata - Add appropriate tags and correlation IDs ### Structured Logging - Use consistent log formats - Include structured data in context - Maintain clear log hierarchies ### Regular Review - Use AI explanations for learning - Build team knowledge base - Improve logging practices based on insights ## Integration with Other Features ### Comments & Collaboration - Share AI explanations with team members - Add AI insights to collaborative discussions - Build knowledge base from AI analysis ### Filtering & Search - Use AI insights to create better filters - Search for patterns identified by AI - Focus on AI-recommended log types ## Privacy and Security - **No Data Storage**: AI analysis doesn't store your log data - **Secure Processing**: All analysis happens securely - **Privacy Focused**: No sensitive information is retained ## Next Steps - [Comments & Collaboration](/platforms/python/products/logs/web-panel/comments-collaboration) - Share AI insights with your team - [Filtering & Search](/platforms/python/products/logs/web-panel/filtering-search) - Use AI insights to improve your searches - [Log Visualization](/platforms/python/products/logs/web-panel/log-visualization) - Enhanced understanding of log details --- # Alerts & Workflows ByteHide's alerting system helps you stay informed about critical events in your applications through automated notifications and workflow triggers. {% .lead %} ## Log Retention Notifications ByteHide automatically notifies you about log retention limits to help manage your data storage. ### Free Plan Retention - **7 Days**: Free plan includes 7 days of log retention - **Upgrade Prompt**: Notification suggests upgrading to Team plan for longer retention - **Visual Indicator**: Blue info banner displays retention status ## Alert Types ### Critical Error Alerts - **Automatic Detection**: Monitor for Critical and Error level logs - **Threshold Based**: Alert when error count exceeds limits - **Real-time Notifications**: Instant alerts for critical issues ### Performance Alerts - **Slow Operations**: Alert on performance degradation - **Resource Usage**: Monitor memory and CPU through logs - **Response Time**: Track application response times ### Security Alerts - **Authentication Failures**: Monitor failed login attempts - **Suspicious Activity**: Detect unusual access patterns - **Security Violations**: Alert on security-related events ### Custom Alerts - **Tag-based**: Create alerts based on specific log tags - **Message Content**: Alert on specific log message patterns - **User Activity**: Monitor specific user actions ## Alert Configuration ### Alert Rules Configure alerts based on: - **Log Level**: Critical, Error, Warn, Info - **Time Window**: Alert frequency and timing - **Threshold**: Number of occurrences before alerting - **Conditions**: Complex filtering criteria ### Notification Methods - **Email**: Send alerts to team email addresses - **Webhook**: Integrate with external systems - **Dashboard**: In-app notifications - **Mobile**: Push notifications (if available) ## Workflow Automation ### Incident Response - **Auto-Escalation**: Escalate unresolved alerts - **Team Notification**: Alert relevant team members - **Ticket Creation**: Automatically create support tickets ### Integration Triggers - **Slack Integration**: Send alerts to Slack channels - **Teams Integration**: Microsoft Teams notifications - **PagerDuty**: Critical alert escalation - **Custom Webhooks**: Integrate with any external system ### Auto-Resolution - **Resolution Detection**: Automatically close alerts when issues resolve - **Follow-up Actions**: Trigger post-resolution workflows - **Report Generation**: Create incident summary reports ## Alert Management ### Alert Dashboard View and manage all alerts from a central dashboard: - **Active Alerts**: Currently triggered alerts - **Alert History**: Past alert activity - **Performance Metrics**: Alert response times - **Team Activity**: Who responded to which alerts ### Alert States - **Triggered**: Alert condition met - **Acknowledged**: Team member acknowledged alert - **Investigating**: Investigation in progress - **Resolved**: Issue resolved and alert closed ## Team Collaboration ### Alert Assignment - **Auto-Assignment**: Assign alerts based on rules - **Manual Assignment**: Team members can claim alerts - **Escalation**: Escalate unassigned alerts ### Communication - **Alert Comments**: Add comments to alert investigations - **Status Updates**: Update alert status with context - **Team Notifications**: Keep team informed of progress ## Configuration Examples ### Critical Error Alert ``` Trigger: Level is Critical Time Window: 1 minute Threshold: 1 occurrence Notification: Email + Slack ``` ### Performance Degradation Alert ``` Trigger: Tags contains "slow" AND Level is Warn Time Window: 5 minutes Threshold: 10 occurrences Notification: Email to DevOps team ``` ### Security Alert ``` Trigger: Tags contains "security" OR Message contains "unauthorized" Time Window: 1 minute Threshold: 1 occurrence Notification: Immediate email + PagerDuty ``` ## Best Practices ### Alert Design - **Actionable**: Ensure alerts lead to specific actions - **Clear Context**: Include enough information for investigation - **Appropriate Urgency**: Match notification method to severity ### Noise Reduction - **Threshold Tuning**: Adjust thresholds to reduce false positives - **Time Windows**: Use appropriate time windows for grouping - **Suppression**: Suppress duplicate or related alerts ### Team Coordination - **Clear Ownership**: Define who responds to which alerts - **Escalation Paths**: Establish clear escalation procedures - **Documentation**: Document common alert responses ## Integration Setup ### Webhook Configuration ```json { "url": "https://your-system.com/webhook", "method": "POST", "headers": { "Authorization": "Bearer your-token" } } ``` ### Slack Integration - Connect your Slack workspace - Choose notification channels - Configure message format - Set up threaded conversations ## Monitoring and Analytics ### Alert Metrics - **Response Time**: How quickly alerts are acknowledged - **Resolution Time**: Time from alert to resolution - **False Positive Rate**: Percentage of invalid alerts - **Coverage**: Percentage of issues caught by alerts ### Reporting - **Daily Summaries**: Alert activity summaries - **Trend Analysis**: Alert volume and pattern trends - **Team Performance**: Response time analytics - **System Health**: Overall application health metrics ## Next Steps - [Security Settings](/platforms/python/products/logs/web-panel/security-settings) - Configure access and security for alerts - [Comments & Collaboration](/platforms/python/products/logs/web-panel/comments-collaboration) - Collaborate on alert investigations - [Filtering & Search](/platforms/python/products/logs/web-panel/filtering-search) - Use alerts to improve log filtering --- # Comments & Collaboration ByteHide's commenting system enables team collaboration on log analysis, allowing developers to share insights, discuss issues, and build collective knowledge. {% .lead %} ## Comments Feature Each log entry supports collaborative comments for team discussion and knowledge sharing. ![Comment Button](/images/dotnet/logs/dashboard/log-comment-button.png) ## How to Add Comments 1. **Open Log Details**: Click on any log entry to view details 2. **Access Comments Tab**: Select the "Comments" tab in the modal 3. **Write Comment**: Type your comment in the text area 4. **Send**: Click "Send comment" to post ![Add Comment](/images/dotnet/logs/dashboard/log-comment-add.png) ## Comment Interface ### Comment Composition - **Text Area**: Large text input for detailed comments - **User Info**: Shows your name and email (e.g., "John Smith, john.smith@company.com") - **Send Button**: Blue "Send comment" button to post ### Comment Display - **Empty State**: "There are no comments yet" when no comments exist - **Encouragement**: "Be the first one to write a comment" - **Mentions**: Use "@" to mention team members ![Tag Team Members](/images/dotnet/logs/dashboard/log-comment-tag.png) ## Collaboration Use Cases ### Debugging Sessions - **Issue Discussion**: Team members discuss error causes - **Solution Sharing**: Share fixes and workarounds - **Knowledge Transfer**: Document discoveries for future reference ### Code Reviews - **Log Quality**: Comment on log message quality - **Best Practices**: Suggest logging improvements - **Pattern Recognition**: Identify recurring issues ### Incident Response - **Real-time Communication**: Coordinate during incidents - **Timeline Documentation**: Record investigation steps - **Resolution Tracking**: Document how issues were resolved ### Knowledge Building - **Context Explanation**: Explain business context of logs - **Documentation**: Create inline documentation - **Training**: Help junior developers understand complex logs ## Comment Features ### User Identification Comments show: - **Name**: Commenter's display name - **Email**: Associated email address - **Timestamp**: When the comment was posted ### Mention System - **@ Mentions**: Tag team members for attention - **Notifications**: Mentioned users receive notifications - **Team Collaboration**: Bring relevant people into discussions ### Rich Text Support - **Formatting**: Basic text formatting options - **Code Snippets**: Include code examples in comments - **Links**: Share relevant documentation or resources ## Team Collaboration Benefits ### Shared Knowledge - **Collective Intelligence**: Leverage team expertise - **Documentation**: Build searchable knowledge base - **Learning**: Share insights across skill levels ### Faster Resolution - **Multiple Perspectives**: Get different viewpoints on issues - **Experience Sharing**: Learn from team members' experiences - **Parallel Investigation**: Multiple team members can contribute ### Quality Improvement - **Peer Review**: Review each other's analysis - **Best Practices**: Share logging and debugging techniques - **Pattern Recognition**: Identify systemic issues together ## Comment Management ### Threading - Comments maintain chronological order - Easy to follow conversation flow - Clear attribution to comment authors ### Persistence - Comments remain with log entries permanently - Historical context preserved - Searchable for future reference ### Privacy - Comments visible to team members - Secure within your organization - No external access ## Integration with Other Features ### AI Assistant - **AI + Human**: Combine AI explanations with human insights - **Context Enhancement**: Add human context to AI analysis - **Learning**: Use AI insights to inform human discussions ### Filtering & Search - **Commented Logs**: Find logs with team discussions - **Knowledge Mining**: Search through comment content - **Pattern Discovery**: Identify frequently discussed issues ## Best Practices ### Effective Comments - **Be Descriptive**: Provide clear, detailed explanations - **Include Context**: Add business or technical context - **Reference Solutions**: Link to fixes or documentation ### Team Guidelines - **Response Time**: Establish comment response expectations - **Escalation**: When to escalate from comments to direct communication - **Documentation**: Use comments to build team knowledge base ### Comment Etiquette - **Professional Tone**: Maintain professional communication - **Constructive Feedback**: Provide helpful, actionable insights - **Acknowledgment**: Recognize others' contributions ## Notifications - **Real-time Updates**: See new comments as they appear - **Mention Alerts**: Get notified when mentioned - **Activity Tracking**: Track comment activity across logs ## Next Steps - [AI Assistant](/platforms/python/products/logs/web-panel/ai-assistant) - Enhance discussions with AI insights - [Alerts & Workflows](/platforms/python/products/logs/web-panel/alerts-workflows) - Set up automated notifications - [Log Visualization](/platforms/python/products/logs/web-panel/log-visualization) - Better understand logs for discussion --- # Filtering & Search ByteHide provides powerful filtering and search capabilities to help you quickly find specific logs and identify patterns in your application data. {% .lead %} ## Add Filters Use the "Add filters" button to create custom filters for your log search. ![Log Filters](/images/dotnet/logs/dashboard/log-filters.png) ### Available Filter Types The filter dropdown provides multiple options: - **level**: Filter by log level (Info, Warn, Error, Critical) - **tags**: Filter by log tags - **message**: Search within log messages - **correlation_id**: Find logs by correlation ID - **metadata**: Filter by metadata fields - **hostname**: Filter by source hostname - **user_id**: Filter by authenticated user ID - **user_email**: Filter by user email - **user_token**: Filter by user authentication token ![Filter Options](/images/dotnet/logs/dashboard/log-filters-dropdown.png) ## Filter Operations Each filter supports different operations: ### Text Filters - **contains**: Search for text within the field - **equals**: Exact match - **starts with**: Begins with specified text - **ends with**: Ends with specified text ### Level Filters - **is**: Exact level match (critical, error, warn, info) - **is not**: Exclude specific levels ### Example Filters Common filter combinations: ``` Level is critical Tags contains payment Message contains timeout ``` ![Active Filters](/images/dotnet/logs/dashboard/logs-filter-applied.png) ## Date Range Selection Control the time range of logs to display using the date picker. ![Date Range](/images/dotnet/logs/dashboard/log-date-range-button.png) ### Quick Date Options Pre-defined time ranges: - **Today**: Current day logs - **7 d**: Last 7 days - **15 d**: Last 15 days - **30 d**: Last 30 days ### Custom Date Range Select specific start and end dates using the calendar picker: - Click on the date range field - Navigate through months using arrow controls - Select start and end dates - Apply the custom range ![Date Picker](/images/dotnet/logs/dashboard/log-date-range-custom.png) ## Active Filters Display Active filters are shown as removable chips above the log list: - **Level is critical**: Shows level-based filtering - **Tags contains database**: Shows tag-based filtering - **Message contains connection**: Shows message content filtering Each filter chip includes an "X" button to remove individual filters. ## Reset Filters Use the "Reset" button to clear all active filters and return to the unfiltered log view. ![Reset Filters](/images/dotnet/logs/dashboard/log-reset-filters.png) ## Filter Combinations Combine multiple filters for precise log discovery: 1. **Error Investigation**: ``` Level is error Tags contains payment Date range: Last 7 days ``` 2. **User Activity Tracking**: ``` User_email contains user@company.com Message contains authentication ``` 3. **Performance Monitoring**: ``` Tags contains performance Level is warn ``` ## Search Tips - **Use specific terms**: More specific searches return better results - **Combine filters**: Use multiple criteria to narrow results - **Check spelling**: Ensure filter values match log content exactly - **Use correlation IDs**: Track related logs across requests - **Filter by time**: Narrow down to specific time periods ## Real-time Filtering Filters apply in real-time as you type, immediately updating the log display to show matching entries. ## Filter Persistence - Filters remain active while navigating the dashboard - Date ranges persist across page refreshes - Filter state is maintained during session ## Performance The filtering system is optimized for: - **Fast response**: Results appear instantly - **Large datasets**: Efficiently handles thousands of logs - **Complex queries**: Multiple simultaneous filters - **Real-time updates**: New logs automatically match active filters ## Next Steps - [AI Assistant](/platforms/python/products/logs/web-panel/ai-assistant) - Get AI-powered analysis of filtered logs - [Log Visualization](/platforms/python/products/logs/web-panel/log-visualization) - View detailed log information - [Comments & Collaboration](/platforms/python/products/logs/web-panel/comments-collaboration) - Share filtered views with team members --- # Log Visualization The ByteHide web panel provides a comprehensive interface to visualize and analyze all logs from your Python applications in real-time. {% .lead %} ## Main Log View The main dashboard displays all your logs in a clean, organized table format. ![Main Dashboard](/images/dotnet/logs/dashboard/main-dashboard.png) ### Log List Features - **Message**: The main log message content - **Level**: Log level with color-coded badges (Info, Warn, Error, Critical) - **Time**: Timestamp when the log was generated - **Actions**: Access to detailed view and AI explanations ### Log Levels Each log level is displayed with distinct visual indicators: - **Info**: Blue badge for informational messages - **Warn**: Orange badge for warnings - **Error**: Red badge for errors - **Critical**: Dark red badge for critical issues ## Detailed Log View Click on any log entry to see comprehensive details in a modal window. ![Log Details](/images/dotnet/logs/dashboard/log-details.png) ### Details Panel The details panel shows: - **Time**: Exact timestamp - **Level**: Log severity level - **Hostname**: Source machine name - **Tags**: Associated tags for categorization ### User Information When available, authenticated user details are displayed: - **ID**: User identifier - **Email**: User email address - **Token**: Authentication token (masked for security) ### Multiple Tabs The detail view organizes information into tabs: - **Log message**: The main log content - **Context**: Additional context data - **Metadata**: Technical metadata and caller information - **Exception**: Exception details if applicable - **Location**: Source code location - **Stacktrace**: Full stack trace for errors ![Log Tabs](/images/dotnet/logs/dashboard/log-tabs.png) ## Context Information The Context tab shows structured data passed with the log: ```json { "ERROR": { "message": "Database connection failed: timeout after 30 seconds" }, "REQUEST_ID": "req_98f5d4e2a1", "USER_ID": "user_12345" } ``` ## Metadata View The Metadata tab displays technical information: - **CallerInfo**: Method, file, and line number - **StackTrace**: Full call stack - **Context**: Additional application context like version ![Log Metadata](/images/dotnet/logs/dashboard/log-metadata.png) ### Example Metadata Structure ```json { "metadata": { "CallerInfo": { "method": "ProcessPayment", "file": "/src/Services/PaymentService.cs", "line": 142, "stackTrace": "at PaymentService.ProcessPayment() in /src/Services/PaymentService.cs:line 142\n at OrderController.CreateOrder() in /src/Controllers/OrderController.cs:line 87" }, "Context": { "AppVersion": "2.1.4", "Environment": "Production", "CorrelationId": "order_abc123" } } } ``` ## Location Details Shows the exact source code location where the log was generated: - File path - Line numbers - Method names - Stack trace navigation ![Log Location](/images/dotnet/logs/dashboard/log-location.png) ## Real-time Updates Logs appear in real-time as your application generates them, allowing for: - Live monitoring during development - Real-time debugging of production issues - Immediate visibility into application behavior ## Pagination Navigate through large log volumes with: - **Rows per page**: Configurable (10, 20, 50, etc.) - **Page navigation**: Previous/next controls - **Total count**: Display of current range (e.g., "11-20 of 28") ![Log Pagination](/images/dotnet/logs/dashboard/log-pagination.png) ## Quick Actions Each log entry provides instant access to: - **View Details**: Expand full log information - **AI Explanation**: Get AI-powered analysis of the log - **Copy**: Copy log details to clipboard ## Visual Indicators The interface uses clear visual cues: - **Color-coded levels**: Instant recognition of log severity - **Expandable rows**: Click to see more details - **Status badges**: Clear identification of log types - **Timestamps**: Easy time-based log correlation ## Next Steps - [Filtering & Search](/platforms/python/products/logs/web-panel/filtering-search) - Learn how to filter and search logs - [AI Assistant](/platforms/python/products/logs/web-panel/ai-assistant) - Get AI-powered log analysis - [Comments & Collaboration](/platforms/python/products/logs/web-panel/comments-collaboration) - Collaborate on log analysis --- # Security Settings ByteHide provides comprehensive security settings to protect your log data and control access to your logging infrastructure. {% .lead %} ## Project Token Management Your project token is the primary authentication mechanism for ByteHide Logger. ![Project Token](/images/dotnet/logs/dashboard/log-security-reset-token.png) ### Current Token - **Token Display**: Project token shown as `bh_rD13Y...` (partially masked for security) - **Copy Function**: "Copy this token into your project configuration file" button - **Secure Storage**: Store token securely in your application configuration ### Token Security - **Unique Identifier**: Each project has a unique token - **Authentication**: Required for all logging operations - **Rotation**: Tokens can be reset when compromised ## Project Usage Monitoring Track your project's logging usage and data consumption. ![Project Usage](/images/dotnet/logs/dashboard/log-security-usage.png) ### Usage Metrics - **Month**: Monthly usage tracking (e.g., "2025-06") - **Stored Data (MB)**: Amount of log data stored (e.g., "0.38 MB") - **Total Data Scanned (MB)**: Total data processed (e.g., "28.54 MB") ### Data Management - Monitor storage consumption - Track data processing volumes - Plan capacity based on usage trends ## Custom Headers Configure custom headers for secure API requests and additional authentication. ![Custom Headers](/images/dotnet/logs/dashboard/log-security-headers.png) ### Header Configuration - **Add Header**: Button to add new custom headers - **Security Enhancement**: Add custom headers to secure your requests - **API Integration**: Support for custom API authentication ### Use Cases - **Additional Authentication**: Layer extra security on API calls - **Request Identification**: Add unique identifiers to requests - **Compliance**: Meet specific security compliance requirements ## IP Whitelist Control access to your logging infrastructure by restricting allowed IP addresses. ![IP Whitelist](/images/dotnet/logs/dashboard/log-security-ip.png) ### Whitelist Configuration - **IP Entry**: Text area for entering allowed IP addresses - **One Per Line**: Enter one complete IP address per line - **IPv4 Support**: Currently supports IPv4 addresses only - **Save IPs**: Button to apply whitelist changes ### Security Benefits - **Access Control**: Limit which networks can send logs - **Threat Reduction**: Prevent unauthorized log submissions - **Compliance**: Meet network security requirements ### Example Configuration ``` 192.168.1.100 10.0.0.50 203.0.113.25 ``` ## Token Reset Reset your project token when security is compromised or for routine security maintenance. ![Reset Token](/images/dotnet/logs/dashboard/log-security-reset-token.png) ### Reset Process - **Reset Button**: Red "Reset project Token" button - **Immediate Effect**: Token reset takes effect immediately - **Update Required**: Update all applications with new token after reset ### When to Reset - **Security Breach**: When token may be compromised - **Team Changes**: When team members leave - **Routine Security**: As part of regular security practices - **Compliance**: To meet security audit requirements ## Security Best Practices ### Token Management - **Secure Storage**: Store tokens in secure configuration systems - **Environment Variables**: Use environment variables, not hard-coded values - **Regular Rotation**: Rotate tokens periodically - **Access Limitation**: Limit who has access to tokens ### Network Security - **IP Restrictions**: Use IP whitelist for production environments - **VPN Access**: Consider VPN requirements for log access - **Network Monitoring**: Monitor for unusual network activity ### Access Control - **Team Permissions**: Control who can access security settings - **Audit Logging**: Track changes to security configurations - **Regular Reviews**: Periodically review access permissions ## Configuration Steps ### Initial Setup 1. **Copy Token**: Copy project token from settings 2. **Configure Application**: Add token to your .NET application 3. **Test Connection**: Verify logging works correctly 4. **Set IP Whitelist**: Add your application server IPs ### Security Hardening 1. **Enable IP Whitelist**: Restrict access to known IPs 2. **Add Custom Headers**: Implement additional authentication 3. **Monitor Usage**: Regularly check usage metrics 4. **Schedule Token Rotation**: Plan regular token updates ## Compliance Features ### Data Protection - **Encryption**: All data encrypted in transit and at rest - **Access Logging**: Track all access to log data - **Retention Controls**: Configure data retention periods - **Geographic Controls**: Control data processing locations ### Audit Trail - **Configuration Changes**: Log all security setting changes - **Access Records**: Maintain records of data access - **Token Usage**: Track token usage patterns - **IP Access**: Log IP address access attempts ## Troubleshooting ### Common Issues - **Authentication Failures**: Verify token is correct and active - **IP Blocking**: Check if IP is in whitelist - **Custom Headers**: Ensure headers are properly configured - **Token Expiry**: Confirm token hasn't been reset ### Diagnostic Steps 1. **Verify Token**: Check token matches settings 2. **Test Network**: Confirm IP is whitelisted 3. **Check Headers**: Validate custom header configuration 4. **Review Logs**: Check for authentication error messages ## Next Steps - [Log Visualization](/platforms/python/products/logs/web-panel/log-visualization) - View logs with proper security settings - [Alerts & Workflows](/platforms/python/products/logs/web-panel/alerts-workflows) - Set up security-related alerts - [Project Token Configuration](/platforms/python/products/logs/configuration/project-token) - Learn more about token configuration --- # Monitor — Runtime Application Self-Protection > Runtime Application Self-Protection (RASP) with real-time threat detection and prevention. ## Monitor — Android # Block Action **Action Type:** `BLOCK` Prevents potentially dangerous requests and operations from executing when a security threat is detected. **Available for:** Cloud protection modules (Mobile and Desktop) --- ## How It Works When the Block action is triggered: 1. The detected malicious operation is intercepted 2. The operation is prevented from executing 3. The application continues running normally 4. A security incident is logged for analysis The Block action provides a middle ground between allowing all operations (Log action) and terminating the application (Close action). --- ## When to Use **Recommended for:** - Blocking suspicious API requests detected as malicious - Preventing unauthorized cloud operations - Stopping data exfiltration attempts - Intercepting command injection attacks **Not recommended for:** - Local protection modules (not currently supported) - Scenarios requiring complete application termination --- ## Cloud Protection Modules > **Cloud Protection Coming Soon** > Cloud protection modules for the Android SDK are coming soon. When available for the Java SDK, they will enable real-time API call filtering, threat-based request blocking, secure cloud communication validation, and anomaly detection in cloud operations. The Block action is currently supported only for cloud-based protection modules. These modules analyze network requests, API calls, and cloud-based threats. Standard local protection modules do not yet support the Block action in the Android SDK. --- ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "NetworkTampering", "action": "block", "interval": 1000 } ] } ``` ### Code-Based Configuration (Kotlin) ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.NETWORK_TAMPERING, ActionType.BLOCK, 1000 ) } ``` ### Code-Based Configuration (Java) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.NETWORK_TAMPERING, ActionType.BLOCK, 1000 ); }); ``` --- ## Best Practices - **Layer Defenses**: Combine Block with Log actions on other modules - **Monitor Blocked Operations**: Track which operations are being blocked to understand attack patterns - **Test Thoroughly**: Ensure legitimate operations are not blocked by testing cloud integration - **Review Logs**: Regularly review logs of blocked operations for security insights --- ## Related Actions --- # Close Action **Action Type:** `CLOSE` Terminates the application immediately when a security threat is detected by the Monitor. **Available for:** All platforms (Mobile and Desktop) --- ## How It Works When the Close action is triggered, the application process exits entirely using `System.exit(1)`. This prevents any further execution of potentially compromised code and ensures the threat cannot propagate. --- ## When to Use **Recommended for:** - Financial applications handling payment data - Healthcare apps with HIPAA-protected information - Government or military applications - Apps managing cryptographic keys or tokens **Not recommended for:** - Applications requiring graceful shutdown - Apps that need to flush pending data before termination - Services requiring cleanup operations --- ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "DebuggerDetection", "action": "close", "interval": 5000 }, { "type": "MemoryDumpDetection", "action": "close", "interval": 3000 } ] } ``` ### Code-Based Configuration (Kotlin) ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.CLOSE, 5000 ) config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.CLOSE, 3000 ) } ``` ### Code-Based Configuration (Java) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.CLOSE, 5000 ); config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.CLOSE, 3000 ); }); ``` --- ## Code Examples ### Using System.exit() When a threat is detected, the application will immediately call `System.exit(1)`: ```kotlin import com.bytehide.monitor.Monitor Monitor.configure { config -> config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.CLOSE, 5000 ) } // When threat is detected: // System.exit(1) is called internally ``` ### Using Android Process Termination API For Android applications, you can alternatively use the native Android process termination API: ```kotlin import android.os.Process // Kill the current process using Android API Process.killProcess(Process.myPid()) ``` Or in Java: ```java import android.os.Process; // Kill the current process using Android API Process.killProcess(Process.myPid()); ``` The Monitor framework uses `System.exit(1)` internally, but both approaches achieve the same result: immediate process termination. ### Exit Code Details The Close action uses the following exit codes: - **Exit Code 1**: Standard abnormal termination due to security threat detection - **Exit Code 0**: Reserved for normal application exit (not used by Close action) Exit code 1 indicates to the operating system that the application terminated abnormally due to a detected threat. ### Interval Configuration The `intervalMs` parameter determines how frequently Monitor checks for threats: - **Shorter intervals** (e.g., 1000ms): More frequent checks, faster threat response, higher CPU usage - **Longer intervals** (e.g., 10000ms): Less frequent checks, lower overhead, delayed threat response For the Close action, recommended intervals are **3000ms to 5000ms** for optimal security without excessive performance impact. --- ## Important Considerations The Close action provides no opportunity for graceful shutdown, data flushing, or cleanup operations. If your application requires graceful termination, consider: - Using the Log action in combination with manual shutdown logic - Using the Custom action to implement cleanup before exit - Using the Erase action to wipe sensitive data before termination --- ## Best Practices - **Pair with Logging**: Use the Log action on other modules to detect patterns before Close is triggered - **Test Thoroughly**: Ensure your application handles unexpected termination gracefully - **Monitor Exit Behavior**: Track application crashes in your analytics to detect when Close is triggered - **Combine with Custom Actions**: Use Custom actions on less critical modules for more nuanced responses - **Document Sensitive Modules**: Clearly identify which modules should trigger Close for security-critical operations --- ## Related Actions --- # Custom Action **Action Type:** `CUSTOM` Execute your own handler logic when security threats are detected. This is the most flexible action type, enabling advanced threat response scenarios. **Available for:** All platforms (Mobile and Desktop) --- ## How It Works Custom actions provide complete control over threat response: 1. Receive detailed threat information (type, confidence, metadata) 2. Analyze threat properties 3. Execute custom business logic 4. Send notifications or alerts 5. Track analytics and monitoring 6. Continue, suspend, or terminate the application --- ## When to Use **Recommended for:** - Integration with analytics and monitoring systems - Sending notifications to security teams - Displaying user-friendly security alerts - Conditional responses based on threat severity - Implementing complex business-specific logic **Not recommended for:** - Simple binary responses (use Log, Close, or Erase instead) - Performance-critical code paths (handlers should be lightweight) --- ## Threat Information Available When your custom handler is invoked, you receive a threat object with these properties: **Kotlin (property syntax):** - `threat.threatType`: Classification of detected threat (String) - `threat.description`: Human-readable threat description (String) - `threat.confidence`: Confidence score 0.0-1.0 (Double) - `threat.metadata`: Additional context data (Map) - `threat.isThreatDetected()`: Boolean indicating if threat was confirmed **Java (getter syntax):** - `threat.getThreatType()`: Classification of detected threat - `threat.getDescription()`: Human-readable threat description - `threat.getConfidence()`: Confidence score 0.0-1.0 - `threat.getMetadata()`: Additional context data - `threat.isThreatDetected()`: Boolean indicating if threat was confirmed --- ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "DebuggerDetection", "action": "log_threat", "interval": 2000 }, { "type": "MemoryDumpDetection", "action": "email_alert", "interval": 1000 }, { "type": "TamperingDetection", "action": "track_analytics", "interval": 3000 } ] } ``` --- ## Code Examples ### Basic Custom Action (Kotlin) Register a simple custom action that logs threat information: ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.registerCustomAction("log_threat") { threat -> println("Threat detected: ${threat.threatType}") println("Description: ${threat.description}") println("Confidence: ${(threat.confidence * 100).toInt()}%") } config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, "log_threat", 2000 ) } ``` ### Basic Custom Action (Java) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.registerCustomAction("log_threat", threat -> { System.out.println("Threat detected: " + threat.getThreatType()); System.out.println("Description: " + threat.getDescription()); System.out.println("Confidence: " + (int)(threat.getConfidence() * 100) + "%"); }); config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, "log_threat", 2000 ); }); ``` ### Custom Action with User Dialog (Kotlin) Display an alert to the user with conditional actions: ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.protection.ProtectionModuleType import android.app.AlertDialog import android.content.Context Monitor.configure { config -> config.registerCustomAction("show_user_alert") { threat -> val dialogBuilder = AlertDialog.Builder(context) dialogBuilder.setTitle("Security Warning") dialogBuilder.setMessage(buildString { appendLine("A security issue was detected:") appendLine(threat.description) appendLine("\nConfidence: ${(threat.confidence * 100).toInt()}%") appendLine("\nPlease update your app or contact support.") }) dialogBuilder.setPositiveButton("Restart App") { dialog, _ -> dialog.dismiss() System.exit(1) } dialogBuilder.setNegativeButton("Continue") { dialog, _ -> dialog.dismiss() } dialogBuilder.setCancelable(false) dialogBuilder.show() } config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, "show_user_alert", 2000 ) } ``` ### Custom Action with User Dialog (Java) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.protection.ProtectionModuleType; import android.app.AlertDialog; Monitor.configure(config -> { config.registerCustomAction("show_user_alert", threat -> { new AlertDialog.Builder(context) .setTitle("Security Warning") .setMessage("A security issue was detected:\n" + threat.getDescription() + "\n\n" + "Confidence: " + (int)(threat.getConfidence() * 100) + "%\n\n" + "Please update your app or contact support.") .setPositiveButton("Restart App", (dialog, which) -> { dialog.dismiss(); System.exit(1); }) .setNegativeButton("Continue", (dialog, which) -> dialog.dismiss()) .setCancelable(false) .show(); }); config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, "show_user_alert", 2000 ); }); ``` ### Custom Action with Analytics Tracking (Kotlin) Track security threats in your analytics system: ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.protection.ProtectionModuleType import com.google.firebase.analytics.FirebaseAnalytics import android.os.Bundle Monitor.configure { config -> config.registerCustomAction("track_analytics") { threat -> val analytics = FirebaseAnalytics.getInstance(context) val bundle = Bundle() bundle.putString("threat_type", threat.threatType) bundle.putString("description", threat.description) bundle.putDouble("confidence", threat.confidence) bundle.putLong("timestamp", System.currentTimeMillis()) // Add metadata if available threat.metadata?.forEach { (key, value) -> bundle.putString("metadata_$key", value.toString()) } analytics.logEvent("security_threat", bundle) } config.addProtection( ProtectionModuleType.TAMPERING_DETECTION, "track_analytics", 3000 ) } ``` ### Custom Action with Analytics Tracking (Java) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.protection.ProtectionModuleType; import com.google.firebase.analytics.FirebaseAnalytics; import android.os.Bundle; Monitor.configure(config -> { config.registerCustomAction("track_analytics", threat -> { FirebaseAnalytics analytics = FirebaseAnalytics.getInstance(context); Bundle bundle = new Bundle(); bundle.putString("threat_type", threat.getThreatType()); bundle.putString("description", threat.getDescription()); bundle.putDouble("confidence", threat.getConfidence()); bundle.putLong("timestamp", System.currentTimeMillis()); // Add metadata if available if (threat.getMetadata() != null) { threat.getMetadata().forEach((key, value) -> bundle.putString("metadata_" + key, value.toString()) ); } analytics.logEvent("security_threat", bundle); }); config.addProtection( ProtectionModuleType.TAMPERING_DETECTION, "track_analytics", 3000 ); }); ``` ### Conditional Response Based on Threat Type (Kotlin) Execute different logic for different threat types: ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.registerCustomAction("conditional_response") { threat -> when (threat.threatType) { "DEBUGGER_ATTACHED" -> { // Debugger detected - immediate exit println("Debugger detected: ${threat.description}") System.exit(1) } "MEMORY_CORRUPTION" -> { // Memory issue - clear sensitive data first println("Memory corruption detected - erasing data") clearSensitiveData(context) System.exit(1) } "JAILBREAK_DETECTED" -> { // Jailbreak detected - send alert println("Jailbreak detected") sendSecurityAlert(threat) } "UNUSUAL_ACTIVITY" -> { // Low confidence threat - just log it if (threat.confidence < 0.70) { println("Low confidence threat logged: ${threat.description}") } } else -> { // Default behavior - log unknown threat println("Unknown threat: ${threat.threatType}") } } } config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, "conditional_response", 2000 ) } ``` ### Conditional Response Based on Threat Type (Java) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.registerCustomAction("conditional_response", threat -> { String threatType = threat.getThreatType(); switch (threatType) { case "DEBUGGER_ATTACHED": System.out.println("Debugger detected: " + threat.getDescription()); System.exit(1); break; case "MEMORY_CORRUPTION": System.out.println("Memory corruption detected - erasing data"); clearSensitiveData(context); System.exit(1); break; case "JAILBREAK_DETECTED": System.out.println("Jailbreak detected"); sendSecurityAlert(threat); break; case "UNUSUAL_ACTIVITY": if (threat.getConfidence() < 0.70) { System.out.println("Low confidence threat logged: " + threat.getDescription()); } break; default: System.out.println("Unknown threat: " + threatType); } }); config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, "conditional_response", 2000 ); }); ``` ### Multiple Custom Actions (Kotlin) Register different handlers for different modules with different behaviors: ```kotlin Monitor.configure { config -> // Action 1: Simple logging config.registerCustomAction("log_all_threats") { threat -> println("Threat logged: ${threat.threatType} (${(threat.confidence * 100).toInt()}%)") } // Action 2: Alert on high confidence threats config.registerCustomAction("alert_high_confidence") { threat -> if (threat.confidence >= 0.85) { sendSecurityAlert(threat) System.exit(1) } } // Action 3: Track specific threat types config.registerCustomAction("track_debugger") { threat -> if (threat.threatType == "DEBUGGER_ATTACHED") { recordDebuggerEvent(threat) } } // Action 4: Conditional erase config.registerCustomAction("conditional_erase") { threat -> if (threat.confidence >= 0.95) { clearSensitiveData(context) System.exit(1) } } // Apply actions to different modules config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, "log_all_threats", 2000 ) config.addProtection( ProtectionModuleType.NETWORK_TAMPERING, "alert_high_confidence", 2000 ) config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, "track_debugger", 1000 ) config.addProtection( ProtectionModuleType.PROCESS_INJECTION, "conditional_erase", 2000 ) } ``` ### Multiple Custom Actions (Java) ```java Monitor.configure(config -> { // Action 1: Simple logging config.registerCustomAction("log_all_threats", threat -> System.out.println("Threat logged: " + threat.getThreatType() + " (" + (int)(threat.getConfidence() * 100) + "%)") ); // Action 2: Alert on high confidence threats config.registerCustomAction("alert_high_confidence", threat -> { if (threat.getConfidence() >= 0.85) { sendSecurityAlert(threat); System.exit(1); } }); // Action 3: Track specific threat types config.registerCustomAction("track_debugger", threat -> { if (threat.getThreatType().equals("DEBUGGER_ATTACHED")) { recordDebuggerEvent(threat); } }); // Action 4: Conditional erase config.registerCustomAction("conditional_erase", threat -> { if (threat.getConfidence() >= 0.95) { clearSensitiveData(context); System.exit(1); } }); // Apply actions to different modules config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, "log_all_threats", 2000 ); config.addProtection( ProtectionModuleType.NETWORK_TAMPERING, "alert_high_confidence", 2000 ); config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, "track_debugger", 1000 ); config.addProtection( ProtectionModuleType.PROCESS_INJECTION, "conditional_erase", 2000 ); }); ``` --- ## Error Handling Implement safe error handling in your custom actions to prevent handler failures from crashing the application: ```kotlin config.registerCustomAction("safe_handler") { threat -> try { // Your custom logic here sendSecurityAlert(threat) trackAnalytics(threat) } catch (e: Exception) { // Fallback behavior - log and exit safely System.err.println("Handler error: ${e.message}") e.printStackTrace() // Attempt graceful fallback try { clearCriticalData(context) } catch (fallbackError: Exception) { fallbackError.printStackTrace() } System.exit(1) } } ``` --- ## Best Practices - **Keep Handlers Fast**: Minimize processing in custom actions to avoid blocking threat detection - **Avoid Sensitive Operations**: Don't call risky APIs in threat handlers that might be intercepted - **Log Everything**: Record all threat occurrences for later analysis - **Test Thoroughly**: Test custom actions with realistic threat scenarios - **Combine Actions**: Use multiple custom actions for comprehensive threat response - **Monitor Performance**: Track performance impact of custom action execution - **Implement Fallbacks**: Provide default behavior if custom handlers fail - **Use Confidence Levels**: Implement different behaviors based on threat confidence scores - **Metadata Analysis**: Leverage metadata for context-aware responses - **Timeout Protection**: Keep handler execution time short to prevent timing issues --- ## DetectionResult Properties When accessing threat properties in custom handlers, use these available properties: **Kotlin (property accessors):** - `threat.threatType` (String): Type of threat detected - `threat.description` (String): Detailed description - `threat.confidence` (Double): Confidence score (0.0-1.0) - `threat.metadata` (Map): Additional context - `threat.isThreatDetected()` (Boolean): Confirmed threat status **Java (getter methods):** - `threat.getThreatType()`: Type of threat detected - `threat.getDescription()`: Detailed description - `threat.getConfidence()`: Confidence score (0.0-1.0) - `threat.getMetadata()`: Additional context - `threat.isThreatDetected()`: Confirmed threat status --- ## Related Actions --- # Erase Action **Action Type:** `ERASE` Securely deletes sensitive data from your application before terminating the process. **Available for:** All platforms (Mobile and Desktop) --- ## How It Works When the Erase action is triggered, the Monitor framework: 1. Clears SharedPreferences containing sensitive data 2. Deletes private database files 3. Overwrites sensitive files with random data 4. Terminates the application process 5. Ensures no trace of sensitive information remains --- ## When to Use **Recommended for:** - Financial applications handling payment data - Applications with personal identifiable information (PII) - Apps managing health and medical records - Systems storing encryption keys and tokens - Any app with proprietary or classified data **Not recommended for:** - Applications without sensitive data - Scenarios where data preservation is required --- ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "DebuggerDetection", "action": "erase", "interval": 3000 }, { "type": "MemoryDumpDetection", "action": "erase", "interval": 3000 } ] } ``` ### Code-Based Configuration (Kotlin) ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.ERASE, 3000 ) config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.ERASE, 3000 ) } ``` ### Code-Based Configuration (Java) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.ERASE, 3000 ); config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.ERASE, 3000 ); }); ``` --- ## Code Examples ### Clearing SharedPreferences (Kotlin) Before the Erase action terminates your app, implement cleanup for SharedPreferences: ```kotlin import android.content.Context import android.content.SharedPreferences // Clear all SharedPreferences fun clearAllSharedPreferences(context: Context) { val sharedPreferences = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE) sharedPreferences.edit().clear().commit() } // Clear sensitive data only fun clearSensitiveData(context: Context) { val sharedPreferences = context.getSharedPreferences("secure_data", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() editor.remove("api_token") editor.remove("user_password") editor.remove("encryption_key") editor.commit() } ``` ### Clearing SharedPreferences (Java) ```java import android.content.Context; import android.content.SharedPreferences; // Clear all SharedPreferences public static void clearAllSharedPreferences(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE); sharedPreferences.edit().clear().commit(); } // Clear sensitive data only public static void clearSensitiveData(Context context) { SharedPreferences sharedPreferences = context.getSharedPreferences("secure_data", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.remove("api_token"); editor.remove("user_password"); editor.remove("encryption_key"); editor.commit(); } ``` ### Clearing Databases (Kotlin) ```kotlin import android.content.Context import android.database.sqlite.SQLiteDatabase // Clear all database contents fun clearDatabase(context: Context) { val dbPath = context.getDatabasePath("app_database.db").absolutePath val database = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE) database.execSQL("DELETE FROM users") database.execSQL("DELETE FROM sessions") database.execSQL("DELETE FROM credentials") database.execSQL("VACUUM") database.close() } ``` ### Clearing Databases (Java) ```java import android.content.Context; import android.database.sqlite.SQLiteDatabase; // Clear all database contents public static void clearDatabase(Context context) { String dbPath = context.getDatabasePath("app_database.db").getAbsolutePath(); SQLiteDatabase database = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE); database.execSQL("DELETE FROM users"); database.execSQL("DELETE FROM sessions"); database.execSQL("DELETE FROM credentials"); database.execSQL("VACUUM"); database.close(); } ``` ### Securely Deleting Files (Kotlin) ```kotlin import android.content.Context import java.io.File // Securely delete a file with data overwriting fun secureShredFile(file: File) { if (file.exists()) { val size = file.length() // Overwrite with random data file.outputStream().use { out -> out.write(ByteArray(size.toInt()) { kotlin.random.Random.nextByte() }) } // Delete the file file.delete() } } // Clear cache directory fun clearCacheDirectory(context: Context) { val cacheDir = context.cacheDir cacheDir.listFiles()?.forEach { file -> secureShredFile(file) } } // Clear app-specific sensitive files fun clearAppSensitiveFiles(context: Context) { val filesDir = context.filesDir filesDir.listFiles()?.forEach { file -> if (file.name.contains("sensitive") || file.name.contains("secret")) { secureShredFile(file) } } } ``` ### Securely Deleting Files (Java) ```java import android.content.Context; import java.io.File; import java.util.Random; // Securely delete a file with data overwriting public static void secureShredFile(File file) { if (file.exists()) { long size = file.length(); try (java.io.FileOutputStream out = new java.io.FileOutputStream(file)) { byte[] random = new byte[(int) size]; new Random().nextBytes(random); out.write(random); } catch (Exception e) { e.printStackTrace(); } file.delete(); } } // Clear cache directory public static void clearCacheDirectory(Context context) { File cacheDir = context.getCacheDir(); File[] files = cacheDir.listFiles(); if (files != null) { for (File file : files) { secureShredFile(file); } } } // Clear app-specific sensitive files public static void clearAppSensitiveFiles(Context context) { File filesDir = context.getFilesDir(); File[] files = filesDir.listFiles(); if (files != null) { for (File file : files) { if (file.getName().contains("sensitive") || file.getName().contains("secret")) { secureShredFile(file); } } } } ``` ### Erase with Custom Cleanup (Kotlin) For maximum control, use the Custom action to implement comprehensive cleanup before termination: ```kotlin Monitor.configure { config -> config.registerCustomAction("erase_with_cleanup") { threat -> val context = getApplicationContext() // Your Context instance // Clear SharedPreferences clearAllSharedPreferences(context) // Clear database clearDatabase(context) // Clear cache and files clearCacheDirectory(context) clearAppSensitiveFiles(context) // Log the security incident println("Critical threat detected: ${threat.description}") // Terminate the process System.exit(1) } } ``` --- ## Best Practices - **Combine with Logging**: Log the threat before erasing to preserve incident details - **Test Data Wipe**: Regularly test your data cleanup implementation - **Use Secure Methods**: Overwrite data multiple times for critical information - **Document Sensitive Data**: Know where all sensitive information is stored - **Verify Deletion**: Confirm that sensitive data is actually deleted, not just marked for deletion - **Back Up Critical Data**: Consider secure backup systems for critical non-sensitive data - **Multiple Overwrites**: For extremely sensitive data, overwrite multiple times with random bytes --- ## Related Actions --- # Log Action **Action Type:** `LOG` Records all detected security threats to the Monitor's internal logger while allowing the application to continue running normally. **Available for:** All platforms (Mobile and Desktop) --- ## How It Works When the Log action is triggered, the Monitor framework: 1. Captures complete threat details including type, confidence, and metadata 2. Records the incident with timestamp and detection context 3. Stores logs persistently for later analysis 4. Continues application execution without interruption --- ## When to Use **Recommended for:** - Production applications that need to monitor threats without disrupting user experience - Building historical security data - Triggering alerts or notifications - Investigating incidents after the fact - Applications requiring comprehensive threat intelligence **Not recommended for:** - Extremely sensitive applications where any threat should trigger termination - Real-time response scenarios where detection delays are unacceptable --- ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "MemoryDumpDetection", "action": "log", "interval": 2000 }, { "type": "DebuggerDetection", "action": "log", "interval": 1000 } ] } ``` ### Code-Based Configuration (Kotlin) ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.LOG, 2000 ) config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.LOG, 1000 ) } ``` ### Code-Based Configuration (Java) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.LOG, 2000 ); config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.LOG, 1000 ); }); ``` --- ## What Gets Logged The Monitor logger records the following information for each threat: - **Threat Type**: Classification of the detected threat (e.g., DEBUGGER_ATTACHED, MEMORY_CORRUPTION) - **Description**: Human-readable explanation of the threat - **Confidence Score**: Numerical confidence (0.0-1.0) indicating certainty of detection - **Timestamp**: Precise moment the threat was detected - **Module**: Which protection module detected the threat - **Metadata**: Additional context (e.g., debugger name, injection method) All logged incidents are reported to the [Cloud Panel](/platforms/android/products/monitor/cloud-panel/incidences), where you can review them, set up alerts, and export data for analysis. --- ## Interval Configuration The `intervalMs` parameter controls checking frequency: - **500-1000ms**: High-frequency monitoring for critical modules - **2000-3000ms**: Standard monitoring with balanced overhead - **5000ms+**: Low-frequency background monitoring For the Log action, shorter intervals are often acceptable since logging has minimal performance impact. --- ## Best Practices - **Always Log in Production**: Use Log action as a safety net for all modules - **Export Regularly**: Periodically export threat logs for analysis and compliance - **Set Alerts**: Configure external systems to monitor logs and trigger alerts - **Combine with Custom Actions**: Use Custom actions on high-risk modules for more aggressive responses - **Monitor Patterns**: Look for repeated threats indicating targeted attacks - **Maintain Log Hygiene**: Review and archive old logs regularly --- ## Related Actions --- # None Action **Action Type:** `NONE` Enable security threat detection while explicitly disabling any automated response. **Available for:** All platforms (Mobile and Desktop) --- ## How It Works When the None action is configured: 1. The Monitor detects all security threats as configured 2. Threat information is logged internally 3. No response action is taken 4. The application continues running normally 5. You retain complete visibility into detected threats --- ## When to Use **Recommended for:** - Development and testing environments - Analyzing detection accuracy - Benchmarking threat detection - Understanding false positive rates - Evaluating protection module sensitivity - Initial module configuration validation **Not recommended for:** - Production environments where threats require response - Critical security modules that must take action - Final application releases without active protection --- ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "DebuggerDetection", "action": "none", "interval": 2000 }, { "type": "MemoryDumpDetection", "action": "none", "interval": 1000 } ] } ``` ### Code-Based Configuration (Kotlin) ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.NONE, 2000 ) config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.NONE, 1000 ) } ``` ### Code-Based Configuration (Java) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.NONE, 2000 ); config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.NONE, 1000 ); }); ``` --- ## Code Examples Even with the None action, all detected threats are reported to the [Cloud Panel](/platforms/android/products/monitor/cloud-panel/incidences), where you can review detection patterns and false positive rates. ### Comparing Actions Across Modules Use the None action alongside other actions to compare detection coverage: ```kotlin Monitor.configure { config -> // Module 1: Passive detection only config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.NONE, 2000 ) // Module 2: Logging only config.addProtection( ProtectionModuleType.NETWORK_TAMPERING, ActionType.LOG, 2000 ) // Module 3: Aggressive response config.addProtection( ProtectionModuleType.TAMPERING_DETECTION, ActionType.CLOSE, 2000 ) // Module 4: Custom handling config.registerCustomAction("hybrid_response") { threat -> if (threat.confidence >= 0.90) { System.exit(1) } } config.addProtection( ProtectionModuleType.PROCESS_INJECTION, "hybrid_response", 2000 ) } ``` This mixed configuration allows you to observe detection patterns on some modules while protecting critical modules. --- ## Performance Impact The None action has minimal performance overhead: - Detection runs at configured intervals - No response processing overhead - Negligible memory impact - Suitable for production monitoring if needed --- ## Development Workflow Best Practices **Step 1: Initial Configuration** ```kotlin // Start all modules with None action config.addProtection(ProtectionModuleType.DEBUGGER_DETECTION, ActionType.NONE, 2000) config.addProtection(ProtectionModuleType.NETWORK_TAMPERING, ActionType.NONE, 2000) config.addProtection(ProtectionModuleType.JAILBREAK_DETECTION, ActionType.NONE, 2000) ``` **Step 2: Run Threat Scenarios** Test your application against various threat scenarios while monitoring detection. **Step 3: Analyze Results** Review incidents in the Cloud Panel to understand detection patterns and false positive rates. **Step 4: Tune Configuration** Adjust module sensitivity and confidence thresholds based on analysis. **Step 5: Transition to Production** Switch modules to appropriate actions (Log, Close, Custom) for production deployment. --- ## Best Practices - **Start with None**: Begin all protection module testing with the None action - **Gradually Enable Actions**: Transition modules to appropriate actions after validation - **Monitor False Positives**: Use None action results to identify false positive rates - **Document Thresholds**: Record which confidence levels trigger false positives - **Review Regularly**: Analyze detection logs to improve module configuration - **Never Deploy Production**: Avoid using None action in production for critical protections - **Collect Baseline Data**: Use None action to establish threat detection baselines - **Test Comprehensively**: Run all threat scenarios before transitioning to production actions --- ## Related Actions --- # Understand how Monitor actions work Monitor actions define how your application responds when a protection module detects a threat. Each module can be assigned its own action, so you can log low-confidence detections, block confirmed attacks, and terminate the application for critical threats. {% .lead %} --- ## Action Types ### SDK Actions These actions are available in JSON configuration and the Configuration API. They execute inside the application at the point where the threat is detected. | Action | Behavior | Use Case | |--------|----------|----------| | **[Close](actions/close)** | Terminates the application immediately | Critical threats on desktop/mobile (debugger attached, tampering detected) | | **[Log](actions/log)** | Records the incident and continues execution | Non-critical threats, monitoring, analytics | | **[Block](actions/block)** | Blocks the request and returns HTTP 403 | Web/API attacks (SQL injection, XSS, path traversal) | | **[Erase](actions/erase)** | Securely deletes sensitive data, then terminates | Financial or healthcare applications on compromised devices | | **[Custom](actions/custom)** | Executes your own async handler | SIEM integration, Slack alerts, custom escalation workflows | | **[None](actions/none)** | Detects the threat but takes no action | Development, testing, shadow mode before enforcing | ### Cloud Dashboard Actions These actions are available when configuring [Workflow Rules](/platforms/android/products/monitor/cloud-configuration#workflow-rules) in the Cloud Dashboard. They extend the SDK actions with network-level responses. | Action | Behavior | Use Case | |--------|----------|----------| | **Log incident** | Records the incident with full forensic context | Audit trail, compliance, analytics | | **Block** | Blocks the specific request or operation | Stop the attack in progress | | **Block session** | Invalidates the attacker's entire session | Prevent the attacker from continuing with a different payload | | **Block IP** | Blocks all traffic from the source IP address | Stop repeated attacks from the same origin | ![ByteHide Monitor workflow rules showing IF/THEN configuration for Command Injection and SQL Injection with Log, Block, Block session, and Block IP actions](/images/monitor/bytehide-monitor-rules.png) You can combine multiple actions in a single Workflow rule. For example, a SQL Injection rule can Log the incident, Block the request, and Block the IP simultaneously. --- ## Action Selection Guide ### By Threat Severity | Threat Severity | Development | Staging | Production | |----------------|-------------|---------|------------| | **Critical** (Debugger, Tampering) | None / Log | Close | Close | | **High** (Jailbreak, Memory Dump) | Log | Close | Close / Erase | | **Medium** (VM, Emulator) | None | Log | Log / Close | | **Low** (Clock Tampering, Cloud Metadata) | None | Log | Log | ### By Application Type | Application Type | Recommended Actions | |----------|-------------------| | **Desktop** (Console, WPF, WinForms) | Close, Log, Erase, Custom | | **Mobile** (MAUI, Xamarin, Android, iOS) | Close, Log, Custom | | **Web / API** (ASP.NET, Node.js) | Block, Log, Custom | | **IoT / On-Premise** | Close, Log, Custom | ### Common Scenarios | Scenario | Action | Why | |----------|--------|-----| | SQL Injection on a public API | Block | Stop the attack, keep the application running for other users | | Debugger attached in production | Close | Immediate shutdown to prevent reverse engineering | | VM detected on desktop app | Log | Track for analytics without disrupting legitimate users on VMs | | Jailbreak on a banking app | Close | Regulatory requirement, compromised device cannot be trusted | | Tampering detected with sensitive data | Erase | Delete credentials and keys before shutting down | | New protection in shadow mode | None | Observe detections before enforcing in production | | Any threat on a monitored API | Log + Block + Block IP | Full Cloud Dashboard workflow: record, stop, and ban the source | --- ## Configuring Actions Actions can be assigned per protection module from any configuration source: - **[Cloud Dashboard](/platforms/android/products/monitor/cloud-configuration)**: Assign actions in Workflow rules with the IF/THEN editor. Supports all cloud actions including Block session and Block IP. - **[JSON Configuration](/platforms/android/products/monitor/json-configuration)**: Set the `action` field per protection in your configuration file. - **[Configuration API](/platforms/android/products/monitor/configuration-api)**: Pass the action type when registering protections in code. ```json { "protections": [ { "type": "DebuggerDetection", "enabled": true, "action": "close", "intervalMs": 10000 }, { "type": "VirtualMachineDetection", "enabled": true, "action": "log", "intervalMs": 60000 }, { "type": "JailbreakDetection", "enabled": true, "action": "close", "intervalMs": 60000 } ] } ``` See [JSON Configuration](/platforms/android/products/monitor/json-configuration) for the full schema reference. --- ## Next Steps --- # Monitor Best Practices Recommendations for deploying ByteHide Monitor effectively in production on Android. {% .lead %} --- ## Token Security - **Never hardcode tokens** in source code. Use environment variables or secure vaults - **Use separate tokens** for development, staging, and production environments - **Rotate tokens** periodically and after any suspected compromise - **Restrict token scope**: each token should be linked to a single project --- ## Action Strategy ### Development Environment Use permissive actions to avoid disrupting the development workflow: ``` Debugger Detection → NONE (developers use debuggers) Emulator Detection → NONE (testing on emulators) VM Detection → NONE (may develop on VMs) All Others → LOG ``` ### Staging Environment Use logging actions to gather data without blocking: ``` All Protections → LOG ``` Review the incident dashboard to tune which protections to enforce in production. ### Production Environment Use a graduated approach based on threat severity. **Desktop and Mobile protections:** ``` Debugger Detection → CLOSE (high severity) Root/Jailbreak → CLOSE (high severity) Tampering Detection → CLOSE (high severity) Memory Dump Detection → CLOSE (high severity) Process Injection → CLOSE (high severity) Emulator Detection → LOG (medium severity) VM Detection → LOG (medium severity) Clock Tampering → LOG (medium severity) Network Tampering → LOG (medium severity) ``` **Web and Cloud protections:** ``` SQL Injection → BLOCK (high severity) XSS → BLOCK (high severity) Command Injection → BLOCK (high severity) Path Traversal → BLOCK (high severity) SSRF → BLOCK (high severity) NoSQL Injection → BLOCK (high severity) LLM Prompt Injection → LOG (evaluate before enforcing) ``` For web protections, configure [Workflow Rules](/platforms/android/products/monitor/cloud-configuration#workflow-rules) in the Cloud Dashboard to combine actions: Log + Block + Block IP for critical threats. --- ## Protection Selection ### Mobile Applications (Android/iOS) Prioritize these protections: 1. **Root/Jailbreak Detection**: compromised devices are the top mobile threat 2. **Debugger Detection**: prevents dynamic analysis 3. **Tampering Detection**: verifies app integrity 4. **Emulator Detection**: blocks automated analysis ### Desktop Applications Prioritize these protections: 1. **Debugger Detection**: blocks reverse engineering 2. **VM Detection**: prevents sandboxed analysis 3. **Tampering Detection**: verifies binary integrity 4. **Memory Dump Detection**: protects in-memory secrets ### Web Applications (Android) Prioritize these protections: 1. **SQL Injection**: the most common web attack vector 2. **XSS**: protects user sessions 3. **Path Traversal**: prevents file system access 4. **SSRF**: blocks internal network access --- ## Configuration Management - **Use [cloud configuration](/platforms/android/products/monitor/cloud-configuration) as the primary method**. It allows instant updates without redeploying - **Keep [JSON configuration](/platforms/android/products/monitor/json-configuration) as a fallback** for offline or air-gapped environments - **Use hybrid configuration** in production: cloud for protection rules, [Configuration API](/platforms/android/products/monitor/configuration-api) for custom action handlers - **Version-control your JSON configuration** alongside your application code. Export from the Cloud Dashboard to keep them in sync --- ## Monitoring and Response - **Review the [incident dashboard](/platforms/android/products/monitor/cloud-panel/incidences) regularly**. Look for patterns and anomalies - **Set up [Workflow Rules](/platforms/android/products/monitor/cloud-panel/workflow)** to automate responses with notifications to Slack or webhooks - **Use [custom actions](/platforms/android/products/monitor/custom-actions)** to integrate with your alerting system (PagerDuty, Slack, SIEM) - **Track incident trends**: a sudden spike may indicate an active attack campaign - **Enable [Anomaly Detection](/platforms/android/products/monitor/protections/anomaly-detection)**: it learns normal behavior and flags deviations automatically --- ## Performance Optimization - **Set appropriate intervals**: 60 seconds is a good default for most protections - **Increase intervals for low-risk protections**: VM and emulator detection can run every 120 seconds - **Decrease intervals for high-risk protections**: debugger detection can run every 30 seconds - **Disable irrelevant protections**: don't enable VM detection on mobile devices --- ## Deployment Checklist Before deploying to production: - [ ] Token is stored as an environment variable or secret (not hardcoded) - [ ] Protection modules are selected based on your application type - [ ] Action types are appropriate for production (not all set to `NONE`) - [ ] Logging level is set to `Info` or higher (not `Debug`) - [ ] Cloud configuration is working and accessible - [ ] Incident dashboard is accessible to your security team - [ ] Custom actions are tested and functioning - [ ] CI/CD pipeline includes the token as a secret - [ ] Debug logging is disabled - [ ] Anomaly Detection is enabled --- ## Next Steps --- # Cloud Configuration Configure Monitor protections, response actions, logging, and advanced settings from the ByteHide Cloud Dashboard. Changes sync to your application in real-time without redeployment. {% .lead %} --- ## Overview Cloud configuration is the recommended way to manage Monitor. Instead of editing JSON files or writing code, you define protection rules, response actions, and operational settings from the web dashboard. Every change propagates instantly to all running instances of your application. > **Configuration Priority** > Cloud configuration takes the highest priority. Any configuration applied through the dashboard will override both the protections defined in `monitor.config.json` and those written directly in code. --- ## Workflow Rules The Workflow tab is where you define how Monitor responds to each type of threat. Rules follow an **IF/THEN** pattern: if a specific threat type is detected, then execute one or more actions. ![ByteHide Monitor workflow rules showing IF/THEN configuration for Command Injection and SQL Injection with Log, Block, Block session, and Block IP actions](/images/monitor/bytehide-monitor-rules.png) ### Creating a Rule 1. Go to the **Workflow** tab in your Monitor project 2. Click **+ Add Rule** 3. Select the protection type (SQL Injection, XSS, Command Injection, etc.) 4. Check the actions to execute when this threat is detected: - **Log incident**: Record the incident with full forensic context - **Block**: Block the specific request or operation - **Block session**: Invalidate the attacker's entire session - **Block IP**: Block all traffic from the source IP address ### Notifications Each rule can also trigger notifications: - **Slack**: Connect your Slack workspace to receive real-time alerts when incidents match the rule - **Webhook**: Send incident data to any HTTP endpoint (SIEM, PagerDuty, custom systems) ### Exporting Configuration Click **Export config** to download your current workflow rules as a JSON file. This is useful for: - Version-controlling your configuration alongside your application code - Copying rules between projects - Using as a base for [JSON Configuration](/platforms/android/products/monitor/json-configuration) in offline environments --- ## Advanced Settings Click **Advanced Config** in the Workflow tab to open the advanced configuration panel. These settings control Monitor's operational behavior. ![ByteHide Monitor advanced configuration panel with logging levels, anomaly detection, rate limiting, and debug mode settings](/images/monitor/bytehide-monitor-advanced-rules.png) ### Logging | Setting | Options | Description | |---------|---------|-------------| | **Logging** | On/Off | Enable or disable Monitor logging | | **Minimum Level** | Debug, Info, Warning, Error, Critical | Controls which events are recorded. Use Info for production, Debug for troubleshooting | | **Console Output** | On/Off | Write log events to standard output | | **Debug Logging** | On/Off | Verbose diagnostic output. Not recommended for production | | **Local Logging** | On/Off | Write events to a local log file on disk | | **ByteHide Logs** | On/Off | Send events to [ByteHide Logs](/platforms/android/products/monitor/logging) for centralized, immutable logging. Recommended | ### Anomaly Detection Toggle to enable or disable [Anomaly Detection](/platforms/android/products/monitor/protections/anomaly-detection). When enabled, Monitor automatically learns your application's normal behavior and flags deviations: authentication anomalies, abnormal request rates, unexpected payload structures, and suspicious session activity. Enabled by default. ### Rate Limit Toggle to enable request rate limiting. When enabled, Monitor limits the number of requests processed within a configurable time window, providing protection against brute force and denial of service attempts. ### Debug Mode Enables verbose debugging output and additional diagnostic information. Marked as "Not in production" in the dashboard for a reason: it generates significant overhead and should only be used during development or active troubleshooting. ### Throw On Failure When enabled, Monitor will throw exceptions if it encounters internal errors instead of silently logging them. Useful during development to catch configuration issues early. --- ## Project Settings The Settings tab contains project-level configuration. ![ByteHide Monitor project settings showing project token, session duration configuration, and token reset options](/images/monitor/bytehide-monitor-settings.png) ### Project Token Your project token (`bh_...`) authenticates your application with the ByteHide platform. Copy it into your environment variables or configuration file. ```bash # Set as environment variable export BYTEHIDE_API_TOKEN="bh_your_token_here" ``` See [Create a Monitor Project](/platforms/android/products/monitor/create-monitor-project) for details on token management. ### Session Duration Configure how long a session remains active before expiring. Default is 60 seconds of inactivity. Sessions group related requests and incidents from the same device, making it easier to trace attack patterns. ### Reset Token Generates a new project token and invalidates the previous one. Use this if your token has been compromised or leaked. After resetting, update the token in all deployed applications. ### Unlink Project Removes the Monitor integration from this project. This is a destructive action that cannot be undone. --- ## How Configuration Syncs 1. You make changes in the Cloud Dashboard (workflow rules, advanced settings, firewall rules) 2. Monitor agents running in your applications periodically sync with the ByteHide API 3. Updated configuration is applied immediately, without restarting the application 4. If the application cannot reach the API (offline, network issues), it continues operating with the last known configuration This means your security team can update response policies, add firewall rules, or adjust logging levels across every running instance of your application without involving the development team or redeploying. --- ## Configuration Priority Monitor supports three configuration methods. When multiple are present, they are applied in this priority order: | Priority | Method | When to Use | |----------|--------|-------------| | 1 (highest) | **Cloud Dashboard** | Production. Real-time updates, team collaboration, no code changes | | 2 | **JSON File** (`monitor.config.json`) | Offline environments, air-gapped deployments, version-controlled config | | 3 (lowest) | **Code (Configuration API)** | Custom actions, programmatic logic, development-time defaults | You can combine methods. For example, use the Configuration API to register custom action handlers in code, and use the Cloud Dashboard to assign those handlers to specific protection modules and define escalation rules. --- ## Next Steps --- # Creating a Monitor Project Create a Monitor project to get your project token and start protecting your Android application. {% .lead %} --- ## Create a Project 1. Go to [cloud.bytehide.com](https://cloud.bytehide.com) and log in 2. Click **+ Create Project** ![ByteHide Cloud dashboard with Create Project button to start a new Monitor project](/images/monitor/bytehide-monitor-create-project.png) 3. Select **Android** as the language 4. Select **Monitor** as the product ![ByteHide project creation modal showing language and product selection with Monitor highlighted](/images/monitor/bytehide-monitor-select-product.png) 5. Choose the project type: - **On-Premise / IoT / Edge / Mobile**: For desktop applications, mobile apps, IoT devices, and edge computing - **Cloud / API / Web**: For web applications, REST APIs, and cloud services 6. Enter a project name and assign a team 7. Click **Create** The project type determines which protections and firewall features are available. See [Cloud Panel Overview](/platforms/android/products/monitor/cloud-panel) for the differences between project types. --- ## Get Your Token After creation, your project token is available in the [Settings tab](/platforms/android/products/monitor/cloud-panel/settings). Copy it and set it as an environment variable: ```bash export BYTEHIDE_API_TOKEN="bh_your_token_here" ``` > **Token Security** > Never commit tokens to source control. Use environment variables or a secret manager. See [Best Practices](/platforms/android/products/monitor/best-practices#token-security) for token management recommendations. --- ## Next Steps --- # Cloud Firewall Protect your API and web application with multiple firewall layers: bot blocking, threat intelligence feeds, geo-blocking, custom IP blocklists, and user agent filtering. {% .lead %} > **Cloud Projects Only** > This page applies to Cloud / Web / API project types. For Desktop, Mobile, and IoT projects, see [On-Premise Firewall](/platforms/android/products/monitor/cloud-panel/firewall/on-premise). --- ## Firewall Overview The Cloud Firewall is organized into five protection layers. The first three are managed lists provided by ByteHide. The last two are custom blocklists you define. ![ByteHide Monitor Cloud Firewall showing Block Bots, Block Threat Actors, Block Countries cards and custom blocklist options](/images/monitor/bytehide-monitor-firewall-cloud.png) --- ## Block Bots Block known bot user agents across 21 categories. Each category can be toggled individually to Block or Ignore. ![ByteHide Monitor bot blocking modal showing 21 bot categories with Block and Ignore toggles](/images/monitor/bytehide-monitor-firewall-bots.png) Categories include: - **AI Data Scrapers**: AI training crawlers and data collection bots - **Vulnerability Scanners**: Automated security scanning tools - **Data Harvesters**: Content scraping and data extraction bots - **Search Engines**: Google, Bing, Yahoo, and other search engine crawlers - **SEO Crawlers**: SEO analysis and monitoring tools - **Social Media Bots**: Social platform crawlers and preview generators - **Headless Browsers**: Automated browser instances (Puppeteer, Playwright) - And 14 more categories > **Selective Blocking** > You probably want to block AI scrapers and vulnerability scanners but allow search engine crawlers. Toggle each category independently based on your needs. --- ## Block Threat Actors Block IPs from seven threat intelligence feeds maintained by ByteHide. Lists are updated daily at midnight. ![ByteHide Monitor threat actor feeds showing seven intelligence lists with IP counts and Block or Ignore options](/images/monitor/bytehide-monitor-firewall-threat-actors.png) | Feed | Total IPs | Description | |------|-----------|-------------| | **Bruteforce Attackers** | 137,694 | IPs observed performing brute force attacks | | **Public Internet Scanners** | 600,071 | IPs running mass internet scans | | **HTTP DoS Attackers** | 614M+ | IPs involved in HTTP denial of service attacks | | **HTTP Exploit Attackers** | 614M+ | IPs attempting HTTP-based exploits | | **Proxy & VPN** | 357M+ | Known proxy and VPN exit nodes | | **WordPress Attackers** | 614M+ | IPs targeting WordPress vulnerabilities | | **Botnet Actors** | 614M+ | IPs participating in botnet activity | Each feed can be toggled individually to Block or Ignore. Blocking is instant with no performance impact on your application. --- ## Block Countries Block all traffic from specific countries using geo-blocking. Search and select countries from the list. Each blocked country is shown with its flag. ![ByteHide Monitor country blocking modal showing searchable country list with flags and block toggles](/images/monitor/bytehide-monitor-firewall-countries.png) Use cases: - Comply with regulations that restrict service to certain regions - Block traffic from countries where you have no users - Respond to attack campaigns originating from specific regions --- ## Custom IP Blocklist Block specific IP addresses or CIDR ranges. IPs can be added manually or automatically through [Workflow Rules](/platforms/android/products/monitor/cloud-panel/workflow) using the **Block IP** action. ![ByteHide Monitor custom IP blocklist showing input field for adding IPs and CIDR ranges](/images/monitor/bytehide-monitor-firewall-custom-ip.png) Supported formats: - Single IP: `192.168.1.100` - CIDR range: `192.168.1.0/24` When a Workflow rule includes the Block IP action, the attacker's IP is automatically added to this list. --- ## Custom User Agent Blocklist Block traffic matching custom user agent patterns. Patterns support regex for flexible matching. ![ByteHide Monitor custom user agent blocklist showing regex pattern input and blocked user agents list](/images/monitor/bytehide-monitor-firewall-custom-useragent.png) Examples: ``` bot.* # Block anything containing "bot" curl/.* # Block curl requests python-requests/.* # Block Python requests library scrapy/.* # Block Scrapy crawler ``` --- ## Next Steps --- # Firewall Block malicious traffic at the network and device level. The Firewall tab provides different capabilities depending on your project type. {% .lead %} --- ## Firewall by Project Type The Firewall tab adapts to your project type: | Feature | On-Premise / Desktop / Mobile | Cloud / Web / API | |---------|-------------------------------|-------------------| | **Block devices** | Yes (device-level blocklist) | No (use IP/session blocking) | | **Block bots** | No | Yes (390+ user agents, 21 categories) | | **Block threat actor IPs** | No | Yes (600M+ IPs, 7 intelligence feeds) | | **Block by country** | No | Yes (geo-blocking) | | **Custom IP blocklist** | No | Yes (single IPs or CIDR ranges) | | **Custom user agent blocklist** | No | Yes (regex patterns) | All firewall changes apply instantly without restarting your application. --- ## On-Premise Firewall For Desktop, Mobile, and IoT projects, the Firewall tab shows a **Blocked Devices** list. Devices can be blocked manually from the [Device Details](/platforms/android/products/monitor/cloud-panel/overview#device-actions) page or automatically by Workflow rules. ![ByteHide Monitor On-Premise Firewall showing Blocked Devices table with device name, ID, operating system, block reason, and date](/images/monitor/bytehide-monitor-firewall-onpremise.png) | Column | Description | |--------|-------------| | **Device Name** | Name of the blocked device | | **Device ID** | Unique device identifier | | **Operating System** | OS and version of the device | | **Block Reason** | Why the device was blocked | | **Blocked Date** | When the device was blocked | | **Actions** | Unblock button to remove the device from the blocklist | [On-Premise Firewall details](/platforms/android/products/monitor/cloud-panel/firewall/on-premise) --- ## Cloud Firewall For Web and API projects, the Firewall tab provides multiple protection layers that work together to filter malicious traffic before it reaches your application. ![ByteHide Monitor Cloud Firewall showing Block Bots, Block Threat Actors, Block Countries cards and custom blocklist options](/images/monitor/bytehide-monitor-firewall-cloud.png) | Layer | Description | Update Frequency | |-------|-------------|-----------------| | **Block Bots** | Block known bot user agents across 21 categories | Static list | | **Block Threat Actors** | Block IPs from 7 threat intelligence feeds (600M+ IPs) | Updated daily at midnight | | **Block Countries** | Block all traffic from specific countries | Real-time | | **Custom IP Blocklist** | Block specific IP addresses or CIDR ranges | Real-time | | **Custom User Agent Blocklist** | Block traffic matching custom user agent patterns | Real-time | [Cloud Firewall details](/platforms/android/products/monitor/cloud-panel/firewall/cloud) --- ## Next Steps --- # On-Premise Firewall Manage devices that have been blocked due to security policy violations. View block reasons, unblock devices, and understand how devices get added to the blocklist. {% .lead %} > **On-Premise Projects Only** > This page applies to On-Premise, Desktop, Mobile, and IoT project types. For Cloud / Web / API projects, see [Cloud Firewall](/platforms/android/products/monitor/cloud-panel/firewall/cloud). --- ## Blocked Devices The Firewall tab for on-premise projects shows a single table listing all devices that have been blocked. ![ByteHide Monitor On-Premise Firewall showing Blocked Devices table with device name, ID, operating system, block reason, and date](/images/monitor/bytehide-monitor-firewall-onpremise.png) | Column | Description | |--------|-------------| | **Device Name** | Name of the blocked device | | **Device ID** | Unique device identifier (full hash) | | **Operating System** | OS and version (e.g., Windows 10.0.26200.0) | | **Block Reason** | Why the device was blocked (e.g., security policy violation, manual block) | | **Blocked Date** | Timestamp of when the block was applied | | **Actions** | Unblock button to remove the device from the blocklist | --- ## How Devices Get Blocked Devices can be blocked in two ways: ### Manual Block From the [Device Details](/platforms/android/products/monitor/cloud-panel/overview#device-actions) page, click **Block Device** to manually add a device to the firewall blocklist. This is useful when you identify a compromised device through the incident dashboard or session analysis. ### Automatic Block Configure [Workflow Rules](/platforms/android/products/monitor/cloud-panel/workflow) to automatically block devices when specific threats are detected. For example, you can create a rule that blocks any device where Tampering Detection or Debugger Detection triggers with a Close action. --- ## Unblocking a Device To unblock a device: 1. Find the device in the Blocked Devices table 2. Click the unblock button in the Actions column 3. The device is immediately removed from the blocklist and can connect again You can also unblock a device from the [Device Details](/platforms/android/products/monitor/cloud-panel/overview#device-actions) page by clicking **Unblock Device**. --- ## Device Actions In addition to blocking and unblocking, you can take other actions on devices from the Device Details page: | Action | Description | |--------|-------------| | **Clear Memory** | Remotely clear sensitive data from the device's application memory | | **Delete Files** | Remotely wipe application files on the device | | **Block Device** | Add the device to the firewall blocklist | | **Unblock Device** | Remove the device from the firewall blocklist | See [Devices & Sessions](/platforms/android/products/monitor/cloud-panel/overview) for full details on device management. --- ## Next Steps --- # Incidences View all detected security threats in real-time. Every incident includes full context: severity, payload, origin, stacktrace, and AI-powered analysis. {% .lead %} --- ## Incidences Dashboard The Incidences tab shows all threats detected across every device and session running your application. ![ByteHide Monitor Incidences dashboard showing threat statistics cards and incidents table with severity levels, detection types, and actions taken](/images/monitor/bytehide-monitor-incidences.png) ### Statistics Cards Four cards at the top summarize your current security status: | Card | Description | |------|-------------| | **Total Incidences** | Total number of detected threats | | **Critical Threats** | Incidents classified as High or Critical severity | | **Blocked Threats** | Percentage of threats that were automatically mitigated (Block, Close, Erase) | | **Pending Review** | Incidents awaiting manual review | ### Incidences Table Each row represents a detected threat with the following columns: | Column | Description | |--------|-------------| | **Type** | Protection module that triggered the detection (SqlInjection, DebuggerDetection, PathTraversal, etc.) with a color-coded badge | | **Level** | Severity badge: Critical (red), High (orange), Medium (yellow) | | **Description** | Summary of the detected threat | | **Origin** | Source IP address with platform icon | | **Date** | Timestamp of when the threat was detected | | **Action** | Action that was executed: Log (green), Block (red), Close (grey) | | **Options** | Menu with Mark as Read and Delete | --- ## Filters Use the filter bar above the table to narrow down incidents: ![ByteHide Monitor incidence filters showing Date Range, Level, Type, and Action dropdown menus](/images/monitor/bytehide-monitor-incidences-filters.png) | Filter | Options | |--------|---------| | **Date Range** | Custom date range picker | | **Level** | Critical, High, Medium, Low | | **Type** | All protection modules: Command Injection, Cross-Site Scripting (XSS), LDAP Injection, LLM Prompt Injection, NoSQL Injection, Path Traversal, SQL Injection, SSRF, XXE, and all desktop/mobile modules | | **Action** | All, Block, Close, Log | --- ## Incident Details Click any incident row to open the detail panel with full forensic context. ![ByteHide Monitor incident detail panel showing confidence gauge, technical details, SQL injection payload, stacktrace, and origin information](/images/monitor/bytehide-monitor-incident-details.png) ### Incident Information The header displays: - **Confidence gauge**: Semicircular gauge showing the detection confidence percentage (e.g., 90%) - **Severity label**: Critical, High, Medium, or Low - **Protection module**: The type of threat detected (e.g., SqlInjection) - **Detection timestamp** - **Status badge**: Current status of the incident (e.g., TO DO) - **"Help me to understand it"** button: Opens the AI Security Analysis ### Technical Details The technical details vary depending on the protection module type. **Web protection example (SQL Injection):** | Field | Example | |-------|---------| | Module Type | SqlInjection | | User Input | `' OR '1'='1` | | Injected Content | `select from where and or` | | SQL Query | `SELECT * FROM Users WHERE Username = 'admin' AND Password = '' OR '1'='1'` | **Desktop protection example (Debugger Detection):** | Field | Example | |-------|---------| | Module Type | DebuggerDetection | | Payload | Debugger type and detection method | ### Stacktrace A code block showing the execution call chain at the time of detection. This shows exactly which code path was executing when the threat was intercepted, from the Monitor interception point back to the application entry point. ### Origin Information | Field | Description | |-------|-------------| | **IP Address** | Source IP of the request or device | | **Device** | Device or server name | | **User Agent** | Full user agent string | | **Device ID** | Unique device identifier | | **Platform** | Application platform (web, mobile, desktop) | | **Session ID** | Session identifier (for tracking related incidents) | > **Tip** > Review the stacktrace and payload to understand the attack vector. Consider implementing additional validation and sanitization measures for the affected code path. --- ## AI Security Analysis Click **"Help me to understand it"** on any incident to get an AI-powered explanation of the threat. ![ByteHide Monitor AI Security Analysis modal showing attack explanation, business impact, attack vector, and severity analysis](/images/monitor/bytehide-monitor-ai-analysis.png) ### Analysis Tab | Section | Description | |---------|-------------| | **What Happened** | Plain-language explanation of the attack | | **Why It Matters** | Potential business impact: data breaches, compliance violations, reputational damage | | **Attack Vector** | Technique used, entry point, and why it worked | | **Severity Explanation** | Why the incident is rated at its severity level | | **Confidence Level** | AI model confidence in the analysis (High, Medium, Low) | ### Protection Status Tab ![ByteHide Monitor AI Protection Status tab showing current protection level, Monitor capabilities, limitations, and action taken](/images/monitor/bytehide-monitor-ai-protection-status.png) | Section | Description | |---------|-------------| | **Is Protected** | Whether the application is fully protected, partially protected, or in detection-only mode | | **What Monitor Does** | Capabilities of Monitor for this type of threat | | **What Monitor Doesn't Do** | Limitations (Monitor does not fix code, does not modify application logic) | | **Action Taken** | Detailed description of the response action that was executed | | **Configuration Required** | Whether additional configuration is needed to improve protection | --- ## Incident Actions Each incident row has an options menu (three dots) with: - **Mark as Read**: Removes the incident from the Pending Review count - **Delete**: Permanently removes the incident from the dashboard --- ## Next Steps --- # Cloud Panel The Cloud Panel is the web dashboard for managing Monitor projects, monitoring threats in real-time, configuring automated responses, and analyzing security incidents. {% .lead %} --- ![ByteHide Monitor Cloud Panel dashboard showing Incidences tab with threat statistics, severity levels, and detected security incidents](/images/monitor/bytehide-monitor-cloud-panel.png) ## Dashboard Tabs The Cloud Panel is organized into six tabs. Each tab focuses on a specific aspect of your application's runtime security. | Tab | Description | |-----|-------------| | **[Incidences](/platforms/android/products/monitor/cloud-panel/incidences)** | All detected threats with severity, origin, action taken, and AI-powered analysis | | **[Firewall](/platforms/android/products/monitor/cloud-panel/firewall)** | Block bots, threat actor IPs, countries, custom IPs, and user agents | | **[Routes](/platforms/android/products/monitor/cloud-panel/routes)** | API endpoint usage and request patterns (web/cloud projects only) | | **[Overview](/platforms/android/products/monitor/cloud-panel/overview)** | Devices, sessions, geographic distribution map, and recent incidents | | **[Workflow](/platforms/android/products/monitor/cloud-panel/workflow)** | Automation rules (IF threat THEN action) and advanced configuration | | **[Settings](/platforms/android/products/monitor/cloud-panel/settings)** | Project token, session duration, token reset, and project management | --- ## Project Types When creating a Monitor project, you choose the project type based on your application. This determines which protections and firewall features are available. | | On-Premise / Desktop / Mobile | Cloud / Web / API | |--|-------------------------------|-------------------| | **Protections** | 13 passive detectors (debugger, VM, jailbreak, tampering, etc.) | 9 active interceptors (SQL injection, XSS, SSRF, etc.) | | **Actions** | Log, Close, Erase, Notifications | Log, Block, Block session, Block IP, Notifications | | **Firewall** | Device-level blocking | Bots, threat actor IPs, countries, custom IPs, user agents | | **Routes tab** | Not available | Available | Both project types include the Incidences, Firewall, Overview, Workflow, and Settings tabs. See [Protection Modules](/platforms/android/products/monitor/protection-modules) for the full list of available protections. --- ## Getting Started 1. **[Create a Project](/platforms/android/products/monitor/cloud-panel/creating-project)**: Choose your platform and project type 2. **Copy your token**: Get the project token from the Settings tab 3. **Install Monitor**: Add the SDK to your application with the token 4. **Configure rules**: Set up [Workflow Rules](/platforms/android/products/monitor/cloud-panel/workflow) to define automated responses 5. **Monitor incidents**: Threats appear in real-time in the [Incidences](/platforms/android/products/monitor/cloud-panel/incidences) tab --- ## Explore the Cloud Panel --- # Devices & Sessions Monitor every device and server running your application. View geographic distribution, inspect device security status, drill into individual sessions, and take action on compromised devices. {% .lead %} --- ## Overview Dashboard The Overview tab provides a high-level view of all application instances and their activity. ![ByteHide Monitor Overview tab showing device count, sessions graph, geographic map, and last incidences](/images/monitor/bytehide-monitor-overview-dashboard.png) ![ByteHide Monitor Devices table showing status, version, device name, device ID, monitor version, sessions, and blocked status](/images/monitor/bytehide-monitor-overview-devices.png) ### Statistics | Card | Description | |------|-------------| | **Devices** | Total number of devices and servers running your application | | **Sessions** | Session activity graph over the last 30 days | ### Geographic Map An interactive world map showing the geographic location of all devices running your application. Each marker represents a device or server, positioned based on IP geolocation. ### Last Incidences A summary of the 5 most recent security incidents detected across all devices, with the protection module name and timestamp. ### Devices Table | Column | Description | |--------|-------------| | **Status** | Active (green check) or Blocked (red) | | **Version** | Operating system version | | **Device** | Device or server name | | **Device ID** | Unique device identifier (truncated hash) | | **Monitor Version** | Version of the Monitor SDK installed | | **Sessions** | Number of sessions recorded for this device (badge with count) | | **Blocked** | Whether the device is currently blocked (red X if blocked) | | **Details** | View button to open the device detail page | --- ## Device Details Click the view button on any device row to open its detail page. ![ByteHide Monitor Device Detail page showing session info, device info, app info, security status checks, and last incidences](/images/monitor/bytehide-monitor-device-details.png) ### Information Cards **Last Session Info:** - Session ID, IP address, uptime - Country (with flag) and city - Interactive map showing the device location **Device Info:** - IPv4 and IPv6 addresses, uptime, country **App Info:** - Application version and Monitor SDK version ### Security Status Six security checks showing the current state of the device: | Check | Description | |-------|-------------| | **Virtual Machine** | Whether the device is running inside a VM | | **Root Device** | Whether the device is rooted or jailbroken | | **Sandbox** | Whether the application is running in a sandbox | | **Deobfuscator tools** | Whether deobfuscation tools are detected | | **Debugger tools** | Whether debugging tools are attached | | **Intercept packages** | Whether network interception tools are detected | Each check shows a green checkmark (safe) or a red warning (detected). ### Device Actions Actions you can take on a specific device: | Action | Description | |--------|-------------| | **Clear Memory** | Remotely clear sensitive data from the device's application memory | | **Delete Files** | Remotely wipe application files on the device | | **Block Device** | Add the device to the firewall blocklist, preventing further connections | | **Unblock Device** | Remove the device from the firewall blocklist | ### Sessions Table Below the device information, a table lists all sessions recorded for this device: | Column | Description | |--------|-------------| | **Incidences** | Number of incidents in the session. Green badge (0) for clean sessions, orange badge (1+) for sessions with threats | | **Start Hour** | Session start timestamp | | **End Hour** | Session end timestamp | | **View** | View button to open the session detail page | **Filters:** IP Address, Date Range, Incidences. --- ## Session Details Click any session row to open the session detail page with a full timeline of events. ![ByteHide Monitor Session Detail page showing visual timeline with start, threat detected, and end events](/images/monitor/bytehide-monitor-session-details.png) ### Session Timeline A visual horizontal timeline showing: - **Start session** (blue): When the session began, with timestamp - **Threat detected** (red): Each security incident during the session, with protection module name and timestamp - **End session** (blue): When the session ended, with timestamp ### Session Actions Two actions available at the top of the session detail page: - **Block Session**: Invalidate this session immediately - **Block User Agent**: Block the user agent string associated with this session ### Session Incidences Table A filtered table showing only the incidents that occurred during this specific session, with the same columns as the main [Incidences table](/platforms/android/products/monitor/cloud-panel/incidences): Type, Level, Description, Origin, Date, and Status. **Filters:** Date Range, Level, Type, Status. --- ## Next Steps --- # Monitor Project Configuration Configure your Monitor project settings from the ByteHide Cloud panel for centralized management across all your applications. {% .lead %} > **Coming Soon**: This page will include detailed screenshots and step-by-step guides for configuring your Monitor project in the ByteHide Cloud panel. The configuration applies to all applications using the same project token. --- ## Protection Modules Configuration Enable or disable specific protection modules for all applications in your project: ### Desktop & Mobile Modules - **Debugger Detection** - Detect attached debuggers - **Virtual Machine Detection** - Identify VM environments - **Emulator Detection** - Detect emulators and sandboxes - **Jailbreak Detection** - Identify rooted/jailbroken devices - **Clock Tampering** - Detect system clock manipulation - **Memory Dump Detection** - Identify memory dumping attempts ### Web & Cloud Modules - **SQL Injection Protection** - Intercept SQL queries - **XSS Protection** - Validate user input/output - **Path Traversal Protection** - Intercept file operations - **Command Injection Protection** - Validate process execution - **SSRF Protection** - Intercept HTTP requests --- ## Action Policies Configure default actions for different threat types: - **Critical Threats** (Debugger, VM): Close application - **Medium Threats** (Clock Tampering): Log incident - **Low Priority** (Analytics): None (detect only) --- ## Notifications & Alerts Configure how your team receives incident notifications: - **Email Alerts** - Receive emails for specific threat types - **Webhook Integration** - Send incidents to external systems - **Slack/Teams Integration** - Real-time team notifications --- ## Team Access Control Manage who can access your Monitor project: - **Admin** - Full control over project settings - **Developer** - View incidents and analytics - **Viewer** - Read-only access to incidents --- ## Analytics Dashboard View real-time statistics and trends: - **Incident Count** - Total threats detected over time - **Threat Distribution** - Breakdown by module type - **Device Statistics** - Active devices and sessions - **Geographic Distribution** - Where threats are being detected --- ## Next Steps - [Create your first Monitor project](/platforms/android/products/monitor/create-monitor-project) - [Install Monitor in your application](/platforms/android/products/monitor/standalone-installation) - [Configure protection modules in code](/platforms/android/products/monitor/configuration-api) --- # Routes Track all API endpoints your application exposes and their request volumes. Identify which routes receive the most traffic and correlate with incident data to find potential attack surfaces. {% .lead %} > **Cloud Projects Only** > The Routes tab is only available for Cloud / Web / API project types. On-Premise, Desktop, Mobile, and IoT projects do not have HTTP route tracking. --- ## Routes Dashboard ![ByteHide Monitor Routes tab showing total API endpoints, request counts, and route table with HTTP methods](/images/monitor/bytehide-monitor-routes.png) ### Statistics Two cards at the top summarize your API surface: | Card | Description | |------|-------------| | **Total Routes** | Number of unique API endpoints detected | | **Total Requests** | Total request count over the last 7 days | ### Routes Table The table lists every endpoint Monitor has observed, with the following columns: | Column | Description | |--------|-------------| | **Method** | HTTP method badge: GET (green), POST (blue), PUT (yellow), DELETE (red) | | **Route** | API endpoint path (e.g., `/api/users/search`) | | **Total Requests** | Number of requests to this endpoint | Routes are sorted by request volume (most requested first). The table includes pagination for large API surfaces. --- ## How Routes Are Collected Monitor automatically discovers and tracks routes as your application receives requests. No manual configuration is needed. Every HTTP request that passes through Monitor's middleware is recorded with its method and path. This gives you visibility into: - **Your full API surface**: See every endpoint your application exposes, including ones you may not have documented - **Traffic distribution**: Identify which endpoints receive the most traffic - **Attack surface analysis**: Correlate high-traffic endpoints with incidents from the [Incidences tab](/platforms/android/products/monitor/cloud-panel/incidences) to prioritize protection - **Unused endpoints**: Find endpoints with zero or minimal traffic that could be candidates for removal --- ## Next Steps --- # Settings Manage your project token, session configuration, and administrative operations from the Settings tab. {% .lead %} --- ## Settings Tab ![ByteHide Monitor project settings showing project token, session duration configuration, and token reset options](/images/monitor/bytehide-monitor-settings.png) --- ## Project Token Your project token (`bh_...`) authenticates your application with the ByteHide platform. Copy it and set it as an environment variable: ```bash export BYTEHIDE_API_TOKEN="bh_your_token_here" ``` > **Token Security** > Never commit tokens to source control. Use environment variables or a secret manager. See [Best Practices](/platforms/android/products/monitor/best-practices#token-security) for recommendations. The token is displayed partially masked in the dashboard. Click the copy button to copy the full token to your clipboard. --- ## Session Duration Configure how long a session remains active before expiring due to inactivity. The default is **60 seconds**. Sessions group related requests and incidents from the same device or client. A longer session duration means more events are grouped together, making it easier to trace attack patterns across multiple requests. Enter the desired duration in seconds and click **Save**. --- ## Reset Token Generates a new project token and immediately invalidates the previous one. Use this if your token has been compromised or leaked. > **Immediate Impact** > Resetting the token immediately invalidates the old one. All running applications using the old token will lose connectivity with the ByteHide platform until they are updated with the new token. After resetting: 1. Copy the new token from the Settings tab 2. Update the environment variable or configuration file in all deployments 3. Restart or redeploy your applications 4. Verify that devices reappear in the [Overview tab](/platforms/android/products/monitor/cloud-panel/overview) --- ## Danger Zone ### Unlink Project Permanently removes the Monitor integration from this project and deletes all associated data: - All devices and device history - All sessions - All incidents and forensic data - All Workflow rules and firewall configurations - The project token (invalidated) > **Permanent Data Loss** > This action cannot be undone. All data will be permanently deleted. Export your configuration and back up any incident data before unlinking. --- ## Next Steps --- # Workflow Actions Actions define what Monitor does when a Workflow rule matches a detected threat. Multiple actions can be combined in a single rule. {% .lead %} --- ## Actions by Project Type Available actions depend on your project type: | Action | On-Premise | Cloud | Description | |--------|-----------|-------|-------------| | **Log incident** | Yes | Yes | Record the threat in the dashboard and logs without disrupting execution | | **Close app** | Yes | No | Terminate the application immediately | | **Erase app data** | Yes | No | Securely delete sensitive data from memory and disk before terminating | | **Block** | No | Yes | Block the current HTTP request and return 403 Forbidden | | **Block session** | No | Yes | Block all requests from this session ID | | **Block IP** | No | Yes | Block all traffic from the source IP (added to [Custom IP Blocklist](/platforms/android/products/monitor/cloud-panel/firewall/cloud#custom-ip-blocklist)) | | **Send notification** | Yes | Yes | Alert via Slack or Webhook | --- ## On-Premise Actions ### Log Incident Records the threat in the Cloud Panel and local logs. The application continues running normally. Use this for development, low-severity threats, and data collection before deciding which protections to enforce. ### Close App Immediately terminates the application. Use this for critical threats where continued execution is dangerous: debugger attached, tampering detected, jailbreak detected. ### Erase App Data Securely deletes sensitive data from memory and disk, then terminates the application. Use this for applications that handle financial data, credentials, or other sensitive information on compromised devices. --- ## Cloud Actions ### Log Incident Records the threat in the Cloud Panel without blocking the request. The response is sent normally. Use this for monitoring new protections before enforcing, or for low-confidence detections you want to review. ### Block Blocks the current request and returns HTTP 403 Forbidden. The attacker receives a generic blocked response. Use this for confirmed attacks: SQL injection, XSS, path traversal, command injection. ### Block Session Blocks the current request and invalidates the entire session. All future requests with the same session ID are blocked. Use this for persistent attackers who try different payloads within the same session. ### Block IP Blocks the current request and adds the source IP address to the [Custom IP Blocklist](/platforms/android/products/monitor/cloud-panel/firewall/cloud#custom-ip-blocklist) in the Firewall tab. All future traffic from this IP is blocked. Use this for repeated attacks or high-severity threats. --- ## Combining Actions You can select multiple actions in a single Workflow rule. They execute simultaneously when the rule matches. Example for maximum protection on a SQL Injection rule: ``` IF: SQL Injection detected THEN: Log incident Block request Block session Block IP Send notification (Slack + Webhook) ``` This logs the incident for forensic review, blocks the request, invalidates the attacker's session, bans their IP from all future traffic, and notifies your team via Slack and webhook. --- ## Notifications ### Slack Connect your Slack workspace to receive real-time alerts when Workflow rules match. Each notification includes the threat type, severity, action taken, and origin information. 1. Check the **Slack** checkbox on the rule 2. Click **Link Slack with ByteHide** to authorize the integration 3. Select the channel to receive alerts ### Webhook Send incident data to any HTTP endpoint. Monitor sends a POST request with the full incident payload when the rule matches. 1. Check the **Webhook** checkbox on the rule 2. Select a webhook endpoint from the dropdown (or create one) Use webhooks to integrate with SIEM systems (Splunk, ELK, Datadog), ticketing platforms (Jira, ServiceNow, PagerDuty), or custom alerting pipelines. --- ## Related For the full reference of all Monitor action types (including SDK-level actions like Custom and None), see [Actions Overview](/platforms/android/products/monitor/actions). --- # Advanced Configuration Configure Monitor's operational behavior from the Cloud Panel. These settings control logging, error handling, anomaly detection, and rate limiting. Changes apply in real-time without restarting your application. {% .lead %} --- ## Access Open the **Workflow** tab and click the **Advanced Config** button in the top right corner. ![ByteHide Monitor advanced configuration panel with logging levels, anomaly detection, rate limiting, and debug mode settings](/images/monitor/bytehide-monitor-advanced-rules.png) > **Configuration Priority** > Advanced Configuration settings in the Cloud Panel override JSON and code-based configuration. See [Configuration Priority](/platforms/android/products/monitor/cloud-configuration#configuration-priority) for details. --- ## Logging Configuration ### Minimum Level Select the minimum severity level for log output. Events below this level are discarded. | Level | Use case | |-------|----------| | **Trace** | Maximum detail, framework internals | | **Debug** | Development troubleshooting | | **Info** | General operational events | | **Warning** | Potential issues that need attention | | **Error** | Failures that need investigation | **Recommended:** `info` or `warning` for production. `debug` for development only. ### Console Output Toggle console logging to stdout/stderr. Enable this when running in containers (Docker, Kubernetes) or cloud environments where logs are collected from stdout (CloudWatch, Azure Monitor, Google Cloud Logging). ### Local Logging (File) Toggle file-based logging with automatic rotation. - **File Path:** `logs/bytehide-monitor.log` - **Max Size:** 10 MB per file before rotation ### ByteHide Logs Integration Send Monitor logs to [ByteHide Logs](/platforms/android/products/logs) for encrypted cloud storage with AI-powered analysis and data masking. 1. Toggle **ByteHide Logs** on 2. Select your Logs project from the dropdown (or create one) For the full logging reference including log levels, output destinations, and sensitive data masking, see [Logging](/platforms/android/products/monitor/logging). --- ## Throw On Failure > **Use with caution** > When enabled, any Monitor service error (network timeout, API failure, configuration error) will crash the application instead of logging the error and continuing. Only enable this in development to catch integration issues early. **Default:** Disabled. Monitor logs errors internally and continues normal execution. --- ## Debug Mode > **Never enable in production** > Debug mode includes detailed threat information in HTTP responses, which exposes your security configuration to attackers. See [Debug Logging](/platforms/android/products/monitor/logging#debug-logging) for what gets exposed and why it matters. Toggle verbose request/response logging for development troubleshooting. When enabled, blocked responses include the full `threatInfo` object with protection module, confidence score, and matched patterns. --- ## Anomaly Detection AI-powered detection of unusual patterns that don't match a specific attack signature but indicate suspicious behavior. Detects: - **IP address changes mid-session** - Same session ID used from different IPs - **Geographic impossibilities** - Requests from locations that are physically impossible given the time between them - **Request pattern anomalies** - Unusual request frequency, timing, or sequencing When anomalies are detected, they appear as incidents in the [Incidences](/platforms/android/products/monitor/cloud-panel/incidences) tab and can trigger [Workflow Rules](/platforms/android/products/monitor/cloud-panel/workflow). --- ## Rate Limiting Limit the number of requests per IP address within a time window. Requests that exceed the limit receive HTTP `429 Too Many Requests`. | Setting | Description | Default | |---------|-------------|---------| | **Max Requests** | Maximum requests allowed per IP | 100 | | **Time Window** | Time period in milliseconds | 60000 (1 minute) | Example: With the defaults, each IP can make up to 100 requests per minute. The 101st request within the same minute window returns 429. --- ## Next Steps --- # Workflow Define automatic actions when threats are detected. Create IF/THEN rules that respond to each type of threat with logging, blocking, notifications, or custom workflows. Changes apply in real-time. {% .lead %} --- > **Configuration Priority** > Workflow rules configured in the Cloud Panel override both `monitor.config.json` and code-based configuration. See [Configuration Priority](/platforms/android/products/monitor/cloud-configuration#configuration-priority) for details. ## Workflow Rules The Workflow tab lists all active automation rules for your project, with three buttons in the top right: - **+ Add Rule**: Create a new automation rule - **Export config**: Download all rules as a JSON file - **Advanced Config**: Open the advanced configuration panel **Cloud / Web / API projects:** ![ByteHide Monitor Workflow rules for cloud projects showing IF/THEN configuration with Log, Block, Block session, and Block IP actions](/images/monitor/bytehide-monitor-workflow-cloud.png) **On-Premise / Desktop / Mobile projects:** ![ByteHide Monitor Workflow rules for on-premise projects showing IF/THEN configuration with Log, Close, and Erase actions](/images/monitor/bytehide-monitor-workflow-onpremise.png) ### Creating a Rule Each rule follows an **IF/THEN** pattern: 1. Click **+ Add Rule** 2. **IF**: Select the protection module (SQL Injection, Debugger Detection, Command Injection, etc.) 3. **THEN**: Check the actions to execute when this threat is detected Available actions depend on your project type: | Action | On-Premise | Cloud | |--------|-----------|-------| | **Log incident** | Yes | Yes | | **Close app** | Yes | No | | **Erase app data** | Yes | No | | **Block request** | No | Yes | | **Block session** | No | Yes | | **Block IP** | No | Yes | You can select multiple actions per rule. For example, a SQL Injection rule can Log the incident, Block the request, and Block the IP simultaneously. ### Deleting a Rule Click the trash icon on any rule to remove it. The change applies immediately. --- ## Notifications Each rule can trigger notifications to alert your team in real-time. ### Slack 1. Check the **Slack** checkbox on the rule 2. Click **Link Slack with ByteHide** to connect your workspace 3. Select the channel to receive alerts ### Webhook 1. Check the **Webhook** checkbox on the rule 2. Select a webhook from the dropdown (or create one) 3. Monitor sends a POST request with the full incident data to your endpoint Use webhooks to integrate with: - SIEM systems (Splunk, ELK, Datadog) - Ticketing (Jira, ServiceNow, PagerDuty) - Custom alerting pipelines --- ## Export Configuration Click **Export config** to download your current workflow rules as a JSON file. This is useful for: - Version-controlling your security configuration - Copying rules between projects - Using as a base for [JSON Configuration](/platforms/android/products/monitor/json-configuration) in offline environments --- ## Advanced Configuration Click **Advanced Config** to open the advanced settings panel. These settings control Monitor's operational behavior beyond individual threat rules. ![ByteHide Monitor advanced configuration panel with logging levels, anomaly detection, rate limiting, and debug mode settings](/images/monitor/bytehide-monitor-advanced-rules.png) See [Advanced Configuration](/platforms/android/products/monitor/cloud-panel/workflow/advanced-configuration) for the full reference of all settings. --- ## Next Steps --- # Android Configuration API Monitor offers three configuration approaches: Gradle DSL (build-time), JSON file (local/offline), and Programmatic API (runtime). You can combine them for a hybrid approach. {% .lead %} --- ## Configuration Options Overview | Option | Best For | Code Required | Offline Support | |---|---|---|---| | **Gradle DSL** | Android apps (recommended) | None | Plugin embeds config at build time | | **JSON File** | Offline / auditable config | None | Yes | | **Programmatic API** | Custom actions / dynamic logic | Yes | Yes | --- ## Option A: Gradle DSL (Android) The Gradle plugin handles initialization automatically via a generated `ContentProvider`. No code changes required for basic protection. ```kotlin monitor { projectToken = "bh_xxxxxxxxxxxx" preset = "mobile" } ``` For full DSL options including presets, individual protection flags, and behavior settings, see [Gradle Setup](/platforms/android/products/monitor/installation/gradle-setup). --- ## Option B: JSON Configuration Define protections locally in a JSON file. Ideal for offline environments or when you need version-controlled configuration. **Android**: Place in `src/main/assets/`. **Desktop/Server**: Place in `src/main/resources/` (classpath). The SDK searches for config files in this order: `monitor-config.json`, `bytehide-monitor-config.json`, `bytehide.monitor.json`, `monitor.config.json`. ```json { "enabled": true, "projectToken": "bh_xxxxxxxxxxxx", "logging": { "level": "info", "console": true, "file": { "enabled": true, "path": "logs/bytehide-monitor.log", "maxSizeMB": 10, "maxFiles": 5 } }, "protections": [ { "type": "DebuggerDetection", "enabled": true, "action": "close" }, { "type": "JailbreakDetection", "enabled": true, "action": "close" }, { "type": "ClockTampering", "enabled": true, "action": "log" } ] } ``` > **Android with Gradle plugin** > On Android with the Gradle plugin, the plugin generates and embeds an encrypted config automatically from the `monitor {}` DSL. You only need a manual JSON file if you're **not** using the plugin or want to override the embedded config during development. See [JSON Configuration](/platforms/android/products/monitor/json-configuration) for the full schema reference. --- ## Option C: Programmatic Configuration Configure Monitor directly in code for maximum control, custom actions, and dynamic logic. ### Android (with Gradle plugin) The plugin handles initialization automatically. You only need code for **additional runtime configuration** (custom actions, extra logging, etc.): #### Kotlin ```kotlin import android.app.Application import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType import com.bytehide.monitor.core.logging.LogLevel import android.util.Log class MyApplication : Application() { override fun onCreate() { super.onCreate() // Monitor is already initialized by the ContentProvider. // Add custom behavior: Monitor.configure { config -> config.registerCustomAction("alert") { result -> Log.w("Security", "Threat: ${result.threatType}") Log.w("Security", "Details: ${result.description}") // Send to analytics, show dialog, notify backend, etc. } } } } ``` #### Java ```java import android.app.Application; import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; import android.util.Log; public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); // Monitor is already initialized by the ContentProvider. // Add custom behavior: Monitor.configure(config -> { config.registerCustomAction("alert", result -> { Log.w("Security", "Threat: " + result.getThreatType()); Log.w("Security", "Details: " + result.getDescription()); }); }); } } ``` Register your `Application` class in `AndroidManifest.xml`: ```xml ``` ![Programmatic Monitor configuration in Android Studio](/images/monitor/android/bytehide-monitor-android-code-config.png) ### Java Desktop / Server (without Gradle plugin) For non-Android (desktop, CLI, Spring Boot, etc.), you initialize Monitor entirely in code. No Gradle plugin is needed. Add the dependency directly: **Gradle:** ```kotlin dependencies { implementation("com.bytehide:monitor-core:1.0.1") } ``` **Maven:** ```xml com.bytehide monitor-core 1.0.1 ``` ![Monitor dependency and runtime output](/images/monitor/android/bytehide-monitor-android-code-dependency.png) #### Minimal setup ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; public class MyApp { public static void main(String[] args) { Monitor.configure(config -> { config.useToken("bh_xxxxxxxxxxxx"); config.enableAllProtections(ActionType.LOG, 60000); }); // Your application code... } } ``` #### Async vs Sync initialization ```java // Async (recommended) - returns immediately, initializes in background Monitor.configure(config -> { ... }); // alias for configureAsync() Monitor.configureAsync(config -> { ... }); // returns CompletableFuture // Sync (blocking) - blocks until fully initialized Monitor.configureSync(config -> { ... }); // blocks current thread ``` > **Always use async on Android** > On Android, always use `configure()` (async) to avoid ANR errors. Use `configureSync()` only in Desktop/Server applications where blocking is acceptable. #### Full Desktop example ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; import com.bytehide.monitor.core.logging.LogLevel; public class DesktopApp { public static void main(String[] args) { Monitor.configure(config -> { config.useToken(System.getenv("BYTEHIDE_MONITOR_TOKEN")); // Logging config.configureLogging(log -> { log.enableConsole(); log.setMinimumLevel(LogLevel.INFO); }); // Custom action config.registerCustomAction("alert", result -> { System.err.println("[SECURITY] " + result.getThreatType() + ": " + result.getDescription()); }); // Protections config.addProtection(ProtectionModuleType.DEBUGGER_DETECTION, ActionType.CLOSE, 10000); config.addProtection(ProtectionModuleType.VIRTUAL_MACHINE_DETECTION, "alert", 60000); config.addProtection(ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.LOG, 30000); config.addProtection(ProtectionModuleType.PROCESS_INJECTION, ActionType.LOG, 30000); config.addProtection(ProtectionModuleType.CLOCK_TAMPERING, ActionType.LOG, 60000); }); System.out.println("Application running with RASP protection."); } } ``` #### Spring Boot example ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; @SpringBootApplication public class Application { public static void main(String[] args) { // Initialize Monitor before Spring Boot Monitor.configureSync(config -> { config.useToken(System.getenv("BYTEHIDE_MONITOR_TOKEN")); config.addProtection(ProtectionModuleType.DEBUGGER_DETECTION, ActionType.LOG, 30000); config.addProtection(ProtectionModuleType.CONTAINER_DETECTION, ActionType.LOG, 60000); config.addProtection(ProtectionModuleType.CLOUD_METADATA, ActionType.LOG, 60000); config.addProtection(ProtectionModuleType.NETWORK_TAMPERING, ActionType.LOG, 60000); }); SpringApplication.run(Application.class, args); } } ``` --- ## Java API Reference ### `useToken(String token)` Sets the API token for backend communication. ```java config.useToken("bh_xxxxxxxxxxxx"); // Or from environment: config.useToken(System.getenv("BYTEHIDE_MONITOR_TOKEN")); ``` ### `enableAllProtections(ActionType action, int intervalMs)` Enables all available protection modules with the same action and interval. ```java config.enableAllProtections(ActionType.LOG, 60000); ``` ### `addProtection(ProtectionModuleType module, ActionType action, int intervalMs)` Adds a specific protection module with a built-in action. ```java config.addProtection(ProtectionModuleType.DEBUGGER_DETECTION, ActionType.CLOSE, 10000); ``` ### `addProtection(ProtectionModuleType module, String customActionName, int intervalMs)` Adds a specific protection module with a custom action (must be registered first). ```java config.addProtection(ProtectionModuleType.DEBUGGER_DETECTION, "notify", 10000); ``` ### `registerCustomAction(String name, IActionHandler handler)` Registers a named custom action handler. ```java config.registerCustomAction("notify", result -> { System.err.println("Threat: " + result.getDescription()); System.err.println("Confidence: " + result.getConfidence()); }); ``` ### `configureLogging(LoggingConfigurator configurator)` Configures logging sinks and levels. ```java config.configureLogging(log -> { log.enableConsole(); log.enableFileLogging("monitor.log"); log.setMinimumLevel(LogLevel.INFO); log.addSink(customSink); // Forward to SLF4J, Log4j, etc. }); ``` --- ## Protection Modules | Module | Enum Constant | Recommended For | |--------|---------------|-----------------| | Debugger Detection | `DEBUGGER_DETECTION` | All | | Clock Tampering | `CLOCK_TAMPERING` | All | | Jailbreak / Root | `JAILBREAK_DETECTION` | Mobile, Desktop | | Virtual Machine | `VIRTUAL_MACHINE_DETECTION` | Desktop | | Emulator | `EMULATOR_DETECTION` | Mobile, Desktop | | Memory Dump | `MEMORY_DUMP_DETECTION` | Desktop | | Process Injection | `PROCESS_INJECTION` | Desktop, Mobile | | Network Tampering | `NETWORK_TAMPERING` | All | | License Binding | `LICENSE_BINDING` | All | | Tampering Detection | `TAMPERING_DETECTION` | Mobile, Desktop | | Container Detection | `CONTAINER_DETECTION` | Server | | Remote Desktop | `REMOTE_DESKTOP` | Desktop | | Cloud Metadata | `CLOUD_METADATA` | Server | --- ## Available Action Types | Type | Enum / DSL String | Behavior | |---|---|---| | **None** | `ActionType.NONE` / `"none"` | Detect only, no response | | **Log** | `ActionType.LOG` / `"log"` | Log the threat (default) | | **Close** | `ActionType.CLOSE` / `"close"` | Terminate the application (`System.exit(1)`) | | **Erase** | `ActionType.ERASE` / `"erase"` | Wipe temp data and terminate | | **Custom** | `ActionType.CUSTOM` / `"custom"` | Execute your registered handler | --- ## Custom Action Example ```kotlin config.registerCustomAction("myAction") { threat -> // 1. Log the incident analytics.trackSecurityThreat(threat.threatType, threat.description) // 2. Notify the user showSecurityWarning(threat.description) // 3. Alert the backend securityApi.reportThreat(threat) // 4. Take action based on confidence when (threat.confidence) { in 0.8..1.0 -> exitProcess(1) // High: close app in 0.5..0.8 -> disableSensitiveFeatures() // Medium: limit else -> Log.i("Security", "Possible threat: ${threat.description}") } } ``` --- ## Detection Result When using custom actions, the `DetectionResult` object provides: | Method | Return Type | Description | |--------|-------------|-------------| | `getThreatType()` | `ProtectionModuleType` | Which module triggered | | `getDescription()` | `String` | Human-readable description | | `getConfidence()` | `float` | Confidence score (0.0 - 1.0) | --- ## Utility Methods ```java Monitor.isInitialized(); // true if Monitor has been configured Monitor.getMachineId(); // SHA-256 hash of hardware identifiers Monitor.getSessionId(); // Current session UUID (null if no session) Monitor.shutdown(); // Explicit shutdown (auto-registered via JVM hook) ``` --- ## Configuration Loading Order When multiple configuration sources are present, they are applied in this priority order: 1. **Embedded encrypted configuration** (injected by the Gradle plugin at build time) 2. **Plain JSON file** in assets/resources (for development / offline) 3. **Programmatic configuration** via `Monitor.configure` (overrides the above) > **Cloud protection modules** > The Java SDK currently supports on-premise protection modules (mobile and desktop). Cloud protection modules (SQL Injection, XSS, Path Traversal, etc.) for web API monitoring will be available soon. --- # Android CI/CD Integration Integrate ByteHide Monitor into your Android CI/CD pipeline so every build is protected automatically. {% .lead %} --- ## Prerequisites - Monitor Gradle plugin configured in your project (see [Gradle Setup](/platforms/android/products/monitor/installation/gradle-setup)) - Project token stored as a CI/CD secret (never hardcode it in your repository) - Internet access during the build (the plugin requests a signed license from ByteHide) The `com.bytehide.monitor` Gradle plugin reads the `BYTEHIDE_API_TOKEN` environment variable, requests a signed license, and embeds encrypted configuration into the APK at build time. At runtime, Monitor auto-initializes via the generated `ContentProvider`. --- ## GitHub Actions ```yaml name: Build Android App on: push: branches: [main] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up JDK 17 uses: actions/setup-java@v4 with: java-version: '17' distribution: 'temurin' - name: Setup Gradle uses: gradle/actions/setup-gradle@v3 - name: Build with Monitor env: BYTEHIDE_API_TOKEN: ${{ secrets.BYTEHIDE_API_TOKEN }} run: ./gradlew assembleRelease - name: Upload APK uses: actions/upload-artifact@v4 with: name: app-release path: app/build/outputs/apk/release/app-release.apk ``` > **Store your token securely** > Add `BYTEHIDE_API_TOKEN` as a repository secret in GitHub: **Settings > Secrets and variables > Actions > New repository secret**. --- ## GitLab CI ```yaml build_android: stage: build image: gradle:8.4-jdk17 variables: BYTEHIDE_API_TOKEN: $BYTEHIDE_API_TOKEN script: - ./gradlew assembleRelease artifacts: paths: - app/build/outputs/apk/release/app-release.apk ``` Add `BYTEHIDE_API_TOKEN` as a CI/CD variable in **Settings > CI/CD > Variables**. --- ## Azure DevOps ```yaml trigger: - main pool: vmImage: 'ubuntu-latest' steps: - task: JavaToolInstaller@0 inputs: versionSpec: '17' jdkArchitectureOption: 'x64' jdkSourceOption: 'PreInstalled' - script: ./gradlew assembleRelease env: BYTEHIDE_API_TOKEN: $(BYTEHIDE_API_TOKEN) displayName: 'Build with Monitor' ``` --- ## Token Configuration In your `build.gradle.kts`, the token is resolved automatically from the environment: ```kotlin monitor { // Token resolved from BYTEHIDE_API_TOKEN env var automatically // Or set explicitly: // projectToken = "bh_xxxxxxxxxxxx" } ``` The token is resolved in priority order: `monitor {}` DSL > `BYTEHIDE_API_TOKEN` env var > `local.properties`. --- ## Key Points - The `BYTEHIDE_API_TOKEN` must be available as an environment variable during the Gradle build - The plugin embeds the encrypted license and configuration into the APK at build time - No runtime environment variable is needed on the device. Monitor initializes automatically - Store the token as a secret in your CI/CD platform. Never commit it to source control --- # Android Gradle Setup Install ByteHide Monitor in your Android project using the Gradle plugin. The plugin is **required** for Android: it signs and embeds the protection configuration at build time and generates the initialization code automatically. {% .lead %} --- ## Requirements | Requirement | Minimum | Recommended | |-------------|---------|-------------| | Android Gradle Plugin | 7.0 | 8.0+ | | Java | 11 | 17 | | Kotlin (if used) | 1.6 | 1.9+ | | Gradle | 7.4 | 8.0+ | | minSdk | 21 | 21 | --- ## Step 1: Configure Repositories The plugin is published on **Maven Central**. Add the standard repositories to your `settings.gradle.kts`: ```kotlin // settings.gradle.kts pluginManagement { repositories { mavenCentral() gradlePluginPortal() google() } } dependencyResolutionManagement { repositories { mavenCentral() google() } } ``` ![Repository configuration in settings.gradle.kts](/images/monitor/android/bytehide-monitor-android-settings-gradle.png) --- ## Step 2: Apply the Plugin Add the Monitor plugin to your app module's `build.gradle.kts`: ```kotlin // app/build.gradle.kts plugins { id("com.android.application") id("com.bytehide.monitor") version "1.0.1" } ``` The plugin automatically adds `com.bytehide:monitor-core:1.0.1` as an `implementation` dependency. No manual dependency needed. --- ## Step 3: Configure the Plugin Add the `monitor` block with your project token: ```kotlin monitor { projectToken = "bh_xxxxxxxxxxxx" } ``` That's it for a minimal setup. The plugin uses sensible defaults for everything else. ### Using a Preset Presets enable a predefined group of protection modules: ```kotlin monitor { projectToken = "bh_xxxxxxxxxxxx" preset = "mobile" } ``` - **`mobile`** - Enables Debugger Detection, Clock Tampering, and Jailbreak Detection. Safe baseline for most Android apps. - **`desktop`** - Everything in mobile plus VM Detection, Emulator Detection, Memory Dump Detection, and License Binding. For desktop JVM apps. - **`null`** (default) - Uses individual `enable*` flags as-is. Full manual control. When using a preset, individual `enable*` flags set **after** the preset override it. ### Manual Configuration For full control, configure each protection module individually: ```kotlin monitor { projectToken = "bh_xxxxxxxxxxxx" enableDebuggerDetection = true enableClockTampering = true enableJailbreakDetection = true enableVirtualMachineDetection = true enableEmulatorDetection = true enableMemoryDumpDetection = false enableProcessInjection = false enableNetworkTampering = false enableLicenseBinding = true enableTamperingDetection = false enableContainerDetection = false enableRemoteDesktop = false enableCloudMetadata = false defaultAction = "log" defaultIntervalMs = 30000 } ``` ![Monitor Gradle plugin configuration in Android Studio](/images/monitor/android/bytehide-monitor-android-gradle-config.png) ### Protection Modules | Property | Type | Default | Description | |----------|------|---------|-------------| | `enableDebuggerDetection` | `Boolean` | `true` | Detect attached debuggers (ADB, JDWP, ptrace) | | `enableClockTampering` | `Boolean` | `true` | Detect system clock manipulation | | `enableJailbreakDetection` | `Boolean` | `true` | Detect root/jailbreak (Magisk, SuperSU, Xposed) | | `enableVirtualMachineDetection` | `Boolean` | `true` | Detect VM environments (VMware, VirtualBox, QEMU) | | `enableEmulatorDetection` | `Boolean` | `true` | Detect Android emulators (Genymotion, AVD, BlueStacks) | | `enableMemoryDumpDetection` | `Boolean` | `false` | Detect memory dumping tools (Frida, Objection) | | `enableProcessInjection` | `Boolean` | `false` | Detect process injection attacks | | `enableNetworkTampering` | `Boolean` | `false` | Detect MITM proxies, VPNs, SSL interception | | `enableLicenseBinding` | `Boolean` | `true` | Validate license binding to device | | `enableTamperingDetection` | `Boolean` | `false` | Detect file/code integrity violations | | `enableContainerDetection` | `Boolean` | `false` | Detect Docker, Kubernetes, LXC | | `enableRemoteDesktop` | `Boolean` | `false` | Detect remote desktop sessions | | `enableCloudMetadata` | `Boolean` | `false` | Detect cloud metadata endpoints | ### Behavior | Property | Type | Default | Description | |----------|------|---------|-------------| | `defaultAction` | `String` | `"log"` | Action when a threat is detected: `"log"`, `"close"`, `"erase"` | | `defaultIntervalMs` | `Int` | `30000` | Detection check interval in milliseconds | --- ## Token Resolution The project token is resolved in priority order: | Priority | Source | Example | |----------|--------|---------| | 1 | `monitor {}` DSL | `projectToken = "bh_xxx"` | | 2 | Environment variable | `BYTEHIDE_API_TOKEN=bh_xxx` | | 3 | `local.properties` | `bytehide.api.token=bh_xxx` | For teams, use `local.properties` (already in `.gitignore`) or an environment variable so the token is never committed. --- ## What the Plugin Does at Build Time When you run `./gradlew assembleDebug` (or any build), the plugin: 1. **Signs the assembly** to protect the APK against tampering 2. **Generates a `ContentProvider`** that auto-initializes Monitor when the app starts 3. **Registers the provider** in `AndroidManifest.xml` 4. **Adds `INTERNET` permission** if not already present 5. **Embeds encrypted configuration** with your protection settings All of this happens automatically. No code changes required for basic protection. --- ## Step 4: Build and Verify Run a build: ```bash ./gradlew assembleDebug ``` When the build runs successfully, you'll see: ``` Configuring ByteHide Monitor... API Token: bh_POlhU6... Package: com.example.myapp Generating MonitorContentProvider... Registering provider in AndroidManifest.xml... Signing assembly... Embedding encrypted resources... ByteHide Monitor configured successfully ``` At runtime, filter Logcat by tag `ByteHideMonitor` to confirm Monitor is running: ``` I/ByteHideMonitor: [I001_INIT_START] MonitorLogger initialized with 2 sinks I/ByteHideMonitor: [I002_INIT_SUCCESS] ByteHideMonitor initialization complete I/ByteHideMonitor: [I010_API_CONNECTED] Registering device... ``` --- ## ProGuard / R8 The library ships consumer ProGuard rules automatically. No extra configuration needed. --- ## Package Name Detection The plugin auto-detects your package name from `android.namespace` or `applicationId`. If auto-detection fails, set it explicitly: ```kotlin monitor { packageName = "com.example.myapp" } ``` --- ## Next Steps - [Quick Start](/platforms/android/products/monitor/quick-start) - Get protected in 5 minutes - [Configuration API](/platforms/android/products/monitor/configuration-api) - Code-based configuration for custom actions - [CI/CD Integration](/platforms/android/products/monitor/installation/cicd) - Pipeline setup --- # JSON Configuration Configure Monitor using local JSON configuration files. Ideal for version-controlled setups, offline environments, and CI/CD pipelines. {% .lead %} --- ## Overview JSON configuration lets you define protections, logging, rate limiting, and other Monitor settings in a file that lives alongside your application code. This is useful for: - **Version control**: Track configuration changes in git alongside your codebase - **Environment-specific configs**: Different files per environment (dev, staging, production) - **Offline deployments**: No dependency on the ByteHide Cloud API - **CI/CD pipelines**: Automate configuration as part of your build and deploy process > **Configuration Priority** > When multiple configuration sources are present, they are applied in this priority order: **Cloud Dashboard** (highest) > **JSON File** > **Code (Configuration API)** (lowest). Cloud configuration overrides JSON settings. See [Cloud Configuration](/platforms/android/products/monitor/cloud-configuration) for details. > **Export from Cloud Dashboard** > If you already have rules configured in the Cloud Dashboard, click **Export config** in the Workflow tab to download them as a JSON file. This gives you a ready-to-use configuration file that matches your current cloud setup. --- ## Configuration Files The SDK searches for configuration files in this order: 1. **Encrypted embedded config** (injected automatically by the Gradle plugin at build time) 2. **Plain JSON files** (fallback for development / desktop): - `monitor-config.json` - `bytehide-monitor-config.json` - `bytehide.monitor.json` - `monitor.config.json` **Android**: Place the file in `src/main/assets/`. **Desktop/Server**: Place it in `src/main/resources/` (classpath). > **Android with Gradle plugin** > On Android with the Gradle plugin, the plugin generates and embeds an encrypted config automatically from the `monitor {}` DSL. You only need a manual JSON file if you're **not** using the plugin or want to override the embedded config during development. --- ## Basic Configuration ### Mobile Application ```json { "enabled": true, "projectToken": "${BYTEHIDE_API_TOKEN}", "protections": [ { "type": "DebuggerDetection", "enabled": true, "action": "close" }, { "type": "JailbreakDetection", "enabled": true, "action": "close" }, { "type": "ClockTampering", "enabled": true, "action": "log" } ] } ``` ### Desktop Application ```json { "enabled": true, "projectToken": "${BYTEHIDE_API_TOKEN}", "protections": [ { "type": "DebuggerDetection", "enabled": true, "action": "close" }, { "type": "VirtualMachineDetection", "enabled": true, "action": "log" }, { "type": "ProcessInjection", "enabled": true, "action": "log" }, { "type": "ContainerDetection", "enabled": true, "action": "log" }, { "type": "CloudMetadata", "enabled": true, "action": "log" } ] } ``` --- ## Complete Schema Reference ### Root Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `name` | string | - | Configuration name/description | | `enabled` | boolean | `true` | Enable/disable monitoring | | `projectToken` | string | - | ByteHide project token (can use env vars) | | `preset` | string | - | `"cloud"`, `"desktop"`, `"mobile"`, `"videogame"`, `"custom"` | | `debugResponses` | boolean | `false` | Include threat details in responses (dev only) | | `autoIntegration` | boolean | `true` | Auto-register middleware (Android web frameworks only) | | `throwOnConnectionFailure` | boolean | `false` | Fail startup if backend unreachable | | `logging` | object | - | Logging configuration | | `protections` | object | - | Protection module configurations | | `cloud` | object | - | Cloud-specific settings (web apps only) | --- ### Protection Configuration Each protection is an object in the `protections` array: ```json { "protections": [ { "type": "DebuggerDetection", "enabled": true, "action": "close", "customActionName": "my-action" } ] } ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `type` | string | *(required)* | Module name (see values below) | | `enabled` | boolean | `true` | Enable this protection | | `action` | string | `"log"` | `"none"`, `"log"`, `"close"`, `"erase"`, `"custom"` | | `intervalMs` | integer | varies | Check interval in milliseconds | | `customActionName` | string | - | Name of custom handler (when `action` is `"custom"`) | ### Protection `type` Values Use the PascalCase name (case-insensitive): | Value | Description | |-------|-------------| | `"DebuggerDetection"` | Attached debuggers (ADB, JDWP, ptrace) | | `"ClockTampering"` | System clock manipulation | | `"JailbreakDetection"` | Root / jailbreak | | `"VirtualMachineDetection"` | VM environments (VMware, VirtualBox, QEMU) | | `"EmulatorDetection"` | Android emulators (Genymotion, AVD, BlueStacks) | | `"MemoryDumpDetection"` | Memory dumping tools (Frida, Objection) | | `"TamperingDetection"` | File/code integrity violations | | `"ProcessInjection"` | Process injection attacks | | `"NetworkTampering"` | MITM / proxy / VPN | | `"LicenseBinding"` | License-to-device binding | | `"ContainerDetection"` | Docker / Kubernetes / LXC | | `"RemoteDesktop"` | Remote desktop sessions | | `"CloudMetadata"` | Cloud metadata endpoints (AWS, Azure, GCP) | > **Interval Configuration** > `intervalMs` only applies to desktop/mobile protections (DebuggerDetection, VirtualMachineDetection, etc.). Web protections run per-request. --- ### Available Presets Presets enable a predefined group of protections. See [Protection Modules](/platforms/android/products/monitor/protection-modules) for the full reference of all available modules. #### `"cloud"` - Web Applications Enables web-focused protections: - SqlInjection - CrossSiteScripting - PathTraversal - CommandInjection - SSRF - LdapInjection - XxeInjection - NoSqlInjection - LlmPromptInjection #### `"desktop"` - Desktop Applications Enables desktop-focused protections: - DebuggerDetection - VirtualMachineDetection - EmulatorDetection - ClockTampering - MemoryDumpDetection - ProcessInjection #### `"mobile"` - Mobile Applications Enables mobile-focused protections: - JailbreakDetection (iOS/Android root) - DebuggerDetection - EmulatorDetection - ClockTampering - MemoryDumpDetection - HookingDetection #### `"videogame"` - Game Applications Enables game-focused protections: - DebuggerDetection - MemoryDumpDetection - SpeedHackDetection - CheatEngineDetection #### `"custom"` - Manual Configuration No default protections. Specify all protections manually. --- ## Logging Configuration ```json { "logging": { "level": "warning", "console": true, "debug": false, "file": { "enabled": true, "path": "logs/monitor.log", "maxSizeMB": 10, "maxFiles": 5 }, "bytehideLogs": { "enabled": false, "token": "${BYTEHIDE_LOGS_TOKEN}", "persist": true, "filePath": "logs/bytehide-logs-offline.json", "maskSensitiveData": ["password", "token", "apiKey"] } } } ``` ### Logging Fields | Field | Type | Default | Description | |-------|------|---------|-------------| | `level` | string | `"info"` | `"trace"`, `"debug"`, `"info"`, `"warning"`, `"error"` | | `console` | boolean | `false` | Enable console logging (stdout) | | `debug` | boolean | `false` | Enable debug output | | `file` | object | - | File logging configuration | | `bytehideLogs` | object | - | ByteHide Logs integration | ### File Logging | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `false` | Enable file logging | | `path` | string | `"logs/bytehide-monitor.log"` | Log file path | | `maxSizeMB` | number | `10` | Max file size before rotation | | `maxFiles` | number | `5` | Number of backup files | ### ByteHide Logs Integration Requires the ByteHide Logger integration. | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `false` | Enable ByteHide Logs | | `token` | string | - | ByteHide Logs API token | | `persist` | boolean | `true` | Persist logs locally when offline | | `filePath` | string | - | Offline persistence path | | `maskSensitiveData` | array | - | Patterns to mask (e.g., `["password"]`) | --- ## Cloud Configuration (Web Applications) Advanced settings for web/API applications: ```json { "cloud": { "rateLimit": { "enabled": true, "maxRequests": 100, "windowSizeInMS": 60000 }, "anomalyDetection": { "enabled": true, "detectIpChanges": true, "detectUserAgentChanges": true, "detectSuspiciousPatterns": true }, "endpoints": [ { "method": "POST", "route": "/api/admin/*", "protections": { "SqlInjection": { "enabled": true, "action": "block" } } }, { "method": "*", "route": "/health", "forceProtectionOff": true } ] } } ``` ### Rate Limiting | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `false` | Enable rate limiting | | `maxRequests` | number | `100` | Max requests per window | | `windowSizeInMS` | number | `60000` | Time window in milliseconds | ### Anomaly Detection | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `false` | Enable anomaly detection | | `detectIpChanges` | boolean | `true` | Detect IP address changes | | `detectUserAgentChanges` | boolean | `true` | Detect User-Agent changes | | `detectSuspiciousPatterns` | boolean | `true` | Detect suspicious patterns | ### Endpoint-Specific Configuration Override protections for specific routes: | Field | Type | Description | |-------|------|-------------| | `method` | string | `"GET"`, `"POST"`, `"PUT"`, `"DELETE"`, `"*"` (all) | | `route` | string | Route pattern (e.g., `"/api/users/{id}"`, `"/admin/*"`) | | `forceProtectionOff` | boolean | Disable ALL protections for this endpoint | | `protections` | object | Endpoint-specific protection overrides | | `rateLimit` | object | Endpoint-specific rate limit | --- ## Environment Variables You can reference environment variables in any string value using `${VARIABLE_NAME}` syntax: ```json { "projectToken": "${BYTEHIDE_API_TOKEN}", "logging": { "bytehideLogs": { "token": "${BYTEHIDE_LOGS_TOKEN}" } } } ``` This avoids hardcoding sensitive values in configuration files. ### Token Resolution Order The project token is resolved in this order: 1. `BYTEHIDE_API_TOKEN` environment variable 2. `BYTEHIDE_MONITOR_TOKEN` environment variable 3. `projectToken` value in the JSON file --- ## Complete Example Desktop application with comprehensive configuration: ```json { "name": "My Production App", "enabled": true, "projectToken": "${BYTEHIDE_API_TOKEN}", "preset": "desktop", "debugResponses": false, "throwOnConnectionFailure": false, "logging": { "level": "warning", "console": false, "file": { "enabled": true, "path": "logs/monitor.log", "maxSizeMB": 50, "maxFiles": 10 } }, "protections": [ { "type": "DebuggerDetection", "enabled": true, "action": "close" }, { "type": "VirtualMachineDetection", "enabled": true, "action": "log" }, { "type": "ClockTampering", "enabled": true, "action": "close" }, { "type": "MemoryDumpDetection", "enabled": true, "action": "erase" }, { "type": "ProcessInjection", "enabled": true, "action": "close" } ] } ``` Web application with cloud features: ```json { "name": "My Web API", "enabled": true, "projectToken": "${BYTEHIDE_API_TOKEN}", "preset": "cloud", "autoIntegration": true, "debugResponses": false, "logging": { "level": "info", "console": true, "bytehideLogs": { "enabled": true, "token": "${BYTEHIDE_LOGS_TOKEN}", "persist": true, "maskSensitiveData": ["password", "token", "apiKey", "secret"] } }, "protections": { "SqlInjection": { "enabled": true, "action": "block" }, "CrossSiteScripting": { "enabled": true, "action": "block" }, "PathTraversal": { "enabled": true, "action": "block" }, "CommandInjection": { "enabled": true, "action": "block" }, "SSRF": { "enabled": true, "action": "block" }, "LlmPromptInjection": { "enabled": true, "action": "log" } }, "cloud": { "rateLimit": { "enabled": true, "maxRequests": 1000, "windowSizeInMS": 60000 }, "anomalyDetection": { "enabled": true, "detectIpChanges": true, "detectUserAgentChanges": true, "detectSuspiciousPatterns": true }, "endpoints": [ { "method": "*", "route": "/health", "forceProtectionOff": true }, { "method": "POST", "route": "/api/admin/*", "rateLimit": { "enabled": true, "maxRequests": 10, "windowSizeInMS": 60000 } }, { "method": "POST", "route": "/api/public/search", "protections": { "SqlInjection": { "enabled": true, "action": "block" }, "NoSqlInjection": { "enabled": true, "action": "block" } } } ] } } ``` --- ## Advanced Interval Configuration For desktop/mobile protections, you can specify check intervals: ```json { "protections": [ { "type": "DebuggerDetection", "enabled": true, "action": "close", "intervalMs": 30000 }, { "type": "VirtualMachineDetection", "enabled": true, "action": "log", "intervalMs": 120000 }, { "type": "ClockTampering", "enabled": true, "action": "close", "intervalMs": 300000 } ] } ``` **Recommended intervals:** - DebuggerDetection: 30000ms (30 seconds) - VirtualMachineDetection: 120000ms (2 minutes, runs once typically) - ClockTampering: 300000ms (5 minutes) - MemoryDumpDetection: 60000ms (1 minute) - JailbreakDetection: 120000ms (2 minutes, runs once typically) > **Performance Impact** > Lower intervals mean more frequent checks but higher CPU usage. Balance security needs with performance requirements. --- ## Next Steps --- # Monitor Logging Configure how Monitor logs security events, threat detections, and operational information. Multiple output destinations, configurable log levels, and integration with ByteHide Logs for centralized forensic logging. {% .lead %} --- ## Overview Monitor generates log events for every security-relevant action: protection module initialization, threat detections, response actions taken, cloud sync status, and internal errors. You control what gets logged, at what level, and where the output goes. Logging can be configured from three sources: - **[Cloud Dashboard](/platforms/android/products/monitor/cloud-configuration)**: Toggle logging settings in the Advanced Configuration panel of the Workflow tab - **[JSON file](/platforms/android/products/monitor/json-configuration)**: Define logging in the `logging` object of your configuration file - **[Configuration API](/platforms/android/products/monitor/configuration-api)**: Set logging options programmatically in code --- ## Log Levels Monitor supports five log levels, from most to least verbose: | Level | Description | When to Use | |---|---|---| | **Debug** | Detailed diagnostic information including internal state | Development and active troubleshooting only | | **Info** | General operational events: module loaded, config synced, incident reported | Default for production | | **Warning** | Potential issues that do not prevent operation | Staging environments, early detection of misconfigurations | | **Error** | Errors that affect functionality but do not stop Monitor | Production minimum recommended level | | **Critical** | Severe errors requiring immediate attention | Always logged regardless of configured level | Set the minimum level to control which events are recorded. For example, setting the level to **Warning** records Warning, Error, and Critical events, but ignores Debug and Info. --- ## Output Destinations ### Console Output Outputs Monitor events to standard output (stdout). Useful during development and in containerized environments where logs are collected from stdout (Docker, Kubernetes). ```json { "logging": { "level": "info", "console": true } } ``` ### File Logging Writes Monitor events to a log file on disk with automatic rotation. When the log file reaches the configured size limit, it rotates to a backup file. ```json { "logging": { "file": { "enabled": true, "path": "logs/monitor.log", "maxSizeMB": 10, "maxFiles": 5 } } } ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `false` | Enable file logging | | `path` | string | `"logs/bytehide-monitor.log"` | Log file path | | `maxSizeMB` | number | `10` | Max file size before rotation | | `maxFiles` | number | `5` | Number of backup files to keep | ### ByteHide Logs Send Monitor events to [ByteHide Logs](/platforms/android/products/logs) for centralized, immutable, cryptographically secured logging. This is the recommended option for production environments. When enabled, every security incident Monitor detects is recorded in ByteHide Logs with full context: timestamp, detection type, payload, affected code, device fingerprint, confidence score, and response action taken. Events appear in your ByteHide Logs dashboard alongside application logs from other ByteHide modules. ![ByteHide Logs dashboard showing centralized log entries with severity levels, timestamps, and source details](/images/dotnet/logs/dashboard/main-dashboard.png) ```json { "logging": { "bytehideLogs": { "enabled": true, "token": "${BYTEHIDE_LOGS_TOKEN}", "persist": true, "filePath": "logs/bytehide-logs-offline.json", "maskSensitiveData": ["password", "token", "apiKey", "secret"] } } } ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `false` | Enable ByteHide Logs integration | | `token` | string | - | ByteHide Logs API token | | `persist` | boolean | `true` | Store events locally when the API is unreachable, and sync when connectivity returns | | `filePath` | string | - | Path for offline event storage | | `maskSensitiveData` | array | - | Field names to mask in log output (e.g., `["password", "token"]`) | > **Offline Persistence** > When `persist` is enabled, Monitor stores events locally if it cannot reach the ByteHide Logs API. Events are automatically synced when connectivity is restored. No events are lost during network outages. --- ## Debug Logging Debug logging is a separate toggle from the log level. When enabled, Monitor includes detailed threat information in API responses and log output: attack type, confidence score, payload, source parameter, and internal reference codes. > **Security Risk in Production** > Debug logging exposes security-sensitive information in HTTP responses. An attacker receiving detailed threat analysis in the response body learns exactly what Monitor detected, how confident it is, and which parameter triggered the detection. This information helps attackers refine their payloads to bypass protection. Never enable debug logging in production. ### What Changes with Debug Enabled With debug logging **disabled**, blocked requests return a generic response with no internal details: ```json { "status": 403, "message": "Request blocked.", "info": "This application is protected by ByteHide Monitor. Learn more at https://bytehide.com", "reference": "BHM-A1B2C3D4" } ``` With debug logging **enabled**, the same blocked request returns full threat context: ```json { "type": "https://docs.bytehide.com/monitor/errors/sql-injection", "title": "SQL Injection Detected", "status": 403, "detail": "SQLite SQL Injection detected - query execution blocked", "instance": "/api/users?id=1 OR 1=1", "threatInfo": { "code": "BHM-T001", "category": "injection", "attackType": "SQL Injection", "confidence": 0.95, "payload": "1 OR 1=1 --", "source": "query.id", "reference": "BHM-A1B2C3D4" } } ``` The `threatInfo` object is only included when debug logging is active. This level of detail is invaluable during development to verify that Monitor is detecting and categorizing threats correctly, but it must be disabled before deploying to any environment accessible to external users. ### JSON Configuration ```json { "logging": { "debug": true } } ``` ### When to Use - Verifying that a protection module detects a specific attack pattern during development - Troubleshooting false positives or missed detections in a staging environment - Confirming that cloud configuration sync applies the expected rules - Diagnosing startup failures or configuration loading issues --- ## Cloud Dashboard Configuration You can configure all logging settings from the [Advanced Configuration](/platforms/android/products/monitor/cloud-configuration#advanced-settings) panel in the Workflow tab of the Cloud Dashboard: ![ByteHide Monitor advanced configuration panel with logging levels, anomaly detection, rate limiting, and debug mode settings](/images/monitor/bytehide-monitor-advanced-rules.png) | Setting | Description | |---------|-------------| | **Logging** | Master toggle to enable or disable all logging | | **Minimum Level** | Select the minimum log level (Debug, Info, Warning, Error, Critical) | | **Console Output** | Toggle stdout output | | **Debug Logging** | Toggle verbose diagnostic output (not for production) | | **Local Logging** | Toggle file logging to disk | | **ByteHide Logs** | Toggle integration with ByteHide Logs (recommended) | Changes made in the Cloud Dashboard apply immediately to all running instances without redeployment. --- ## Log Output Format Monitor log entries include: - **Timestamp**: When the event occurred - **Level**: Log level (Debug, Info, Warning, Error, Critical) - **Module**: Which protection module generated the event - **Message**: Description of the event - **Threat Details**: For detection events, includes threat type, confidence score, and action taken Example console output: ``` [2025-01-15 10:23:45.123] [INFO] Monitor initialized successfully [2025-01-15 10:23:45.456] [INFO] Protection modules loaded: 6 active [2025-01-15 10:24:12.789] [WARN] SqlInjection detected - Action: BLOCK - Confidence: 0.95 [2025-01-15 10:24:12.790] [INFO] Incident reported to ByteHide Cloud ``` --- ## Best Practices - Set the minimum level to **Info** in production for a balance between visibility and log volume - Enable **ByteHide Logs** in production for centralized, immutable forensic records - Enable **console logging** in containerized environments (Docker, Kubernetes) where log collectors read from stdout - Enable **file logging** in on-premise or offline deployments where cloud logging is not available - Use `maskSensitiveData` to prevent passwords, tokens, and API keys from appearing in log output - Keep **debug logging disabled** in production. Enable it temporarily when troubleshooting, then disable it again - Configure file rotation (`maxSizeMB`, `maxFiles`) to prevent disk space issues in long-running applications --- ## Next Steps --- # Understand how Monitor protections work Monitor protection modules are runtime detectors that identify threats, attacks, and security violations as they happen inside your application. {% .lead %} --- Each module operates independently and can be enabled, disabled, and configured with its own [response action](/platforms/android/products/monitor/actions). All on-premise modules run at configurable intervals to monitor the runtime environment for threats like debuggers, virtual machines, jailbreaks, and tampering. --- ## On-Premise Protections Passive detectors that run at configurable intervals (`intervalMs`) to monitor the runtime environment. These modules detect reverse engineering, device compromise, and integrity violations on devices where your application runs. All modules work on both mobile and desktop platforms. --- ## Web & Cloud Protections > **Coming Soon** > Cloud protection modules (SQL Injection, XSS, Path Traversal, Command Injection, SSRF, LDAP Injection, XXE, NoSQL Injection, and LLM Prompt Injection) for web API monitoring will be available soon in the Java SDK. --- ## Anomaly Detection Active by default in every project. Anomaly Detection learns your application's normal behavior patterns and flags deviations without requiring predefined rules. It operates across all application types (desktop, mobile, web). --- ## Configuring Protections Each module can be enabled individually with its own response action. You can configure protections from the [Cloud Dashboard](/platforms/android/products/monitor/cloud-configuration), a [JSON configuration file](/platforms/android/products/monitor/json-configuration), or the [Configuration API](/platforms/android/products/monitor/configuration-api). ```json { "protections": [ { "type": "DebuggerDetection", "enabled": true, "action": "close" }, { "type": "JailbreakDetection", "enabled": true, "action": "close" } ] } ``` See [JSON Configuration](/platforms/android/products/monitor/json-configuration) for the full list of configuration options. --- ## Next Steps --- # Anomaly Detection Anomaly Detection is active by default in every Monitor project. It learns your application's normal behavior and automatically flags activity that deviates from it, detecting unknown threats, abnormal patterns, and suspicious access. {% .lead %} --- ## What It Does Anomaly Detection builds a behavioral baseline from your application's real usage and continuously analyzes it to identify suspicious activity. It monitors: - **Authentication patterns**: failed login spikes, credential rotation, login attempts from unusual locations or at unusual times - **Session behavior**: geographic jumps within a session, concurrent sessions from different locations, impossible travel scenarios - **Device behavior**: sudden changes in device usage patterns, interaction styles, and feature access sequences - **Request behavior**: abnormal request rates, non-human navigation sequences, automated patterns - **Error patterns**: sudden spikes in errors that may indicate scanning or fuzzing --- ## Why It's Always On Anomaly Detection doesn't require configuration because it doesn't rely on predefined rules. It builds its baseline automatically from your application's real usage and flags deviations. This means it can detect: - **Zero-day attacks** that no signature exists for yet - **Credential stuffing** campaigns using leaked credential databases - **Brute force attempts** against authentication endpoints - **Account takeover patterns** where attackers test stolen credentials - **Reconnaissance activity** before a targeted attack - **Automated access** from bots or scripts mimicking user behavior --- ## How It Differs From Other Protections Unlike other ByteHide Monitor protections that require explicit configuration via `Monitor.configure()` and a `ProtectionModuleType`, Anomaly Detection: - **Has no enum value**: It is not part of `ProtectionModuleType` and cannot be added via `addProtection()` - **Requires no setup**: Works out-of-the-box on every Monitor instance - **Learns automatically**: Establishes and continuously adapts its behavioral baseline - **Runs transparently**: Operates in the background without impacting application performance --- ## What Gets Reported When Anomaly Detection identifies suspicious behavior, it creates an incident in your [Cloud Panel](/platforms/android/products/monitor/cloud-panel/incidences) with: - The type of anomaly detected (authentication, session, device, rate, etc.) - Confidence score based on how far the behavior deviates from baseline - Device info, session details, and contextual metadata - Timeline of the suspicious activity You can review these incidents alongside incidents from other protection modules in the same dashboard. --- ## Configuration Anomaly Detection works out of the box. You can adjust its sensitivity through the Cloud Panel or JSON configuration: ```json { "anomalyDetection": { "sensitivity": "medium" } } ``` | Setting | Options | Default | Description | |---------|---------|---------|-------------| | `sensitivity` | `low`, `medium`, `high` | `medium` | How aggressively deviations are flagged | ### Sensitivity Levels | Level | Behavior | Best For | |-------|----------|----------| | **Low** | Only extreme deviations trigger incidents | High-traffic apps where minor variations are normal | | **Medium** | Balanced detection with few false positives | Most applications (default) | | **High** | Flags subtle anomalies, more incidents to review | Security-critical applications (finance, healthcare) | --- ## Related - [Protection Modules Overview](/platforms/android/products/monitor/protection-modules) - [Cloud Panel: Incidences](/platforms/android/products/monitor/cloud-panel/incidences) --- # Clock Tampering Detection **Protection Module:** `ClockTampering` ## Available For Android (HTTP time APIs only) Desktop Java (HTTP time APIs + NTP servers) ## How It Works The Clock Tampering Detection module identifies attempts to manipulate the device's system clock. Clock tampering is commonly used to bypass time-based security mechanisms, exploit trial periods, or commit transaction fraud. The module uses multiple independent time sources to detect inconsistencies indicating tampering. ### Detection Techniques **HTTP Time API Comparison (Android & Desktop):** - **worldtimeapi.org**: Fetches UTC time from public API - **timeapi.io**: Alternative time source for consensus - **worldclockapi.com**: Additional verification API **NTP Server Comparison (Desktop Only):** - **time.google.com**: Google's NTP server - **time.windows.com**: Microsoft's NTP server - **pool.ntp.org**: Public NTP pool **Time Consistency Analysis:** - **Cached Reference Time**: Maintains historical reference for offline detection - **Monotonic Clock Comparison**: Compares `System.nanoTime()` (Android) or equivalent against wall clock - **Absolute Time Difference**: Detects forward/backward clock jumps exceeding threshold - **Multiple Source Consensus**: Uses median of multiple sources for accuracy **Confidence Scoring:** - Fresh API response: confidence 0.95 - Cached reference time: confidence 0.85 **Default Threshold**: 86400 seconds (24 hours) **Default Detection Interval**: 5 minutes ## JSON Configuration ```json { "protections": [ { "type": "ClockTampering", "action": "close", "intervalMs": 300000 } ] } ``` ## Code-Based Configuration ### Kotlin ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.CLOCK_TAMPERING, ActionType.CLOSE, 300000 ) } ``` ### Java ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.CLOCK_TAMPERING, ActionType.CLOSE, 300000 ); }); ``` ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **Close** | Terminate application immediately | Production apps with critical IP | | **Log** | Record incident and continue | Development, analytics | | **Erase** | Securely delete data then terminate | Financial, healthcare apps | | **Custom** | Execute custom handler | Enterprise integrations | | **None** | Detect only, no action | Testing configurations | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. ## When to Use Enable Clock Tampering Detection when: - Building subscription or trial-based applications - Protecting against trial extension fraud - Securing transaction processing and payment systems - Implementing time-locked content or promotional offers - Detecting abuse of time-based features - Preventing token expiration bypass attacks - Enforcing time-based licensing compliance ## Code Examples ### Kotlin - Basic Integration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Monitor.configure { config -> config.addProtection( ProtectionModuleType.CLOCK_TAMPERING, ActionType.CLOSE, 300000 ) } setContentView(R.layout.activity_main) } } ``` ### Kotlin - Custom Action with Time Deviation Analysis ```kotlin Monitor.configure { config -> config.registerCustomAction("clock-tampering-handler") { threat -> val threatType = threat.getThreatType() val confidence = threat.getConfidence() val metadata = threat.getMetadata() Log.e("Security", "Time tampering detected: $threatType") Log.d("Metadata", "Confidence: $confidence") val timeDeviation = metadata["time_deviation_seconds"] as? Long ?: 0 Log.w("Time", "System clock off by $timeDeviation seconds") when { timeDeviation > 86400 -> { // More than 24 hours: likely tampering Log.e("Security", "Major time deviation detected. Exiting.") secureDataAndExit() } timeDeviation > 3600 -> { // More than 1 hour: suspicious Log.w("Security", "Significant time deviation. Restricting features.") restrictTimeBasedFeatures() } else -> { // Minor deviation: log and continue Log.i("Security", "Minor time deviation observed.") } } } config.addProtection( ProtectionModuleType.CLOCK_TAMPERING, "clock-tampering-handler", 300000 ) } private fun restrictTimeBasedFeatures() { // Disable time-locked features // Disable trial/subscription checks // Disable promotional offers } private fun secureDataAndExit() { // Wipe sensitive data System.exit(1) } ``` ### Java - Multi-Source Consensus Handling ```java Monitor.configure(config -> { config.registerCustomAction("time-consensus-check", threat -> { Map metadata = threat.getMetadata(); @SuppressWarnings("unchecked") Map apiTimes = (Map) metadata.get("time_api_responses"); long systemTime = (long) metadata.get("system_time_ms"); Log.e("Time", "Time sources: " + apiTimes); Log.d("System", "System clock: " + systemTime); // Check consensus among sources long minTime = apiTimes.values().stream().mapToLong(v -> v).min().orElse(0); long maxTime = apiTimes.values().stream().mapToLong(v -> v).max().orElse(0); long deviation = Math.abs(systemTime - ((minTime + maxTime) / 2)); if (deviation > 300000) { // More than 5 minutes Log.e("Security", "System clock severely out of sync"); invalidateTrialPeriod(); System.exit(1); } }); config.addProtection( ProtectionModuleType.CLOCK_TAMPERING, "time-consensus-check", 300000 ); }); private static void invalidateTrialPeriod() { // Reset trial counters and timestamps // Force re-verification with backend } ``` ### Java - Subscription Protection ```java Monitor.configure(config -> { config.registerCustomAction("subscription-guard", threat -> { Map metadata = threat.getMetadata(); double confidence = threat.getConfidence(); if (confidence > 0.85) { Log.e("Subscription", "Time manipulation detected. Disabling features."); // Disable premium features disableSubscriptionFeatures(); // Force backend verification syncWithBackend(); // Log security event reportClockTamperingEvent(threat); } }); config.addProtection( ProtectionModuleType.CLOCK_TAMPERING, "subscription-guard", 300000 ); }); private static void disableSubscriptionFeatures() { // Disable all premium functionality } private static void syncWithBackend() { // Contact server for authoritative time } private static void reportClockTamperingEvent(Object threat) { // Send security event to backend } ``` ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Android 5.0+ | ✓ Fully Supported | HTTP time API queries | | Android 10+ | ✓ Optimized | Enhanced network handling | | Desktop Java | ✓ Fully Supported | HTTP APIs + NTP servers | | Windows | ✓ Fully Supported | NTP and HTTP time sources | | macOS | ✓ Fully Supported | NTP and HTTP time sources | | Linux | ✓ Fully Supported | NTP and HTTP time sources | ## Performance Impact - **CPU Impact**: < 1% increase during detection cycles - **Memory Overhead**: ~100 KB for time cache and history - **Detection Latency**: 1000-3000 ms per cycle (network API calls) - **Battery Impact**: Moderate (network requests every 5 minutes) - **Network**: Minimal data transfer (~500 bytes per check) ## Threat Detection Details Forward Clock Jump Detection: ```json { "threatType": "forward_clock_jump", "description": "System clock advanced significantly ahead of reference time", "confidence": 0.95, "timestamp": "2026-03-02T18:02:17.956Z", "metadata": { "detectionMethod": "http_time_api_comparison", "time_api_responses": { "worldtimeapi.org": 1708457137000, "timeapi.io": 1708457138000, "worldclockapi.com": 1708457137500 }, "system_time_ms": 1708457737000, "time_deviation_seconds": 600, "deviation_threshold_seconds": 86400, "monotonic_clock_jump_detected": true, "cache_state": "fresh" } } ``` Backward Clock Jump Detection: ```json { "threatType": "backward_clock_jump", "description": "System clock reversed to earlier time", "confidence": 0.92, "timestamp": "2026-03-02T18:02:17.956Z", "metadata": { "detectionMethod": "monotonic_clock_analysis", "previous_system_time_ms": 1708457937000, "current_system_time_ms": 1708457137000, "time_deviation_seconds": -800, "monotonic_clock_previous": 1234567890000000, "monotonic_clock_current": 1234567890050000, "cache_state": "using_cached_reference", "cached_reference_confidence": 0.85 } } ``` ## Related Protections - [Debugger Detection](/platforms/android/products/monitor/protections/debugger-detection) - [Jailbreak Detection](/platforms/android/products/monitor/protections/jailbreak-detection) - [Virtual Machine Detection](/platforms/android/products/monitor/protections/virtual-machine-detection) - [Tampering Detection](/platforms/android/products/monitor/protections/tampering-detection) ## Next Steps - [Configure Protection Actions](/platforms/android/products/monitor/actions) - [Implement Custom Actions](/platforms/android/products/monitor/actions/custom) - [Configuration API Reference](/platforms/android/products/monitor/configuration-api) --- # Cloud Metadata Detection **Protection Module:** `CloudMetadata` Detects when the application is running on cloud provider infrastructure by probing Instance Metadata Services (IMDS) endpoints and analyzing cloud-specific environment indicators. **Available for:** All platforms (uses HTTP metadata endpoints) --- ## How It Works The Cloud Metadata Detection module identifies cloud environments by querying metadata service endpoints that are only available when running on cloud provider infrastructure. This prevents applications from being deployed in cloud environments for large-scale unauthorized testing, credential harvesting, or distributed abuse. ### Detection Techniques - **AWS EC2 Detection**: Queries `http://169.254.169.254/latest/meta-data/` for instance-id, instance-type, placement/availability-zone (confidence: 0.95) - **Azure VM Detection**: Queries `http://169.254.169.254/metadata/instance?api-version=2021-02-01` with Metadata header for vmId, vmSize, location, zone (confidence: 0.95) - **Google Cloud Detection**: Queries `http://metadata.google.internal/computeMetadata/v1/instance/` with Metadata-Flavor header for id, machine-type, zone (confidence: 0.95) - **DigitalOcean Detection**: Queries `http://169.254.169.254/metadata/v1/` for id, region (confidence: 0.95) - **HTTP Timeout**: 2 seconds per provider endpoint - **Caching**: Cached permanently after successful detection Detection confidence: **0.95** | Default interval: **10 minutes** (cached permanently) | HTTP timeout: **2 seconds per provider** ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "CloudMetadata", "action": "log", "intervalMs": 600000 } ] } ``` ### Kotlin Code-Based ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.CLOUD_METADATA, ActionType.LOG, 600000 ) } ``` ### Java Code-Based ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.CLOUD_METADATA, ActionType.LOG, 600000 ); }); ``` ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **close** | Terminate application immediately | Production apps with critical IP | | **log** | Record incident and continue | Development, analytics | | **erase** | Securely delete data then terminate | Financial, healthcare apps | | **custom** | Execute custom handler | Enterprise integrations | | **none** | Detect only, no action | Testing configurations | | **block** | Block the operation | Cloud protection modules | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. ## When to Use Enable Cloud Metadata Detection when: - Preventing large-scale cloud-based abuse campaigns - Ensuring applications only run on genuine user devices - Protecting against distributed attacks and credential farming - Preventing unauthorized cloud deployments - Enforcing device-locked licensing and feature access - Monitoring infrastructure-level attacks ## Code Examples ### Kotlin - Basic Integration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Monitor.configure { config -> config.addProtection( ProtectionModuleType.CLOUD_METADATA, ActionType.LOG, 600000 ) } setContentView(R.layout.activity_main) } } ``` ### Kotlin - Custom Action with Provider Detection ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.registerCustomAction("handle-cloud-metadata") { threat -> val threatType = threat.getThreatType() val description = threat.getDescription() val confidence = threat.getConfidence() val metadata = threat.getMetadata() Log.e("Security", "Cloud environment detected: $threatType (confidence: $confidence)") Log.e("Security", "Description: $description") when (threatType) { "AWS" -> { Log.e("Security", "AWS EC2 instance detected") val instanceId = metadata["instance-id"] val region = metadata["placement/region"] Log.e("Security", "Instance: $instanceId in region: $region") disableSensitiveFeatures() } "Azure" -> { Log.e("Security", "Azure VM detected") val vmId = metadata["vmId"] val location = metadata["location"] Log.e("Security", "VM: $vmId in location: $location") disableSensitiveFeatures() } "GCP" -> { Log.e("Security", "Google Cloud instance detected") val projectId = metadata["project/project-id"] val zone = metadata["instance/zone"] Log.e("Security", "Project: $projectId in zone: $zone") disableSensitiveFeatures() } } } config.addProtection( ProtectionModuleType.CLOUD_METADATA, "handle-cloud-metadata", 600000 ) } private fun disableSensitiveFeatures() { // Disable payment processing, premium features, etc. } ``` ### Java - Close Action (Production Security) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.CLOUD_METADATA, ActionType.CLOSE, 600000 ); }); ``` ### Java - Erase Action (Financial/Sensitive Apps) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.CLOUD_METADATA, ActionType.ERASE, 600000 ); }); ``` ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Windows | ✓ Fully Supported | HTTP IMDS endpoint access | | Linux | ✓ Fully Supported | HTTP IMDS endpoint access | | macOS | ✓ Fully Supported | HTTP IMDS endpoint access | | Mobile (Android) | ✓ Supported | HTTP IMDS endpoint access (limited cloud use) | | AWS EC2 | ✓ Detected | All instance types (confidence: 0.95) | | Azure VMs | ✓ Detected | Both classic and ARM VMs (confidence: 0.95) | | Google Cloud | ✓ Detected | All machine types (confidence: 0.95) | | DigitalOcean | ✓ Detected | Droplet instances (confidence: 0.95) | | Kubernetes Pods | ✓ Detected | K8s service account injection | ## Performance Impact - **CPU Impact**: < 1% during detection cycles - **Memory Overhead**: ~250 KB for IMDS cache - **Detection Latency**: 200-500 ms per cycle (includes network probe with 2-second timeout per provider) - **Battery Impact**: Minimal (infrequent checks, cached permanently) - **Network Impact**: < 1 KB per detection cycle (only on initial detection) ## Threat Detection Details ```json { "detection": { "threatType": "AWS", "timestamp": "2026-03-03T14:30:45.309Z", "description": "AWS EC2 instance metadata service detected - application running on AWS infrastructure", "confidence": 0.95, "metadata": { "cloudProvider": "AWS", "environmentType": "EC2", "instanceId": "i-0a1b2c3d4e5f6g7h8", "instanceType": "t3.micro", "region": "us-east-1", "availabilityZone": "us-east-1a", "accountId": "123456789012", "amiId": "ami-0a1b2c3d4e5f6g7h8", "imdsVersion": "2", "detectionMethod": "imds_metadata_service" } } } ``` Azure VM detection example: ```json { "detection": { "threatType": "Azure", "timestamp": "2026-03-03T14:30:45.309Z", "description": "Azure VM metadata service detected - application running on Azure infrastructure", "confidence": 0.95, "metadata": { "cloudProvider": "Azure", "environmentType": "VM", "vmId": "8f3348df-513e-46eb-9560-90a4626c68c4", "vmSize": "Standard_B1s", "location": "eastus", "zone": "1", "subscriptionId": "12345678-1234-1234-1234-123456789012", "resourceGroupName": "my-resource-group", "imdsVersion": "2021-02-01", "detectionMethod": "azure_imds_endpoint" } } } ``` Google Cloud detection example: ```json { "detection": { "threatType": "GCP", "timestamp": "2026-03-03T14:30:45.309Z", "description": "Google Cloud instance metadata detected - application running on GCP infrastructure", "confidence": 0.95, "metadata": { "cloudProvider": "GCP", "environmentType": "ComputeEngine", "instanceId": "1234567890123456789", "machineType": "n1-standard-1", "zone": "us-central1-a", "projectId": "my-project-12345", "projectNumber": "1234567890", "serviceAccountEmail": "default@my-project-12345.iam.gserviceaccount.com", "detectionMethod": "gcp_metadata_server" } } } ``` ## Related Protections ## Next Steps --- # Container Detection **Protection Module:** `ContainerDetection` Detects when the application is running inside containerized environments such as Docker, Kubernetes, LXC, Podman, or systemd-nspawn. **Available for:** Linux (full), Windows (partial), macOS (limited), Mobile (N/A) --- ## How It Works The Container Detection module identifies when the application is running inside containerized environments by analyzing system indicators specific to different container runtimes and environment metadata. These environments are commonly used for automated testing, malware analysis, and unauthorized code execution. ### Detection Techniques - **Docker Markers**: Checks for `/.dockerenv` file and docker-specific cgroup paths - **Cgroup Analysis**: Identifies container control group signatures indicating Docker, LXC, Podman, or systemd-nspawn - **Kubernetes Detection**: Identifies Kubernetes service account paths and environment variables (KUBERNETES_SERVICE_HOST, KUBERNETES_SERVICE_PORT, KUBERNETES_PORT) - **LXC/LXD Indicators**: Detects LXC container markers in `/proc/1/cgroup` and `/run/systemd/container` file - **Podman Detection**: Identifies Podman containers via `/proc/1/cgroup` and `/run/.containerenv` file - **systemd-nspawn Detection**: Detects systemd-nspawn environments via cgroup and container markers - **Environment Variable Analysis**: Monitors for container-specific environment variables - **Hostname Detection**: Identifies container-style hostnames and UUID-based naming patterns Detection confidence: **0.9** | Default interval: **10 minutes** (cached permanently) ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "ContainerDetection", "action": "log", "intervalMs": 600000 } ] } ``` ### Kotlin Code-Based ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.CONTAINER_DETECTION, ActionType.LOG, 600000 ) } ``` ### Java Code-Based ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.CONTAINER_DETECTION, ActionType.LOG, 600000 ); }); ``` ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **close** | Terminate application immediately | Production apps with critical IP | | **log** | Record incident and continue | Development, analytics | | **erase** | Securely delete data then terminate | Financial, healthcare apps | | **custom** | Execute custom handler | Enterprise integrations | | **none** | Detect only, no action | Testing configurations | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. ## When to Use Enable Container Detection when: - Protecting against automated abuse and bot farming - Preventing large-scale security research and reverse engineering - Detecting unauthorized execution environments - Monitoring for infrastructure-level attacks - Preventing containerized malware execution - Enforcing real device usage policies ## Code Examples ### Kotlin - Basic Integration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Monitor.configure { config -> config.addProtection( ProtectionModuleType.CONTAINER_DETECTION, ActionType.LOG, 600000 ) } setContentView(R.layout.activity_main) } } ``` ### Kotlin - Custom Action Handler ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.registerCustomAction("handle-container") { threat -> val threatType = threat.getThreatType() val description = threat.getDescription() val confidence = threat.getConfidence() val metadata = threat.getMetadata() Log.e("Security", "Container detected: $threatType (confidence: $confidence)") Log.e("Security", "Description: $description") Log.e("Security", "Metadata: $metadata") // Custom response: disable sensitive features, alert admin, etc. disableSensitiveFeatures() } config.addProtection( ProtectionModuleType.CONTAINER_DETECTION, "handle-container", 600000 ) } private fun disableSensitiveFeatures() { // Disable payment processing, premium features, etc. } ``` ### Java - Basic Integration ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Monitor.configure(config -> { config.addProtection( ProtectionModuleType.CONTAINER_DETECTION, ActionType.LOG, 600000 ); }); setContentView(R.layout.activity_main); } } ``` ### Java - Close Action (Production Security) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.CONTAINER_DETECTION, ActionType.CLOSE, 600000 ); }); ``` ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Linux | ✓ Fully Supported | /proc analysis, cgroup detection, marker files | | Windows | ✓ Partial | Environment variables, process detection | | macOS | ✓ Limited | Process-based detection | | Mobile (Android) | ✗ N/A | Not applicable on mobile platforms | | Docker Engine | ✓ Detected | All Docker versions | | Kubernetes | ✓ Detected | Service account path detection | | LXC/LXD | ✓ Detected | Cgroup and marker file detection | | Podman | ✓ Detected | Cgroup and `.containerenv` detection | | systemd-nspawn | ✓ Detected | Cgroup and `/run/systemd/container` detection | ## Performance Impact - **CPU Impact**: < 1% during detection cycles - **Memory Overhead**: ~300 KB for environment data caching - **Detection Latency**: 100-200 ms per cycle - **Battery Impact**: Minimal (low-frequency checks, cached permanently) - **Network Impact**: None (purely local system analysis) ## Threat Detection Details ```json { "detection": { "threatType": "Docker", "timestamp": "2026-03-03T14:30:45.309Z", "description": "Docker container environment detected via /.dockerenv marker and cgroup analysis", "confidence": 0.9, "metadata": { "containerType": "docker", "dockerenvExists": true, "cgroupPath": "/docker/a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6", "containerId": "a1b2c3d4e5f6", "hostname": "a1b2c3d4e5f6", "detectionMethod": "marker_and_cgroup_analysis", "indicators": ["/.dockerenv", "docker", "/docker/", "DOCKER_HOST"] } } } ``` Another detection example (Kubernetes): ```json { "detection": { "threatType": "Kubernetes", "timestamp": "2026-03-03T14:30:45.309Z", "description": "Kubernetes environment detected via service account path and environment variables", "confidence": 0.9, "metadata": { "containerType": "kubernetes", "serviceAccountPath": "/var/run/secrets/kubernetes.io/serviceaccount", "kubernetesPod": true, "namespace": "default", "podName": "app-deployment-5d4c8b7a9", "clusterDomain": "cluster.local", "detectionMethod": "service_account_path_and_env_vars", "indicators": ["KUBERNETES_SERVICE_HOST", "KUBERNETES_SERVICE_PORT", "/var/run/secrets/kubernetes.io"] } } } ``` ## Related Protections ## Next Steps --- # Debugger Detection **Protection Module:** `DebuggerDetection` ## Available For Android API 21+ (Mobile) Desktop Java Runtime (JVM) ## How It Works The Debugger Detection module monitors and identifies various debugging interfaces and tools that could be used to inspect or manipulate your application at runtime. It detects active debugging sessions through platform-specific mechanisms and prevents execution when debugging tools are attached. ### Detection Techniques **Android Platform:** - **isDebuggerConnected()**: Uses `android.os.Debug.isDebuggerConnected()` via reflection to detect active debugger connections - **Build Type Detection**: Checks `Build.TYPE` for engineering builds ("eng") or debug builds ("userdebug") that indicate development environments - **Confidence**: 1.0 (maximum certainty on Android) **Desktop Java Platform:** - **JDWP Argument Inspection**: Analyzes `ManagementFactory.getRuntimeMXBean().getInputArguments()` for JDWP flags including `-agentlib:jdwp`, `-Xrunjdwp`, and `-Xdebug` - **Debug Session Detection**: Identifies active Java Debug Wire Protocol sessions - **Confidence**: 0.9 Default detection interval: **60 seconds** ## JSON Configuration ```json { "protections": [ { "type": "DebuggerDetection", "action": "close", "intervalMs": 60000 } ] } ``` ## Code-Based Configuration ### Kotlin ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.CLOSE, 60000 ) } ``` ### Java ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.CLOSE, 60000 ); }); ``` ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **Close** | Terminate application immediately | Production apps with critical IP | | **Log** | Record incident and continue | Development, analytics | | **Erase** | Securely delete data then terminate | Financial, healthcare apps | | **Custom** | Execute custom handler | Enterprise integrations | | **None** | Detect only, no action | Testing configurations | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. ## When to Use Enable Debugger Detection when: - Building financial or banking applications - Protecting sensitive user data or credentials - Developing premium apps vulnerable to feature unlocking - Requiring compliance with security standards (PCI DSS, HIPAA) - Preventing reverse engineering and code inspection - Protecting intellectual property in mobile apps ## Code Examples ### Kotlin - Basic Integration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Monitor.configure { config -> config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.CLOSE, 60000 ) } setContentView(R.layout.activity_main) } } ``` ### Kotlin - Custom Action Handler ```kotlin Monitor.configure { config -> config.registerCustomAction("debugger-handler") { threat -> val threatType = threat.getThreatType() val confidence = threat.getConfidence() val metadata = threat.getMetadata() Log.e("Security", "Debugger detected: $threatType (confidence: $confidence)") // Send to security backend reportSecurityEvent( threatType = threatType, confidence = confidence, timestamp = System.currentTimeMillis(), metadata = metadata ) // Graceful shutdown gracefulShutdown() } config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, "debugger-handler", 60000 ) } ``` ### Java - Custom Action with Log Fallback ```java Monitor.configure(config -> { config.registerCustomAction("debugger-handler", threat -> { String threatType = threat.getThreatType(); double confidence = threat.getConfidence(); Map metadata = threat.getMetadata(); if (confidence > 0.95) { Log.e("Security", "High-confidence debugger: " + threatType); System.exit(1); } else { Log.w("Security", "Potential debugger: " + threatType); // Log only, allow execution } }); config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, "debugger-handler", 60000 ); }); ``` ### Java - Different Actions for Different Scenarios ```java Monitor.configure(config -> { // Development build: log only if (BuildConfig.DEBUG) { config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.LOG, 60000 ); } // Production build: close immediately if (BuildConfig.RELEASE) { config.addProtection( ProtectionModuleType.DEBUGGER_DETECTION, ActionType.CLOSE, 60000 ); } }); ``` ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Android 5.0+ | ✓ Fully Supported | API Level 21+ with reflection-based detection | | Android 11+ | ✓ Optimized | Enhanced build property inspection | | Desktop Java | ✓ Supported | JDWP detection via ManagementFactory | | Windows JVM | ✓ Supported | Standard JDWP argument parsing | | macOS JVM | ✓ Supported | Standard JDWP argument parsing | | Linux JVM | ✓ Supported | Standard JDWP argument parsing | ## Performance Impact - **CPU Impact**: < 0.5% increase during detection cycles - **Memory Overhead**: ~50 KB for reflection cache - **Detection Latency**: 10-20 ms per cycle - **Battery Impact**: Minimal (background monitoring only) ## Threat Detection Details When a debugger is detected, the module generates a detection result with the following structure: ```json { "threatType": "isDebuggerConnected", "description": "Active debugger detected via android.os.Debug.isDebuggerConnected()", "confidence": 1.0, "timestamp": "2026-03-02T14:32:17.842Z", "metadata": { "detectionMethod": "reflection_check", "buildType": "eng", "isDebuggerConnected": true, "platformVersion": "Android 12" } } ``` ```json { "threatType": "jdwp_flag_detected", "description": "JDWP flag found in runtime arguments", "confidence": 0.9, "timestamp": "2026-03-02T14:32:17.842Z", "metadata": { "detectionMethod": "jdwp_flag_inspection", "runtimeArguments": ["-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"], "platformVersion": "Java 11", "jvmVersion": "OpenJDK 11.0.11" } } ``` ## Related Protections - [Jailbreak Detection](/platforms/android/products/monitor/protections/jailbreak-detection) - [Virtual Machine Detection](/platforms/android/products/monitor/protections/virtual-machine-detection) - [Emulator Detection](/platforms/android/products/monitor/protections/emulator-detection) - [Memory Dump Detection](/platforms/android/products/monitor/protections/memory-dump-detection) ## Next Steps - [Configure Protection Actions](/platforms/android/products/monitor/actions) - [Implement Custom Actions](/platforms/android/products/monitor/actions/custom) - [Configuration API Reference](/platforms/android/products/monitor/configuration-api) --- # Emulator Detection **Protection Module:** `EmulatorDetection` ## Available For Linux (Wine detection) macOS (Wine + Rosetta 2 detection) Windows (Limited support) ## How It Works The Emulator Detection module identifies runtime emulation layers and compatibility environments that can obscure actual platform capabilities or introduce security risks. It detects Wine-based emulation and Apple's Rosetta 2 translation environment through process enumeration, environment variables, filesystem artifacts, and architecture comparisons. ### Detection Techniques **Wine Detection (Linux, macOS, Windows):** - **Environment Variables**: Checks for `WINE`, `WINEPREFIX`, `WINESERVER`, and other Wine-specific environment variables - **Filesystem Artifacts**: Scans for Wine directories (`/usr/lib/wine`, `~/.wine`, registry files) - **Process Enumeration**: Uses `ProcessHandle.allProcesses()` to detect Wine server processes (`wine`, `wineserver`) running on the system - **Registry Keys**: Checks Windows registry for Wine installation markers **Rosetta 2 Detection (macOS):** - **Architecture Mismatch**: Compares `os.arch` property against `sysctl hw.optional.arm64` to detect ARM64 translation - **Process Architecture**: Identifies processes running under Rosetta translation layer - **System Capabilities**: Checks for native ARM64 support vs. translated execution **Detection Confidence**: 0.95 **Default Detection Interval**: 5 minutes **Caching**: Results cached permanently (until process restart) ## JSON Configuration ```json { "protections": [ { "type": "EmulatorDetection", "action": "block", "intervalMs": 300000 } ] } ``` ## Code-Based Configuration ### Kotlin ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.EMULATOR_DETECTION, ActionType.BLOCK, 300000 ) } ``` ### Java ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.EMULATOR_DETECTION, ActionType.BLOCK, 300000 ); }); ``` ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **Close** | Terminate application immediately | Production apps with critical IP | | **Log** | Record incident and continue | Development, analytics | | **Erase** | Securely delete data then terminate | Financial, healthcare apps | | **Custom** | Execute custom handler | Enterprise integrations | | **None** | Detect only, no action | Testing configurations | | **Block** | Block the operation (cloud modules) | Cloud protection modules | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. ## When to Use Enable Emulator Detection when: - Protecting against unauthorized environment manipulation - Running on Linux/macOS systems where Wine emulation is a concern - Detecting Apple Silicon compatibility shims (Rosetta 2) - Preventing code execution in incompatible runtime environments - Enforcing native execution on target architecture - Detecting security research using emulation layers ## Code Examples ### Kotlin - Basic Integration with Process Detection ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class Application : android.app.Application() { override fun onCreate() { super.onCreate() Monitor.configure { config -> config.addProtection( ProtectionModuleType.EMULATOR_DETECTION, ActionType.CLOSE, 300000 ) } } } ``` ### Kotlin - Custom Action with Environment Analysis ```kotlin Monitor.configure { config -> config.registerCustomAction("emulator-handler") { threat -> val threatType = threat.getThreatType() val confidence = threat.getConfidence() val metadata = threat.getMetadata() Log.e("Security", "Emulation environment detected: $threatType") Log.d("Metadata", "Confidence: $confidence, Details: $metadata") when (threatType) { "wine_detected" -> handleWineEnvironment(metadata) "rosetta2_detected" -> handleRosettaEnvironment(metadata) else -> handleUnknownEmulator(metadata) } } config.addProtection( ProtectionModuleType.EMULATOR_DETECTION, "emulator-handler", 300000 ) } private fun handleWineEnvironment(metadata: Map) { // Wine-specific handling Log.w("Security", "Wine processes: ${metadata["processes"]}") disableNetworkFeatures() } private fun handleRosettaEnvironment(metadata: Map) { // Rosetta 2-specific handling Log.w("Security", "Rosetta translation detected: ${metadata["architecture"]}") reducePerfSensitiveOperations() } ``` ### Java - Conditional Actions Based on Environment ```java Monitor.configure(config -> { config.registerCustomAction("emulator-check", threat -> { double confidence = threat.getConfidence(); String threatType = threat.getThreatType(); // Strict in production if (confidence > 0.95) { Log.e("Security", "Confirmed emulation: " + threatType); secureDataAndExit(); } // Warn on lower confidence if (confidence > 0.7) { Log.w("Security", "Possible emulation: " + threatType); enableSafeMode(); } }); config.addProtection( ProtectionModuleType.EMULATOR_DETECTION, "emulator-check", 300000 ); }); private static void secureDataAndExit() { // Perform secure data wipe System.exit(1); } private static void enableSafeMode() { // Reduce sensitive functionality } ``` ### Java - Wine Detection with Logging ```java Monitor.configure(config -> { config.registerCustomAction("wine-detector", threat -> { Map metadata = threat.getMetadata(); if (metadata.containsKey("wine_processes")) { @SuppressWarnings("unchecked") List processes = (List) metadata.get("wine_processes"); Log.e("Security", "Wine processes detected: " + processes); } if (metadata.containsKey("wine_environment_vars")) { @SuppressWarnings("unchecked") Map envVars = (Map) metadata.get("wine_environment_vars"); Log.e("Security", "Wine environment: " + envVars.keySet()); } }); config.addProtection( ProtectionModuleType.EMULATOR_DETECTION, "wine-detector", 300000 ); }); ``` ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Linux | ✓ Fully Supported | Wine detection via environment and process enumeration | | macOS 10.16+ | ✓ Fully Supported | Wine + Rosetta 2 detection | | Windows | ◐ Limited | Wine detection only, no Rosetta support | | Docker/Containers | ◐ Limited | Process enumeration may be restricted | | Virtualized Linux | ◐ Limited | Wine detection functional, process access varies | ## Performance Impact - **CPU Impact**: < 1% increase during detection cycles - **Memory Overhead**: ~150 KB for process cache - **Detection Latency**: 50-150 ms per cycle - **Battery Impact**: Minimal (one-time detection with caching) - **Note**: Results cached permanently per process lifetime ## Threat Detection Details When emulation is detected, the module generates detection results: ```json { "threatType": "wine_detected", "description": "Wine emulation environment identified via process enumeration", "confidence": 0.95, "timestamp": "2026-03-02T15:45:22.103Z", "metadata": { "detectionMethod": "process_enumeration", "wine_processes": ["wine", "wineserver"], "wine_environment_vars": ["WINE", "WINEPREFIX"], "wine_directories": ["/usr/lib/wine", "/home/user/.wine"], "platform": "Linux" } } ``` ```json { "threatType": "rosetta2_detected", "description": "Apple Rosetta 2 translation layer detected on ARM64 system", "confidence": 0.95, "timestamp": "2026-03-02T15:45:22.103Z", "metadata": { "detectionMethod": "architecture_comparison", "reported_arch": "x86_64", "actual_arch": "arm64", "hw_optional_arm64": 1, "platform": "macOS" } } ``` ## Related Protections - [Virtual Machine Detection](/platforms/android/products/monitor/protections/virtual-machine-detection) - [Debugger Detection](/platforms/android/products/monitor/protections/debugger-detection) - [Jailbreak Detection](/platforms/android/products/monitor/protections/jailbreak-detection) ## Next Steps - [Configure Protection Actions](/platforms/android/products/monitor/actions) - [Implement Custom Actions](/platforms/android/products/monitor/actions/custom) - [Configuration API Reference](/platforms/android/products/monitor/configuration-api) --- # Jailbreak Detection **Protection Module:** `JailbreakDetection` ## Available For Android API 21+ (Mobile) iOS (Planned) ## How It Works The Jailbreak Detection module identifies compromised mobile devices where security controls have been bypassed. It uses multiple detection indicators across device properties, processes, and filesystem artifacts to determine if the device has been rooted (Android) or jailbroken (iOS), with dynamic confidence scoring based on the number of indicators found. ### Detection Techniques **Android Root Detection:** - **Superuser Binary Scanning**: Checks for SU binary paths (`/system/bin/su`, `/system/xbin/su`, `/data/local/su`) - **Root Management Apps**: Detects presence of popular root managers (Magisk, SuperSU, KingRoot) via package scanning - **Build Property Analysis**: Checks for `test-keys` in fingerprint (indicator of custom builds), `ro.debuggable=1` (debug mode enabled) - **SELinux Permissive Mode**: Detects `ro.build.selinux=0` or permissive SELinux policies - **System Partition Writable**: Checks if `/system` partition is writable (sign of partition modification) - **BusyBox Detection**: Scans for BusyBox installation which is commonly used in rooted devices **iOS Jailbreak Detection (Planned):** - **Jailbreak App Detection**: Checks for Cydia, Sileo, zbra package managers - **Symbolic Link Verification**: Identifies /Applications symlink modifications - **Dynamic Library Injection**: Detects injected dylibs and modified binary metadata - **Fork Test**: Executes fork test to detect sandbox restrictions **Dynamic Confidence Scoring:** - Combines multiple detection indicators for increased reliability - Confidence ranges from 0.0 to 1.0 - Adjustable sensitivity levels: `strict` (0.5), `normal` (0.7), `lenient` (0.9) Default detection interval: **5 minutes** Caching: Results cached until device reboot ## JSON Configuration ```json { "protections": [ { "type": "JailbreakDetection", "action": "close", "intervalMs": 300000 } ] } ``` ## Code-Based Configuration ### Kotlin ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.JAILBREAK_DETECTION, ActionType.CLOSE, 300000 ) } ``` ### Java ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.JAILBREAK_DETECTION, ActionType.CLOSE, 300000 ); }); ``` ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **Close** | Terminate application immediately | Production apps with critical IP | | **Log** | Record incident and continue | Development, analytics | | **Erase** | Securely delete data then terminate | Financial, healthcare apps | | **Custom** | Execute custom handler | Enterprise integrations | | **None** | Detect only, no action | Testing configurations | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. ## When to Use Enable Jailbreak Detection when: - Protecting financial applications and banking systems - Securing healthcare applications storing patient data - Preventing unauthorized access to premium features - Enforcing compliance requirements (PCI DSS, HIPAA, SOC 2) - Protecting cryptocurrency wallets and trading apps - Detecting unauthorized device modifications - Preventing malware execution on compromised devices ## Code Examples ### Kotlin - Basic Integration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class SecurityApplication : Application() { override fun onCreate() { super.onCreate() Monitor.configure { config -> config.addProtection( ProtectionModuleType.JAILBREAK_DETECTION, ActionType.CLOSE, 300000 ) } } } ``` ### Kotlin - Custom Action with Confidence-Based Response ```kotlin Monitor.configure { config -> config.registerCustomAction("jailbreak-handler") { threat -> val threatType = threat.getThreatType() val confidence = threat.getConfidence() val metadata = threat.getMetadata() Log.e("Security", "Jailbreak detected: $threatType (confidence: $confidence)") when { confidence >= 0.9 -> { // High confidence: immediate action Log.e("Security", "High confidence jailbreak. Shutting down.") secureDataAndExit() } confidence >= 0.7 -> { // Medium confidence: restricted mode Log.w("Security", "Medium confidence jailbreak. Enabling restricted mode.") enableRestrictedMode() reportToSecurityBackend(threatType, confidence, metadata) } confidence >= 0.5 -> { // Low confidence: log only Log.i("Security", "Low confidence indicator: $threatType") logSecurityEvent(threatType, confidence, metadata) } } } config.addProtection( ProtectionModuleType.JAILBREAK_DETECTION, "jailbreak-handler", 300000 ) } private fun enableRestrictedMode() { // Disable sensitive features // Disable payment processing // Reduce data access } private fun reportToSecurityBackend(threatType: String, confidence: Double, metadata: Map) { // Send to backend } private fun secureDataAndExit() { // Wipe sensitive data System.exit(1) } private fun logSecurityEvent(threatType: String, confidence: Double, metadata: Map) { // Local logging } ``` ### Java - Multi-Indicator Analysis ```java Monitor.configure(config -> { config.registerCustomAction("multi-indicator-check", threat -> { Map metadata = threat.getMetadata(); // Analyze individual indicators @SuppressWarnings("unchecked") List detectedIndicators = (List) metadata.get("detected_indicators"); int indicatorCount = detectedIndicators != null ? detectedIndicators.size() : 0; double confidence = threat.getConfidence(); Log.e("Security", "Detected " + indicatorCount + " jailbreak indicators"); Log.d("Details", "Indicators: " + detectedIndicators); if (indicatorCount >= 3) { Log.e("Security", "Multiple indicators found. Device is likely compromised."); System.exit(1); } }); config.addProtection( ProtectionModuleType.JAILBREAK_DETECTION, "multi-indicator-check", 300000 ); }); ``` ### Java - Production vs Development Handling ```java Monitor.configure(config -> { config.registerCustomAction("env-aware-handler", threat -> { double confidence = threat.getConfidence(); String threatType = threat.getThreatType(); if (isProduction()) { // Production: zero tolerance if (confidence > 0.5) { Log.e("Security", "Production mode: terminating due to " + threatType); System.exit(1); } } else { // Development: warn only if (confidence > 0.8) { Log.w("Security", "Development mode: jailbreak detected but allowed"); } } }); config.addProtection( ProtectionModuleType.JAILBREAK_DETECTION, "env-aware-handler", 300000 ); }); private static boolean isProduction() { return !BuildConfig.DEBUG; } ``` ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Android 5.0+ | ✓ Fully Supported | API Level 21+ with multi-indicator detection | | Android 8.0+ | ✓ Optimized | Enhanced package enumeration and property access | | Android 12+ | ✓ Optimized | Improved permissions model handling | | iOS | ◐ Planned | Jailbreak detection coming in future release | ## Performance Impact - **CPU Impact**: < 1% increase during detection cycles - **Memory Overhead**: ~300 KB for process and package cache - **Detection Latency**: 100-300 ms per cycle - **Battery Impact**: Minimal (one-time detection with caching until reboot) ## Threat Detection Details When a jailbreak is detected, the module generates a detection result: ```json { "threatType": "rooted_device", "description": "Android device root detected via multiple indicators", "confidence": 0.85, "timestamp": "2026-03-02T16:10:44.521Z", "metadata": { "detectionMethod": "multi_indicator_analysis", "detected_indicators": [ "su_binary_found_system_xbin", "magisk_app_detected", "system_partition_writable", "ro_debuggable_enabled" ], "indicator_count": 4, "su_binary_paths": ["/system/xbin/su"], "root_management_apps": ["com.topjohnwu.magisk"], "debuggable_property": "1", "selinux_status": "enforcing", "api_level": 33, "device_manufacturer": "Samsung" } } ``` ```json { "threatType": "low_confidence_indicator", "description": "Single jailbreak indicator detected", "confidence": 0.52, "timestamp": "2026-03-02T16:10:44.521Z", "metadata": { "detectionMethod": "single_indicator", "detected_indicators": ["busybox_installed"], "indicator_count": 1, "sensitivity_level": "normal" } } ``` ## Related Protections - [Virtual Machine Detection](/platforms/android/products/monitor/protections/virtual-machine-detection) - [Debugger Detection](/platforms/android/products/monitor/protections/debugger-detection) - [Emulator Detection](/platforms/android/products/monitor/protections/emulator-detection) - [Memory Dump Detection](/platforms/android/products/monitor/protections/memory-dump-detection) ## Next Steps - [Configure Protection Actions](/platforms/android/products/monitor/actions) - [Implement Custom Actions](/platforms/android/products/monitor/actions/custom) - [Configuration API Reference](/platforms/android/products/monitor/configuration-api) --- # License Binding Detection **Protection Module:** `LicenseBinding` Validate application deployment across licensed devices and detect unauthorized installations through hardware fingerprinting and installation frequency monitoring. **Available for:** Windows full, Linux partial, macOS partial, Mobile limited --- ## How It Works The License Binding Detection module validates that the application is running on authorized devices by monitoring hardware fingerprints and tracking installation frequency. It detects hardware changes, MAC address modifications, and excessive installations that indicate license violations or unauthorized redistribution. ### Detection Techniques **Hardware Fingerprint Changes:** - CPU cores, primary MAC, BIOS UUID, hostname → SHA-256 hash (0.85 confidence) - Detects hardware changes that indicate device replacement or spoofing **MAC Address Monitoring:** - Tracks all network interface MACs hashed together - Detects removed/added network interfaces (0.7 confidence) - Identifies MAC spoofing attempts **Hostname Changes:** - System hostname monitoring (0.6 confidence) - Detects device rebranding **Installation Frequency Tracking:** - Count over 30-day rolling window - Default limit: 5 installations per month (0.8 confidence) - Prevents license abuse through frequent reinstalls **State Persistence:** - Linux/macOS: ~/.bytehide_license_state - Windows: %LOCALAPPDATA%\.bytehide_license_state - Permanent cache of installation and hardware data Default detection interval: **1 minute** --- ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "LicenseBinding", "action": "erase", "intervalMs": 60000 } ] } ``` ### Kotlin Configuration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.LICENSE_BINDING, ActionType.ERASE, 60000 ) } ``` ### Java Configuration ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.LICENSE_BINDING, ActionType.ERASE, 60000 ); }); ``` ### Custom Action Configuration ```kotlin Monitor.configure { config -> config.registerCustomAction("my-license-action") { threat -> val threatType = threat.getThreatType() // String val description = threat.getDescription() // String val confidence = threat.getConfidence() // Double (0.0-1.0) val metadata = threat.getMetadata() // Map Log.e("License", "Detected: $threatType (Confidence: $confidence)") } config.addProtection( ProtectionModuleType.LICENSE_BINDING, "my-license-action", 60000 ) } ``` --- ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **Close** | Terminate application immediately | Production apps with critical IP | | **Log** | Record incident and continue | Development, analytics | | **Erase** | Securely delete data then terminate | Financial, healthcare apps | | **Custom** | Execute custom handler | Enterprise integrations | | **None** | Detect only, no action | Testing configurations | | **Block** | Block the operation | Not applicable for this module | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. --- ## When to Use Enable License Binding Detection when: - Protecting premium software licenses from unauthorized sharing - Preventing account takeover through device changes - Enforcing device-locked licensing models - Limiting installation frequency to prevent redistribution - Validating hardware consistency for license compliance - Monitoring for enterprise license violations --- ## Code Examples ### Kotlin - Basic Integration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class SecurityManager { fun initializeLicenseBinding() { Monitor.configure { config -> config.addProtection( ProtectionModuleType.LICENSE_BINDING, ActionType.ERASE, 60000 ) } } } ``` ### Kotlin - Hardware and Installation Monitoring ```kotlin Monitor.configure { config -> config.registerCustomAction("monitor-license-binding") { threat -> val threatType = threat.getThreatType() val confidence = threat.getConfidence() val metadata = threat.getMetadata() when (threatType) { "hardware_fingerprint_mismatch" -> { Log.e("License", "Hardware fingerprint changed!") val expectedHash = metadata["expectedFingerprintHash"] as? String val actualHash = metadata["actualFingerprintHash"] as? String Log.d("Hashes", "Expected: $expectedHash, Actual: $actualHash") } "mac_address_changed" -> { Log.w("License", "Network MAC address changed (Confidence: $confidence)") val previousMacs = metadata["previousMacs"] as? String val currentMacs = metadata["currentMacs"] as? String Log.d("MACs", "Previous: $previousMacs, Current: $currentMacs") } "hostname_changed" -> { Log.w("License", "System hostname changed") val previousHostname = metadata["previousHostname"] as? String val currentHostname = metadata["currentHostname"] as? String Log.d("Hostnames", "Previous: $previousHostname, Current: $currentHostname") } "installation_frequency_exceeded" -> { Log.e("License", "Installation frequency limit exceeded!") val installCount = metadata["installCountThisMonth"] as? Number val limit = metadata["monthlyInstallationLimit"] as? Number Log.d("Installs", "Current: $installCount, Limit: $limit") } } } config.addProtection( ProtectionModuleType.LICENSE_BINDING, "monitor-license-binding", 60000 ) } ``` ### Java - Basic Integration ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; public class SecurityManager { public void initializeLicenseBinding() { Monitor.configure(config -> { config.addProtection( ProtectionModuleType.LICENSE_BINDING, ActionType.ERASE, 60000 ); }); } } ``` --- ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Windows 7+ | ✓ Fully Supported | Full hardware fingerprinting and state persistence | | Linux | ◐ Partial | Hardware monitoring with filesystem persistence | | macOS 10.12+ | ◐ Partial | Hardware monitoring with home directory persistence | | Android 5.0+ | ◐ Limited | Basic device identifier tracking | | iOS 12+ | ◐ Limited | IDFA-based tracking only | --- ## Performance Impact - **CPU Impact**: 1-2% increase during detection cycles - **Memory Overhead**: ~400 KB for hardware fingerprint data - **Detection Latency**: 100-200 ms per cycle - **Disk I/O**: Minimal state file updates (< 1 KB) --- ## Threat Detection Details ```json { "detection": { "threatType": "hardware_fingerprint_mismatch", "timestamp": "2026-03-03T18:32:15.654Z", "description": "Device hardware fingerprint changed indicating potential device replacement", "confidence": 0.85, "metadata": { "detectionMethod": "hardware_fingerprint_analysis", "expectedFingerprintHash": "cpu8_mac00aabbccddee_uuid1234_hostpc1", "actualFingerprintHash": "cpu4_mac11223344eeff_uuid5678_hostpc2", "components": { "cpuCoresChanged": true, "macAddressChanged": true, "biosUuidChanged": true, "hostnameChanged": true } } } } ``` ```json { "detection": { "threatType": "mac_address_changed", "timestamp": "2026-03-03T18:33:42.321Z", "description": "Network interface MAC address hash changed", "confidence": 0.7, "metadata": { "detectionMethod": "mac_address_monitoring", "previousMacs": "hashed:a1b2c3d4e5f6", "currentMacs": "hashed:f6e5d4c3b2a1", "macAddressesRemoved": ["00:11:22:33:44:55"], "macAddressesAdded": ["ff:ee:dd:cc:bb:aa"] } } } ``` ```json { "detection": { "threatType": "installation_frequency_exceeded", "timestamp": "2026-03-03T18:34:58.789Z", "description": "Installation frequency limit exceeded in rolling 30-day window", "confidence": 0.8, "metadata": { "detectionMethod": "installation_frequency_tracking", "installCountThisMonth": 7, "monthlyInstallationLimit": 5, "rollingWindowDays": 30, "exceedsLimitBy": 2, "recentInstallations": [ "2026-03-01T10:15:00Z", "2026-03-02T14:20:00Z", "2026-03-02T16:30:00Z", "2026-03-03T09:45:00Z", "2026-03-03T18:34:00Z" ] } } } ``` ```json { "detection": { "threatType": "hostname_changed", "timestamp": "2026-03-03T18:36:10.456Z", "description": "System hostname changed from baseline", "confidence": 0.6, "metadata": { "detectionMethod": "hostname_monitoring", "previousHostname": "workstation-alpha", "currentHostname": "workstation-beta" } } } ``` --- ## Related Protections --- ## Next Steps --- # Memory Dump Detection **Protection Module:** `MemoryDumpDetection` Detect attempts to extract or analyze application memory through specialized dumping tools and suspicious memory access patterns. **Available for:** Desktop full monitoring, Android memory monitoring, iOS memory monitoring --- ## How It Works The Memory Dump Detection module identifies attempts to extract or analyze application memory by detecting popular memory analysis tools and monitoring for suspicious memory patterns. ### Detection Techniques **Desktop Tool Detection (High Confidence):** - Process-based detection: procdump, megadumper, scylla, pe-sieve, hollows_hunter, extremedumper, windbg, cdb, gcore, gdb, lldb (0.95 confidence) - Medium confidence tools: processhacker, procmon, cheat engine (0.75 confidence) - Java/.NET tools: jvisualvm, jconsole, jmap, jhat, dnspy, ilspy (0.85 confidence) **Memory Anomaly Detection:** - Baseline establishment and spike detection (>50% increase in <30 seconds) - Requires 3 or more spikes to confirm threat - Anomaly confidence: 0.7 **Sensitivity Levels:** - Strict: 0.5 (highest sensitivity) - Normal: 0.7 (default) - Lenient: 0.9 (lowest sensitivity) Default detection interval: **15 seconds**, process cache: 30 seconds --- ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "MemoryDumpDetection", "action": "close", "intervalMs": 15000 } ] } ``` ### Kotlin Configuration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.CLOSE, 15000 ) } ``` ### Java Configuration ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.CLOSE, 15000 ); }); ``` ### Custom Action Configuration ```kotlin Monitor.configure { config -> config.registerCustomAction("my-memory-action") { threat -> val threatType = threat.getThreatType() // String val description = threat.getDescription() // String val confidence = threat.getConfidence() // Double (0.0-1.0) val metadata = threat.getMetadata() // Map // Custom handling logic Log.e("Memory", "Detected: $threatType (Confidence: $confidence)") } config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, "my-memory-action", 15000 ) } ``` --- ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **Close** | Terminate application immediately | Production apps with critical IP | | **Log** | Record incident and continue | Development, analytics | | **Erase** | Securely delete data then terminate | Financial, healthcare apps | | **Custom** | Execute custom handler | Enterprise integrations | | **None** | Detect only, no action | Testing configurations | | **Block** | Block the operation | Not applicable for this module | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. --- ## When to Use Enable Memory Dump Detection when: - Protecting cryptographic keys and sensitive data - Defending against specialized memory analysis frameworks - Preventing cheating in gaming applications - Detecting active memory dumping attempts - Protecting against data exfiltration via memory analysis - Ensuring compliance with data protection standards --- ## Code Examples ### Kotlin - Basic Integration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class SecurityManager { fun initializeMemoryProtection() { Monitor.configure { config -> config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.CLOSE, 15000 ) } } } ``` ### Kotlin - Custom Response ```kotlin Monitor.configure { config -> config.registerCustomAction("handle-memory-threat") { threat -> when (threat.getThreatType()) { "procdump" -> Log.e("Security", "Procdump detected!") "megadumper" -> Log.e("Security", "Megadumper detected!") "memory_anomaly" -> { Log.w("Security", "Memory anomaly: ${threat.getDescription()}") Log.d("Confidence", threat.getConfidence().toString()) } else -> Log.e("Security", "Unknown memory threat: ${threat.getThreatType()}") } } config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, "handle-memory-threat", 15000 ) } ``` ### Java - Basic Integration ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; public class SecurityManager { public void initializeMemoryProtection() { Monitor.configure(config -> { config.addProtection( ProtectionModuleType.MEMORY_DUMP_DETECTION, ActionType.CLOSE, 15000 ); }); } } ``` --- ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Android 5.0+ | ✓ Fully Supported | Memory map and process monitoring | | Android 10+ | ✓ Optimized | Enhanced system monitoring | | Desktop Java | ✓ Fully Supported | Process detection and monitoring | | iOS 12+ | ✓ Supported | Memory monitoring only | --- ## Performance Impact - **CPU Impact**: 2-3% increase during detection cycles - **Memory Overhead**: ~800 KB for monitoring structures - **Detection Latency**: 100-200 ms per cycle - **Battery Impact**: Low (frequent monitoring required) --- ## Threat Detection Details ```json { "detection": { "threatType": "procdump", "timestamp": "2026-03-03T14:22:45.320Z", "description": "Memory dump tool process detected", "confidence": 0.95, "metadata": { "toolName": "procdump", "detectionMethod": "process_detection", "processId": 5824, "processPath": "/usr/bin/procdump" } } } ``` ```json { "detection": { "threatType": "memory_anomaly", "timestamp": "2026-03-03T14:23:12.456Z", "description": "Abnormal memory access pattern detected", "confidence": 0.70, "metadata": { "anomalyType": "spike_detection", "memoryIncreasePercent": 62, "timeWindowMs": 28000, "spikeCount": 3, "detectionMethod": "baseline_and_spike_analysis" } } } ``` --- ## Related Protections --- ## Next Steps --- # Network Tampering Detection **Protection Module:** `NetworkTampering` Detect man-in-the-middle attacks, proxy configurations, and network interception attempts. **Available for:** Desktop full, Android partial (proxy, VPN, env vars) --- ## How It Works The Network Tampering Detection module identifies network interception attempts by monitoring system proxy settings, detecting MITM tool processes, analyzing environment variables, and detecting active VPN connections. ### Detection Techniques **System Proxy Detection:** - HTTP proxy: http.proxyHost/Port (0.7 confidence) - HTTPS proxy: https.proxyHost/Port (0.8 confidence) - SOCKS proxy: socksProxyHost/Port (0.6 confidence) **Environment Variable Proxies:** - http_proxy, HTTP_PROXY, https_proxy, HTTPS_PROXY, all_proxy (0.6 confidence) **MITM Tool Process Detection (Desktop):** - Fiddler, Charles, Burp Suite, ZAP, mitmproxy (0.95 confidence) **Network Analyzer Detection:** - Wireshark, tshark, tcpdump (0.7 confidence) **Proxy Tools:** - Proxifier, ProxyCap (0.5 confidence) **Android VPN Detection:** - VPN network interfaces: tun, ppp, pptp, l2tp, ipsec, vpn (0.8 confidence) - NetworkCapabilities.TRANSPORT_VPN API detection (0.8 confidence) Default detection interval: **3 minutes**, process cache: 2 minutes --- ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "NetworkTampering", "action": "block", "intervalMs": 180000 } ] } ``` ### Kotlin Configuration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.NETWORK_TAMPERING, ActionType.BLOCK, 180000 ) } ``` ### Java Configuration ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.NETWORK_TAMPERING, ActionType.BLOCK, 180000 ); }); ``` ### Custom Action Configuration ```kotlin Monitor.configure { config -> config.registerCustomAction("my-network-action") { threat -> val threatType = threat.getThreatType() // String val description = threat.getDescription() // String val confidence = threat.getConfidence() // Double (0.0-1.0) val metadata = threat.getMetadata() // Map Log.e("Network", "Detected: $threatType (Confidence: $confidence)") } config.addProtection( ProtectionModuleType.NETWORK_TAMPERING, "my-network-action", 180000 ) } ``` --- ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **Close** | Terminate application immediately | Production apps with critical IP | | **Log** | Record incident and continue | Development, analytics | | **Erase** | Securely delete data then terminate | Financial, healthcare apps | | **Custom** | Execute custom handler | Enterprise integrations | | **None** | Detect only, no action | Testing configurations | | **Block** | Block network operations | Cloud protection modules | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. --- ## When to Use Enable Network Tampering Detection when: - Protecting financial transactions and banking operations - Securing API communications with sensitive data - Preventing credential interception attacks - Monitoring for network-based fraud attempts - Detecting unauthorized network monitoring - Preventing man-in-the-middle attacks --- ## Code Examples ### Kotlin - Basic Integration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class SecurityManager { fun initializeNetworkProtection() { Monitor.configure { config -> config.addProtection( ProtectionModuleType.NETWORK_TAMPERING, ActionType.BLOCK, 180000 ) } } } ``` ### Kotlin - Custom Handler with Detection Types ```kotlin Monitor.configure { config -> config.registerCustomAction("handle-network-tampering") { threat -> val threatType = threat.getThreatType() val confidence = threat.getConfidence() val metadata = threat.getMetadata() when (threatType) { "system_proxy_detected" -> { val proxyHost = metadata["proxyHost"] as? String val proxyPort = metadata["proxyPort"] as? String Log.e("Security", "System proxy detected: $proxyHost:$proxyPort") } "environment_proxy_detected" -> { val proxyVar = metadata["proxyVariable"] as? String Log.e("Security", "Environment proxy detected: $proxyVar") } "mitm_tool_detected" -> { val toolName = metadata["toolName"] as? String Log.e("Security", "MITM tool process detected: $toolName") } "network_analyzer_detected" -> { val analyzerName = metadata["analyzerName"] as? String Log.w("Security", "Network analyzer detected: $analyzerName") } "vpn_detected" -> { val vpnInterface = metadata["vpnInterface"] as? String Log.w("Security", "VPN connection detected: $vpnInterface (Confidence: $confidence)") } } } config.addProtection( ProtectionModuleType.NETWORK_TAMPERING, "handle-network-tampering", 180000 ) } ``` ### Java - Basic Integration ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; public class SecurityManager { public void initializeNetworkProtection() { Monitor.configure(config -> { config.addProtection( ProtectionModuleType.NETWORK_TAMPERING, ActionType.BLOCK, 180000 ); }); } } ``` --- ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Android 5.0+ | ✓ Fully Supported | Proxy and environment variable monitoring | | Android 7+ | ✓ Optimized | Network capabilities API | | Android 10+ | ✓ Enhanced | Granular VPN detection | | Desktop Java | ✓ Fully Supported | System proxy and process detection | | iOS 12+ | ◐ Partial | VPN detection only | --- ## Performance Impact - **CPU Impact**: 1-2% increase during detection cycles - **Memory Overhead**: ~300 KB for proxy configuration cache - **Detection Latency**: 100-200 ms per cycle - **Battery Impact**: Minimal (3-minute intervals) --- ## Threat Detection Details ```json { "detection": { "threatType": "system_proxy_detected", "timestamp": "2026-03-03T17:15:22.654Z", "description": "System proxy configuration detected", "confidence": 0.8, "metadata": { "detectionMethod": "system_proxy_monitoring", "proxyHost": "192.168.1.100", "proxyPort": 8080, "proxyProtocol": "http" } } } ``` ```json { "detection": { "threatType": "mitm_tool_detected", "timestamp": "2026-03-03T17:16:45.321Z", "description": "MITM tool process detected running on system", "confidence": 0.95, "metadata": { "detectionMethod": "process_detection", "toolName": "Burp Suite", "processId": 3456, "processPath": "/opt/burp/burp" } } } ``` ```json { "detection": { "threatType": "vpn_detected", "timestamp": "2026-03-03T17:17:58.789Z", "description": "Active VPN connection detected on device", "confidence": 0.8, "metadata": { "detectionMethod": "network_interface_analysis", "vpnInterface": "tun0", "vpnType": "generic_vpn", "transportMethod": "TRANSPORT_VPN" } } } ``` ```json { "detection": { "threatType": "environment_proxy_detected", "timestamp": "2026-03-03T17:19:10.456Z", "description": "Environment variable proxy configuration detected", "confidence": 0.6, "metadata": { "detectionMethod": "environment_variable_monitoring", "proxyVariable": "HTTP_PROXY", "proxyValue": "http://proxy.internal:3128" } } } ``` --- ## Related Protections --- ## Next Steps --- # Process Injection Detection **Protection Module:** `ProcessInjection` Detect process injection frameworks and tools that attempt to modify application behavior at runtime. **Available for:** Android full (Frida, Xposed, Substrate), Desktop partial (process detection) --- ## How It Works The Process Injection Detection module identifies instrumentation frameworks and injection tools that attempt to modify application behavior at runtime through code hooking and patching. ### Detection Techniques **Android Frida Detection:** - File-based detection: /data/local/tmp/re.frida.server, frida-agent*.so, frida-gadget*.so (0.8 confidence) - Port scanning: port 27042 (0.7 confidence) - Library detection: libfrida-gadget.so (0.95 confidence) **Android Xposed Detection:** - Class detection: de.robv.android.xposed.XposedBridge (0.95 confidence) - File-based: /system/framework/XposedBridge.jar (0.85 confidence) - Package detection: de.robv.android.xposed.installer, edxposed.manager (0.8 confidence) **Android Cydia Substrate Detection:** - Library detection: /system/lib/libsubstrate.so (0.8 confidence) **Desktop Tool Detection:** - Frida process detection (0.9 confidence) - Xenos, extremeinjector, dllinjector, ghinjector, cheatengine (0.9 confidence) **Sensitivity Levels:** - Strict: 0.5 (highest sensitivity) - Normal: 0.7 (default) - Lenient: 0.9 (lowest sensitivity) Default detection interval: **30 seconds** --- ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "ProcessInjection", "action": "close", "intervalMs": 30000 } ] } ``` ### Kotlin Configuration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.PROCESS_INJECTION, ActionType.CLOSE, 30000 ) } ``` ### Java Configuration ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.PROCESS_INJECTION, ActionType.CLOSE, 30000 ); }); ``` ### Custom Action Configuration ```kotlin Monitor.configure { config -> config.registerCustomAction("my-injection-action") { threat -> val threatType = threat.getThreatType() // String val description = threat.getDescription() // String val confidence = threat.getConfidence() // Double (0.0-1.0) val metadata = threat.getMetadata() // Map Log.e("Injection", "Detected: $threatType (Confidence: $confidence)") } config.addProtection( ProtectionModuleType.PROCESS_INJECTION, "my-injection-action", 30000 ) } ``` --- ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **Close** | Terminate application immediately | Production apps with critical IP | | **Log** | Record incident and continue | Development, analytics | | **Erase** | Securely delete data then terminate | Financial, healthcare apps | | **Custom** | Execute custom handler | Enterprise integrations | | **None** | Detect only, no action | Testing configurations | | **Block** | Block the operation | Not applicable for this module | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. --- ## When to Use Enable Process Injection Detection when: - Protecting against runtime code hooking and patching - Detecting instrumentation frameworks like Frida and Xposed - Preventing function interception and behavior modification - Defending against advanced reverse engineering attempts - Protecting sensitive operations from runtime modification - Ensuring code execution integrity --- ## Code Examples ### Kotlin - Basic Integration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class SecurityManager { fun initializeInjectionProtection() { Monitor.configure { config -> config.addProtection( ProtectionModuleType.PROCESS_INJECTION, ActionType.CLOSE, 30000 ) } } } ``` ### Kotlin - Detailed Framework Detection ```kotlin Monitor.configure { config -> config.registerCustomAction("detect-injection-framework") { threat -> val threatType = threat.getThreatType() val confidence = threat.getConfidence() val metadata = threat.getMetadata() when (threatType) { "frida" -> { Log.e("Security", "Frida framework detected!") val libraryPath = metadata["libraryPath"] as? String val detectionMethod = metadata["detectionMethod"] as? String Log.d("Details", "Library: $libraryPath, Method: $detectionMethod") } "xposed" -> { Log.e("Security", "Xposed framework detected!") val className = metadata["className"] as? String Log.d("Details", "Class: $className") } "cydia_substrate" -> { Log.e("Security", "Cydia Substrate detected!") val libraryPath = metadata["libraryPath"] as? String Log.d("Details", "Library: $libraryPath") } "xenos" -> { Log.e("Security", "Xenos injector detected!") } "cheatengine" -> { Log.w("Security", "CheatEngine detected (Confidence: $confidence)") } } } config.addProtection( ProtectionModuleType.PROCESS_INJECTION, "detect-injection-framework", 30000 ) } ``` ### Java - Basic Integration ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; public class SecurityManager { public void initializeInjectionProtection() { Monitor.configure(config -> { config.addProtection( ProtectionModuleType.PROCESS_INJECTION, ActionType.CLOSE, 30000 ); }); } } ``` --- ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Android 5.0+ | ✓ Fully Supported | Frida, Xposed, Substrate detection | | Android 9+ | ✓ Optimized | Enhanced library scanning | | Android 12+ | ✓ Optimized | Improved sandbox detection | | Desktop Java | ◐ Partial | Process injection detection only | | Linux | ◐ Partial | Process-based detection | --- ## Performance Impact - **CPU Impact**: 2-3% increase during detection cycles - **Memory Overhead**: ~600 KB for framework signatures - **Detection Latency**: 80-150 ms per cycle - **Battery Impact**: Low to moderate (frequent library scanning) --- ## Threat Detection Details ```json { "detection": { "threatType": "frida", "timestamp": "2026-03-03T16:05:18.523Z", "description": "Frida instrumentation framework detected", "confidence": 0.95, "metadata": { "detectionMethod": "library_detection", "libraryPath": "/data/local/tmp/libfrida-gadget.so", "frameworkName": "Frida", "serverPort": 27042, "injectionMethod": "gadget" } } } ``` ```json { "detection": { "threatType": "xposed", "timestamp": "2026-03-03T16:06:42.187Z", "description": "Xposed framework detected via class inspection", "confidence": 0.95, "metadata": { "detectionMethod": "class_detection", "className": "de.robv.android.xposed.XposedBridge", "frameworkName": "Xposed", "installerPackage": "de.robv.android.xposed.installer" } } } ``` ```json { "detection": { "threatType": "cydia_substrate", "timestamp": "2026-03-03T16:07:55.412Z", "description": "Cydia Substrate injection detected", "confidence": 0.8, "metadata": { "detectionMethod": "library_detection", "libraryPath": "/system/lib/libsubstrate.so", "frameworkName": "Cydia Substrate" } } } ``` --- ## Related Protections --- ## Next Steps --- # Remote Desktop Detection **Protection Module:** `RemoteDesktop` Detects remote access sessions, screen sharing applications, and unauthorized remote control attempts including TeamViewer, AnyDesk, VNC, and Chrome Remote Desktop. **Available for:** Windows (full), Linux (partial), macOS (partial), Mobile (N/A) --- ## How It Works The Remote Desktop Detection module identifies unauthorized remote access and screen sharing by monitoring for remote access applications, detecting process execution patterns, and analyzing environment variables. This prevents compromised accounts from being remotely controlled by attackers. ### Detection Techniques - **RDP Session Detection** (Windows): SESSIONNAME environment variable starting with "RDP-" (confidence: 0.95) - **Remote Access App Detection**: Identifies TeamViewer, AnyDesk, Parsec, NoMachine, Splashtop processes (confidence: 0.9) - **VNC Server Detection**: Detects TightVNC, RealVNC, UltraVNC, TigerVNC, x11vnc processes (confidence: 0.7) - **Chrome Remote Desktop Detection**: Identifies remoting_host, chrome_remote_desktop_host processes (confidence: 0.7) - **Native Remote Desktop Tools**: Detects mstsc, rdpclip (Windows), screensharingd (macOS), remmina (Linux) (confidence: 0.9) - **X11 Forwarding Detection** (Linux): DISPLAY environment variable combined with SSH_CONNECTION or SSH_CLIENT (confidence: 0.8) - **Process Runtime Monitoring**: Tracks active remote access processes and network connections Detection confidence: **0.7-0.95** (varies by method) | Default interval: **2 minutes** (process cache 2 minutes) ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "RemoteDesktop", "action": "log", "intervalMs": 120000 } ] } ``` ### Kotlin Code-Based ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.REMOTE_DESKTOP, ActionType.LOG, 120000 ) } ``` ### Java Code-Based ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.REMOTE_DESKTOP, ActionType.LOG, 120000 ); }); ``` ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **close** | Terminate application immediately | Production apps with critical IP | | **log** | Record incident and continue | Development, analytics | | **erase** | Securely delete data then terminate | Financial, healthcare apps | | **custom** | Execute custom handler | Enterprise integrations | | **none** | Detect only, no action | Testing configurations | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. ## When to Use Enable Remote Desktop Detection when: - Protecting financial accounts from remote takeover - Securing enterprise applications and data access - Preventing credential harvesting via screen sharing - Detecting device compromise through remote access - Protecting against account takeover attacks - Monitoring for unauthorized administrative access ## Code Examples ### Kotlin - Basic Integration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Monitor.configure { config -> config.addProtection( ProtectionModuleType.REMOTE_DESKTOP, ActionType.LOG, 120000 ) } setContentView(R.layout.activity_main) } } ``` ### Kotlin - Custom Action with Threat Details ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.registerCustomAction("handle-remote-desktop") { threat -> val threatType = threat.getThreatType() val description = threat.getDescription() val confidence = threat.getConfidence() val metadata = threat.getMetadata() Log.e("Security", "Remote access detected: $threatType (confidence: $confidence)") Log.e("Security", "Description: $description") when (threatType) { "TeamViewer" -> { Log.e("Security", "TeamViewer process active") disableSensitiveFeatures() } "AnyDesk" -> { Log.e("Security", "AnyDesk process active") disableSensitiveFeatures() } "RDP" -> { Log.e("Security", "RDP session detected") disableSensitiveFeatures() } } } config.addProtection( ProtectionModuleType.REMOTE_DESKTOP, "handle-remote-desktop", 120000 ) } private fun disableSensitiveFeatures() { // Disable payment processing, sensitive data display, etc. } ``` ### Java - Close Action (Production Security) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.REMOTE_DESKTOP, ActionType.CLOSE, 120000 ); }); ``` ### Java - Erase Action (Financial Apps) ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.REMOTE_DESKTOP, ActionType.ERASE, 120000 ); }); ``` ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Windows 7+ | ✓ Fully Supported | RDP session detection, process analysis | | Windows 10+ | ✓ Optimized | Enhanced RDP and process monitoring | | Linux | ✓ Partial | VNC detection, X11 forwarding, process-based | | macOS | ✓ Partial | VNC detection, Screen Sharing, process-based | | Mobile (Android) | ✗ N/A | Not applicable on mobile platforms | | TeamViewer | ✓ Detected | All versions | | AnyDesk | ✓ Detected | All versions | | Parsec | ✓ Detected | Cloud gaming remote desktop | | Chrome Remote Desktop | ✓ Detected | Process and service detection | | VNC Variants | ✓ Detected | TightVNC, RealVNC, UltraVNC, TigerVNC, x11vnc | ## Performance Impact - **CPU Impact**: 1-2% during detection cycles - **Memory Overhead**: ~350 KB for process metadata caching - **Detection Latency**: 150-300 ms per cycle - **Battery Impact**: Minimal (frequent but lightweight checks) - **Network Impact**: None (local process and environment analysis) ## Threat Detection Details ```json { "detection": { "threatType": "TeamViewer", "timestamp": "2026-03-03T14:30:45.309Z", "description": "Remote access application detected and running with active network connection", "confidence": 0.9, "metadata": { "detectionMethod": "process_analysis", "processName": "TeamViewer.exe", "packageName": "com.teamviewer.teamviewer.market.mobile", "appName": "TeamViewer", "version": "15.44.23", "isRunning": true, "hasNetworkConnection": true, "firstSeen": "2026-03-01T10:30:00.000Z" } } } ``` RDP session detection example: ```json { "detection": { "threatType": "RDP", "timestamp": "2026-03-03T14:30:45.309Z", "description": "Remote Desktop Protocol session active via RDP environment variable", "confidence": 0.95, "metadata": { "detectionMethod": "rdp_environment_variable", "sessionName": "RDP-Tcp#1", "isRemoteSession": true, "sessionType": "RDP-Tcp", "detectionSource": "SESSIONNAME" } } } ``` X11 Forwarding detection example (Linux): ```json { "detection": { "threatType": "X11Forwarding", "timestamp": "2026-03-03T14:30:45.309Z", "description": "X11 forwarding detected via SSH connection with DISPLAY variable", "confidence": 0.8, "metadata": { "detectionMethod": "x11_ssh_forwarding", "displayVariable": ":10.0", "sshConnection": "192.168.1.100:22", "sshClient": "ssh", "isForwarded": true } } } ``` ## Related Protections ## Next Steps --- # Tampering Detection **Protection Module:** `TamperingDetection` Verify application integrity through APK signature validation and cryptographic license binding verification. **Available for:** Android only (requires Context). NOT available on Desktop/Server. --- ## How It Works The Tampering Detection module verifies the integrity of the application package through cryptographic validation. It extracts the expected APK signature hash from your ByteHide JWT license, calculates the current APK signature hash at runtime via reflection, and compares the SHA-256 hashes to detect modifications. ### Detection Techniques **APK Signature Verification:** - Extracts expected signature hash from ByteHide JWT license token - Calculates current APK signature hash via reflection - Uses Android PackageManager.getPackageInfo() with GET_SIGNATURES flag - Compares SHA-256 of certificate public key - Signature hash is cryptographically signed in RS256 JWT **Detection Confidence:** - Signature mismatch: 1.0 (certain) - Signature extraction failure: 0.8 - Verification failure: 0.7 **License Binding:** - Signature hash embedded in RS256 JWT token - Cryptographic validation ensures authenticity Default detection interval: **5 minutes**, cached permanently --- ## Configuration ### JSON Configuration ```json { "protections": [ { "type": "TamperingDetection", "action": "close", "intervalMs": 300000 } ] } ``` ### Kotlin Configuration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.TAMPERING_DETECTION, ActionType.CLOSE, 300000 ) } ``` ### Java Configuration ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.TAMPERING_DETECTION, ActionType.CLOSE, 300000 ); }); ``` ### Custom Action Configuration ```kotlin Monitor.configure { config -> config.registerCustomAction("my-tampering-action") { threat -> val threatType = threat.getThreatType() // String val description = threat.getDescription() // String val confidence = threat.getConfidence() // Double (0.0-1.0) val metadata = threat.getMetadata() // Map Log.e("Tampering", "Detected: $threatType (Confidence: $confidence)") } config.addProtection( ProtectionModuleType.TAMPERING_DETECTION, "my-tampering-action", 300000 ) } ``` --- ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **Close** | Terminate application immediately | Production apps with critical IP | | **Log** | Record incident and continue | Development, analytics | | **Erase** | Securely delete data then terminate | Financial, healthcare apps | | **Custom** | Execute custom handler | Enterprise integrations | | **None** | Detect only, no action | Testing configurations | | **Block** | Block the operation | Not applicable for this module | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. --- ## When to Use Enable Tampering Detection when: - Protecting against code injection and patching attacks - Preventing unauthorized modifications to APK or native libraries - Detecting modified or cracked app installations - Ensuring code integrity for compliance requirements - Protecting intellectual property from reverse engineering - Preventing exploitation via code modification --- ## Code Examples ### Kotlin - Basic Integration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class SecurityManager { fun initializeTamperingProtection() { Monitor.configure { config -> config.addProtection( ProtectionModuleType.TAMPERING_DETECTION, ActionType.CLOSE, 300000 ) } } } ``` ### Kotlin - Custom Response Handler ```kotlin Monitor.configure { config -> config.registerCustomAction("handle-tampering") { threat -> val threatType = threat.getThreatType() val confidence = threat.getConfidence() val metadata = threat.getMetadata() when (threatType) { "signature_mismatch" -> { Log.e("Security", "APK signature mismatch detected!") val expectedHash = metadata["expectedSignatureHash"] as? String val actualHash = metadata["actualSignatureHash"] as? String Log.d("Hashes", "Expected: $expectedHash, Actual: $actualHash") } "signature_extraction_failure" -> { Log.w("Security", "Failed to extract signature: $confidence confidence") } "verification_failure" -> { Log.w("Security", "Verification failed: $confidence confidence") } } } config.addProtection( ProtectionModuleType.TAMPERING_DETECTION, "handle-tampering", 300000 ) } ``` ### Java - Basic Integration ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; public class SecurityManager { public void initializeTamperingProtection() { Monitor.configure(config -> { config.addProtection( ProtectionModuleType.TAMPERING_DETECTION, ActionType.CLOSE, 300000 ); }); } } ``` --- ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Android 5.0+ | ✓ Fully Supported | APK signature verification via PackageManager | | Android 11+ | ✓ Optimized | Enhanced reflection for signature extraction | | Google Play | ✓ Recommended | Compatible with Play Integrity API | | Side-loaded Apps | ✓ Protected | Works with manually installed APKs | --- ## Performance Impact - **CPU Impact**: 1-2% increase during detection cycles - **Memory Overhead**: ~200 KB for hash cache - **Detection Latency**: 50-150 ms per cycle - **Battery Impact**: Minimal (5-minute intervals with caching) --- ## Threat Detection Details ```json { "detection": { "threatType": "signature_mismatch", "timestamp": "2026-03-03T15:10:22.987Z", "description": "APK signature hash mismatch with license binding", "confidence": 1.0, "metadata": { "detectionMethod": "apk_signature_verification", "expectedSignatureHash": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6", "actualSignatureHash": "z9y8x7w6v5u4t3s2r1q0p9o8n7m6l5k4", "certificateStatus": "valid", "jwtTokenStatus": "verified", "licenseBindingValid": false } } } ``` ```json { "detection": { "threatType": "signature_extraction_failure", "timestamp": "2026-03-03T15:11:45.654Z", "description": "Unable to extract APK signature for verification", "confidence": 0.8, "metadata": { "detectionMethod": "reflection_based_extraction", "failureReason": "PackageManager unavailable", "fallbackVerification": "pending" } } } ``` --- ## Related Protections --- ## Next Steps --- # Virtual Machine Detection **Protection Module:** `VirtualMachineDetection` ## Available For Android (Emulator detection) Desktop (VM/Container detection) ## How It Works The Virtual Machine Detection module identifies when an application is running within virtualized or emulated environments. It uses platform-specific detection techniques to identify common hypervisors, Android emulators, and container runtimes through hardware signatures, system properties, and process enumeration. ### Detection Techniques **Desktop Virtual Machines:** - **VM Driver Files**: Checks for driver files like `/sys/devices/virtual/dmi/id/` (Linux), checking for `vmware.sys`, `vboxguest.sys` (Windows) - **DMI Identification**: Reads `/sys/class/dmi/id/*` files for manufacturer, product name, and system info - **CPU Hypervisor Flag**: Scans `/proc/cpuinfo` for hypervisor detection bit - **Systemd Detection**: Runs `systemd-detect-virt` to identify virtualization type - **VM Process Detection**: Enumerates processes for common VM management tools - **Detects**: VMware, VirtualBox, Hyper-V, Parallels, QEMU, KVM, Xen, Docker, LXC, Kubernetes **Android Emulator Detection:** - **System Properties**: Checks `ro.kernel.qemu=1`, `ro.hardware=goldfish/ranchu` - **Build Properties**: Analyzes `Build.HARDWARE`, `Build.PRODUCT`, `Build.MODEL`, `Build.FINGERPRINT` for emulator signatures - **QEMU Sockets**: Checks for `/dev/socket/qemud` - **Genymotion Detection**: Identifies Genymotion-specific properties and binaries - **Detects**: Goldfish, Ranchu, Genymotion, and other Android emulators **Dynamic Sensitivity Levels:** - `strict` (confidence: 0.5): One indicator triggers detection - `normal` (confidence: 0.7): Multiple indicators required - `lenient` (confidence: 0.9): High confidence threshold Default detection interval: **5 minutes** Caching: Results cached permanently ## JSON Configuration ```json { "protections": [ { "type": "VirtualMachineDetection", "action": "close", "intervalMs": 300000 } ] } ``` ## Code-Based Configuration ### Kotlin ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType Monitor.configure { config -> config.addProtection( ProtectionModuleType.VIRTUAL_MACHINE_DETECTION, ActionType.CLOSE, 300000 ) } ``` ### Java ```java import com.bytehide.monitor.Monitor; import com.bytehide.monitor.core.action.ActionType; import com.bytehide.monitor.core.protection.ProtectionModuleType; Monitor.configure(config -> { config.addProtection( ProtectionModuleType.VIRTUAL_MACHINE_DETECTION, ActionType.CLOSE, 300000 ); }); ``` ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **Close** | Terminate application immediately | Production apps with critical IP | | **Log** | Record incident and continue | Development, analytics | | **Erase** | Securely delete data then terminate | Financial, healthcare apps | | **Custom** | Execute custom handler | Enterprise integrations | | **None** | Detect only, no action | Testing configurations | | **Block** | Block the operation (cloud modules) | Cloud protection modules | See [Actions](/platforms/android/products/monitor/actions) for detailed action documentation. ## When to Use Enable Virtual Machine Detection when: - Protecting against automated testing and analysis - Preventing app testing in uncontrolled lab environments - Restricting access to premium features in non-production environments - Detecting security research and reverse engineering attempts - Preventing malware testing in isolated environments - Enforcing real-device or native execution for sensitive operations - Protecting cryptocurrency trading apps and financial software ## Code Examples ### Kotlin - Basic Integration ```kotlin import com.bytehide.monitor.Monitor import com.bytehide.monitor.core.action.ActionType import com.bytehide.monitor.core.protection.ProtectionModuleType class SecurityApplication : Application() { override fun onCreate() { super.onCreate() Monitor.configure { config -> config.addProtection( ProtectionModuleType.VIRTUAL_MACHINE_DETECTION, ActionType.CLOSE, 300000 ) } } } ``` ### Kotlin - Custom Action with VM Type Handling ```kotlin Monitor.configure { config -> config.registerCustomAction("vm-detector") { threat -> val threatType = threat.getThreatType() val confidence = threat.getConfidence() val metadata = threat.getMetadata() Log.e("Security", "VM/Emulator detected: $threatType (confidence: $confidence)") when (threatType) { "android_emulator" -> handleAndroidEmulator(metadata) "vmware" -> handleVMware(metadata) "virtualbox" -> handleVirtualBox(metadata) "docker" -> handleDocker(metadata) else -> handleUnknownVM(threatType, metadata) } } config.addProtection( ProtectionModuleType.VIRTUAL_MACHINE_DETECTION, "vm-detector", 300000 ) } private fun handleAndroidEmulator(metadata: Map) { Log.w("Security", "Android emulator: ${metadata["emulator_type"]}") disableInAppPurchases() } private fun handleVMware(metadata: Map) { Log.w("Security", "VMware detected via ${metadata["detection_method"]}") System.exit(1) } private fun handleVirtualBox(metadata: Map) { Log.w("Security", "VirtualBox detected. Exiting.") System.exit(1) } private fun handleDocker(metadata: Map) { Log.w("Security", "Docker container detected.") System.exit(1) } private fun handleUnknownVM(threatType: String, metadata: Map) { Log.e("Security", "Unknown VM environment: $threatType") System.exit(1) } private fun disableInAppPurchases() { // Disable monetization } ``` ### Java - Emulator-Specific Handling ```java Monitor.configure(config -> { config.registerCustomAction("emulator-check", threat -> { Map metadata = threat.getMetadata(); String threatType = threat.getThreatType(); if (threatType.contains("emulator")) { @SuppressWarnings("unchecked") Map buildProps = (Map) metadata.get("build_properties"); Log.e("Security", "Emulator detected"); Log.d("Details", "Model: " + buildProps.get("model")); Log.d("Details", "Fingerprint: " + buildProps.get("fingerprint")); disableSecurityFeatures(); } }); config.addProtection( ProtectionModuleType.VIRTUAL_MACHINE_DETECTION, "emulator-check", 300000 ); }); private static void disableSecurityFeatures() { // Reduce features for emulated environment } ``` ### Java - Conditional Based on Environment ```java Monitor.configure(config -> { config.registerCustomAction("env-check", threat -> { double confidence = threat.getConfidence(); // Only block high-confidence detections if (confidence > 0.8) { Log.e("Security", "High-confidence VM/Emulator: " + threat.getThreatType()); System.exit(1); } else if (confidence > 0.6) { Log.w("Security", "Possible VM/Emulator environment"); // Restrict features } }); config.addProtection( ProtectionModuleType.VIRTUAL_MACHINE_DETECTION, "env-check", 300000 ); }); ``` ## Platform Compatibility | Platform | Status | Notes | |----------|--------|-------| | Android 5.0+ | ✓ Fully Supported | Android emulator detection via properties | | Android 10+ | ✓ Optimized | Enhanced QEMU and Genymotion detection | | Linux | ✓ Fully Supported | VM driver, DMI, and systemd-detect-virt | | macOS | ✓ Fully Supported | Hypervisor framework detection | | Windows | ✓ Fully Supported | WMI and driver detection | | Docker | ✓ Detected | cgroup and namespace detection | | Kubernetes | ◐ Supported | Container environment detection | ## Performance Impact - **CPU Impact**: < 1% increase during detection cycles - **Memory Overhead**: ~250 KB for property cache - **Detection Latency**: 100-250 ms per cycle - **Battery Impact**: Minimal (one-time detection with caching) ## Threat Detection Details Android Emulator Detection: ```json { "threatType": "android_emulator", "description": "Android emulator detected via system properties", "confidence": 0.95, "timestamp": "2026-03-02T15:20:33.847Z", "metadata": { "detectionMethod": "system_property_analysis", "emulator_type": "goldfish", "ro_kernel_qemu": "1", "ro_hardware": "goldfish", "build_fingerprint": "google/sdk_google_phone_x86/generic_x86:14/UPB1.231015.013", "build_model": "sdk_google_phone_x86", "api_level": 34, "qemud_socket_found": true } } ``` Desktop VM Detection: ```json { "threatType": "vmware", "description": "VMware hypervisor detected via system properties and device drivers", "confidence": 0.92, "timestamp": "2026-03-02T15:20:33.847Z", "metadata": { "detectionMethod": "dmi_and_driver_analysis", "hypervisor_type": "VMware", "dmi_manufacturer": "VMware, Inc.", "dmi_product_name": "VMware Virtual Platform", "driver_files": ["/sys/devices/virtual/dmi/id/"], "platform": "Linux", "cpu_hypervisor_flag_detected": true } } ``` ## Related Protections - [Emulator Detection](/platforms/android/products/monitor/protections/emulator-detection) - [Jailbreak Detection](/platforms/android/products/monitor/protections/jailbreak-detection) - [Debugger Detection](/platforms/android/products/monitor/protections/debugger-detection) - [Memory Dump Detection](/platforms/android/products/monitor/protections/memory-dump-detection) ## Next Steps - [Configure Protection Actions](/platforms/android/products/monitor/actions) - [Implement Custom Actions](/platforms/android/products/monitor/actions/custom) - [Configuration API Reference](/platforms/android/products/monitor/configuration-api) --- # Quick Start - Monitor for Android Get ByteHide Monitor protecting your Android application in under 5 minutes using the Gradle plugin. No code changes required for basic protection. {% .lead %} --- ## Prerequisites - Android Studio with Gradle support (AGP 7.0+ or 8.0+) - Java 11 or higher - A ByteHide account with a Monitor project ([create one here](/platforms/android/products/monitor/cloud-panel/creating-project)) - Your **ByteHide Project Token** from [app.bytehide.com](https://app.bytehide.com) --- ## Step 1: Configure Repositories Add Maven Central to your `settings.gradle.kts`: ```kotlin // settings.gradle.kts pluginManagement { repositories { mavenCentral() gradlePluginPortal() google() } } dependencyResolutionManagement { repositories { mavenCentral() google() } } ``` --- ## Step 2: Apply the Plugin Add the Monitor plugin to your app module's `build.gradle.kts`: ```kotlin // app/build.gradle.kts plugins { id("com.android.application") id("com.bytehide.monitor") version "1.0.1" } ``` The plugin automatically adds the Monitor runtime library. No separate dependency needed. --- ## Step 3: Configure Add the `monitor` block with your token and the `mobile` preset: ```kotlin monitor { projectToken = "bh_xxxxxxxxxxxx" preset = "mobile" } ``` ![Monitor Gradle plugin configuration in Android Studio](/images/monitor/android/bytehide-monitor-android-gradle-config.png) The `mobile` preset enables Debugger Detection, Clock Tampering, and Jailbreak Detection. A safe baseline for most Android applications. See [Gradle Setup](/platforms/android/products/monitor/installation/gradle-setup#presets) for all available presets. > **No code changes required** > The plugin generates a `ContentProvider` that auto-initializes Monitor when the app starts. All configuration is embedded at build time. You only need code if you want custom action handlers or runtime overrides. --- ## Step 4: Build ```bash ./gradlew assembleDebug ``` You'll see Monitor configuring in the build output: ``` Configuring ByteHide Monitor... API Token: bh_POlhU6... Package: com.example.myapp Generating MonitorContentProvider... Registering provider in AndroidManifest.xml... Embedding encrypted resources... ByteHide Monitor configured successfully ``` --- ## Step 5: Verify Run the app and filter Logcat by tag `ByteHideMonitor`: ``` I/ByteHideMonitor: [I001_INIT_START] MonitorLogger initialized with 2 sinks I/ByteHideMonitor: [I002_INIT_SUCCESS] ByteHideMonitor initialization complete I/ByteHideMonitor: [I010_API_CONNECTED] Registering device... ``` Detected threats also appear in the [ByteHide Dashboard](https://app.bytehide.com). --- ## What Happens at Runtime 1. The plugin signs the assembly and embeds encrypted configuration into the APK at build time 2. At app launch, the generated `ContentProvider` initializes Monitor automatically 3. Monitor verifies the assembly signature to ensure the APK has not been tampered with 4. Configured protection modules start running 5. Threats are logged locally and reported to the ByteHide Dashboard --- ## Next Steps - [Gradle Setup - Full reference](/platforms/android/products/monitor/installation/gradle-setup) - All DSL options, protection modules, and presets - [Configuration API](/platforms/android/products/monitor/configuration-api) - Add custom actions and runtime overrides - [Protection Modules](/platforms/android/products/monitor/protection-modules) - All 13 available protection modules - [CI/CD Integration](/platforms/android/products/monitor/installation/cicd) - Pipeline setup --- # Runtime Correlation with Radar (SAST) Monitor feeds runtime exploit data back to Radar, turning static analysis findings from theoretical risk into actionable intelligence. Vulnerabilities confirmed as actively exploited get escalated. Vulnerabilities confirmed as unreachable get deprioritized. {% .lead %} --- ## The Problem with Static Findings Alone Static analysis (SAST) scans your source code and identifies potential vulnerabilities. This is essential work. But a report with 200 findings does not tell you which ones are actually being exploited right now in production. Without runtime context, security teams are forced to prioritize by CVSS score and guesswork. A medium-severity SQL injection on line 847 might be the most critical finding in your codebase if attackers are actively targeting it. Or it might be buried in a code path no request ever reaches. The gap between "this code is vulnerable" and "this vulnerability is being exploited" is where Monitor and Radar connect. --- ## How It Works When both Monitor and Radar are active on the same project, they share data bidirectionally through the ByteHide platform. ### Escalation: Theoretical to Actively Exploited 1. Radar flags a vulnerability in your codebase (for example, a SQL injection in an API endpoint) 2. Radar assigns it a severity based on static analysis: medium 3. Monitor detects a SQL injection attempt targeting that same endpoint in production 4. Monitor reports the incident with full context: payload, source IP, method, confidence score 5. Radar receives the runtime signal and reprioritizes the finding to **critical**, because it is no longer theoretical The vulnerability now shows a **"Runtime Confirmed"** indicator in the Radar dashboard, with a direct link to the Monitor incident that validated it. ### De-escalation: Flagged but Unreachable The loop works in the other direction too: 1. Radar flags a vulnerability in an endpoint 2. Monitor has runtime visibility into how that endpoint is accessed 3. Monitor confirms the endpoint is internal, behind authentication, or unreachable from the outside 4. Radar receives the runtime context and adjusts the priority downward Your team stops spending time on vulnerabilities that cannot be exploited in the real deployment environment. --- ## What You See in the Dashboard ### In Radar Findings enriched with runtime data display additional context: - **Runtime Status**: Whether Monitor has observed exploit attempts against this vulnerability - **Last Exploit Attempt**: Timestamp of the most recent attack targeting this finding - **Attack Frequency**: How often this vulnerability is being targeted - **Reachability**: Whether Monitor confirms the vulnerable code path is reachable from external traffic ### In Monitor Incidents that match a Radar finding display: - **Linked Vulnerability**: Direct link to the corresponding Radar finding with CWE/CVE reference - **Code Location**: The exact file and line Radar identified, alongside the runtime execution context Monitor captured --- ## Impact on Prioritization Without runtime correlation: | Finding | CVSS | Priority | |---------|------|----------| | SQL Injection in `/api/users` | 8.6 | High | | XSS in `/admin/reports` | 6.1 | Medium | | Path Traversal in `/api/files` | 7.5 | High | | SSRF in `/internal/webhook` | 9.1 | Critical | With runtime correlation from Monitor: | Finding | CVSS | Runtime Signal | Adjusted Priority | |---------|------|----------------|-------------------| | SQL Injection in `/api/users` | 8.6 | 47 exploit attempts this week | **Critical** (actively exploited) | | XSS in `/admin/reports` | 6.1 | No attempts observed | Medium (unchanged) | | Path Traversal in `/api/files` | 7.5 | Endpoint is internal only | **Low** (unreachable) | | SSRF in `/internal/webhook` | 9.1 | Endpoint is internal only | **Medium** (unreachable, deprioritized) | The SSRF finding had the highest CVSS score, but runtime data shows it is on an internal endpoint that external traffic never reaches. The SQL injection had a lower score, but it is actively under attack. Without Monitor, your team would fix the SSRF first. With Monitor, they fix the SQL injection first. --- ## Setup Runtime correlation is automatic when both products are active: 1. [Set up a Radar project](/products/radar/create-radar-project) and connect your repository 2. [Set up Monitor](/platforms/android/products/monitor/quick-start) on the same application 3. Both products share data through the ByteHide platform automatically No additional configuration is needed. When Monitor detects an attack that matches a Radar finding, the correlation appears in both dashboards. --- ## Related --- # Monitor Troubleshooting Solutions to common issues when integrating and running ByteHide Monitor on Android. {% .lead %} --- ## Build Issues ### Plugin not found ``` Plugin [id: 'com.bytehide.monitor', version: '1.0.1'] was not found ``` **Solution**: Add `mavenCentral()` to `pluginManagement.repositories` in `settings.gradle.kts`: ```kotlin pluginManagement { repositories { mavenCentral() gradlePluginPortal() google() } } ``` ### No API token configured ``` WARNING: No API token configured (offline mode) ``` **Solution**: Set the token in one of these locations (checked in order): 1. `monitor { projectToken = "bh_xxx" }` in `build.gradle.kts` 2. `BYTEHIDE_API_TOKEN` environment variable 3. `bytehide.api.token=bh_xxx` in `local.properties` ### Could not detect package name ``` ERROR: Could not detect package name ``` **Solution**: Set it explicitly in the plugin DSL: ```kotlin monitor { packageName = "com.example.myapp" } ``` ### Failed to obtain application security signature ``` BUILD FAILED: Could not obtain application security signature ``` **Causes**: invalid or expired API token, no internet access during build, or ByteHide server temporarily unavailable. **Solution**: Verify your token at [app.bytehide.com](https://app.bytehide.com) and check your network connection. --- ## Token Issues ### "Invalid token" or "Token not found" **Cause**: The ByteHide project token is missing or incorrect. **Solution**: 1. Verify your token at [app.bytehide.com](https://app.bytehide.com) under your project [Settings](/platforms/android/products/monitor/cloud-panel/settings) 2. Ensure the `BYTEHIDE_API_TOKEN` environment variable is set correctly 3. Check that the token matches your Monitor project (not a Shield or Secrets token) 4. If using [JSON configuration](/platforms/android/products/monitor/json-configuration), verify the `projectToken` field ### "Token expired" or "Unauthorized" **Cause**: The project token has been revoked or the project was deleted. **Solution**: 1. Log in to [app.bytehide.com](https://app.bytehide.com) 2. Navigate to your Monitor project 3. Generate a new token if needed 4. Update the token in your environment or configuration file --- ## False Positives ### No logs in Logcat **Check these in order:** 1. Filter Logcat by tag `ByteHideMonitor` 2. Verify `android.permission.INTERNET` is in the manifest 3. Do a clean build: `./gradlew clean assembleDebug` 4. Check that the plugin ran during build (look for "Configuring ByteHide Monitor..." in build output) ### Monitor doesn't seem to initialize If you see no `[I001_INIT_START]` log at all: 1. Clean the build: `./gradlew clean` 2. Invalidate caches in Android Studio: File > Invalidate Caches > Invalidate and Restart 3. Rebuild from scratch ### "Registering device..." hangs If logs stop at `[I010_API_CONNECTED] Registering device...`, check internet connectivity on the device/emulator, verify the API token is valid, and check if a proxy or VPN is intercepting connections. ### Debugger detection triggering in development **Cause**: The debugger detection module detects your IDE's debugger during development. **Solution**: - Use the [`NONE` or `LOG` action](/platforms/android/products/monitor/actions) for debugger detection during development - Use [cloud configuration](/platforms/android/products/monitor/cloud-configuration) to easily toggle actions between development and production - Use a separate Monitor project for development with relaxed settings ### Emulator detection in CI/CD **Cause**: CI/CD environments may be detected as emulators due to virtualized hardware. **Solution**: - Use `LOG` action for emulator detection in CI/CD pipelines - Disable emulator detection in CI/CD environments using environment-specific configuration - Use cloud configuration with separate projects for CI/CD vs production ### VM detection on cloud servers **Cause**: Cloud servers (AWS, Azure, GCP) run on hypervisors that are detected as virtual machines. **Solution**: - For cloud-hosted applications, use `LOG` or `NONE` action for VM detection - VM detection is primarily useful for desktop and mobile applications - Consider disabling VM detection for server-side deployments ### SQL Injection false positives on legitimate queries **Cause**: Some legitimate user input may contain patterns that resemble SQL injection (e.g., search queries with quotes or keywords like `OR`, `AND`). **Solution**: - Review the incident in the [Incidences dashboard](/platforms/android/products/monitor/cloud-panel/incidences) to check the confidence score. Low-confidence detections are more likely to be false positives - Use the `LOG` action instead of `BLOCK` while evaluating the pattern - Configure [endpoint-specific overrides](/platforms/android/products/monitor/json-configuration#endpoint-specific-configuration) to relax protections on specific routes that handle complex user input ### Requests blocked unexpectedly (HTTP 403) **Cause**: A web protection module is blocking legitimate requests. **Solution**: 1. Enable [debug logging](/platforms/android/products/monitor/logging#debug-logging) temporarily to see which module triggered the block and why 2. Check the `reference` code in the 403 response to find the corresponding incident in the dashboard 3. Adjust the protection configuration or action for the specific module > **Disable Debug Logging After Troubleshooting** > Debug logging exposes detailed threat information in HTTP responses (attack type, confidence, payload). Always disable it after troubleshooting. See [Debug Logging](/platforms/android/products/monitor/logging#debug-logging) for details. --- ## Configuration Issues ### Protections not activating **Cause**: Configuration is not being loaded properly. **Solution**: 1. Enable [debug logging](/platforms/android/products/monitor/logging#debug-logging) to see Monitor's startup sequence 2. Verify the [configuration priority](/platforms/android/products/monitor/cloud-configuration#configuration-priority): Cloud Dashboard overrides JSON, which overrides code 3. Check that protections have `"enabled": true` in your configuration 4. Verify the JSON file is in the project root with a [recognized filename](/platforms/android/products/monitor/json-configuration#configuration-files) ### Cloud configuration not updating **Cause**: The application cannot reach the ByteHide API. **Solution**: 1. Verify network connectivity to `api.bytehide.com` 2. Check firewall rules and proxy settings 3. Verify the token has not expired 4. Monitor will continue with its last known configuration if the cloud is unreachable --- ## Performance ### High CPU usage **Cause**: Protection check intervals are too frequent. **Solution**: - Increase the `intervalMs` for protection modules (e.g., from 30000 to 60000 or 120000) - Disable protection modules that are not relevant to your deployment environment - Use targeted protections instead of `EnableAllProtections` ### Slow application startup **Cause**: Monitor initialization is blocking the main thread. **Solution**: - For cloud configuration, Monitor initialization includes an API call. Ensure good network connectivity - Use JSON or embedded configuration for faster startup in latency-sensitive environments - Consider async initialization where supported. Use `Monitor.configure()` (async) on Android to avoid ANR errors --- ## Desktop / Server Issues ### Missing dependency ``` ClassNotFoundException: com.bytehide.monitor.Monitor ``` **Solution**: Add the dependency to your build: ```kotlin dependencies { implementation("com.bytehide:monitor-core:1.0.1") } ``` ### Token not found Ensure you're passing the token before calling any protection methods: ```java Monitor.configure(config -> { config.useToken(System.getenv("BYTEHIDE_MONITOR_TOKEN")); config.enableAllProtections(ActionType.LOG, 60000); }); ``` ### How do I check if Monitor is running? ```java boolean running = Monitor.isInitialized(); String sessionId = Monitor.getSessionId(); // null if not connected ``` ### How do I run offline (without backend)? ```bash export BYTEHIDE_MONITOR_OFFLINE=true ``` Detections run locally, threats are logged to console/file, but no data is sent to the dashboard. --- ## Getting Help If you cannot resolve your issue: 1. Enable [debug logging](/platforms/android/products/monitor/logging#debug-logging) and collect the log output 2. Note your Monitor SDK version, Android version, and framework version 3. Check the [Incidences dashboard](/platforms/android/products/monitor/cloud-panel/incidences) for related incidents and their details 4. Contact ByteHide support at [cloud.bytehide.com](https://cloud.bytehide.com) with the information above --- ## Next Steps --- ## Monitor — .NET # Block Action **Action Type:** `Block` Blocks the specific operation and returns HTTP 403 Forbidden. **Web applications only.** **Available for:** ASP.NET Core, ASP.NET Framework, Azure Functions (HTTP triggers) --- ## How It Works The Block action prevents the attack from executing and returns a 403 response. **Behavior:** - Returns `403 Forbidden` status code - Prevents operation from executing (query, file access, etc.) - Application continues running normally - Other requests unaffected - Optionally includes threat details in response --- ## When to Use **Recommended for:** - **SQL Injection** - Block malicious database queries - **NoSQL Injection** - Block MongoDB/Redis attacks - **Cross-Site Scripting (XSS)** - Block script injection attempts - **Path Traversal** - Block unauthorized file access - **Command Injection** - Block OS command execution - **SSRF** - Block unauthorized HTTP requests - **LDAP Injection** - Block directory attacks - **XXE** - Block XML external entity attacks - **LLM Prompt Injection** - Block AI prompt manipulation **Not for:** - Desktop applications (use `close` instead) - Mobile applications (use `close` instead) - Non-HTTP contexts --- ## Configuration ### JSON Configuration ```json { "protections": { "SqlInjection": { "enabled": true, "action": "block" }, "CrossSiteScripting": { "enabled": true, "action": "block" }, "PathTraversal": { "enabled": true, "action": "block" } } } ``` ### ASP.NET Core Configuration ```csharp builder.Services.AddByteHideMonitor(monitor => { monitor.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block); monitor.WithProtection(ProtectionModuleType.CrossSiteScripting, ActionType.Block); monitor.WithProtection(ProtectionModuleType.PathTraversal, ActionType.Block); monitor.WithProtection(ProtectionModuleType.CommandInjection, ActionType.Block); }); ``` --- ## Default Response ### Standard 403 Response ```http HTTP/1.1 403 Forbidden Content-Type: application/json { "error": "Forbidden", "message": "Security violation detected" } ``` ### With Threat Details (Optional) ```http HTTP/1.1 403 Forbidden Content-Type: application/json { "error": "Security violation detected", "incidentId": "SQL-2025-12-28-5678", "timestamp": "2025-12-28T23:00:00Z" } ``` --- ## Custom Block Response ### JSON Response ```csharp builder.Services.AddByteHideMonitor(monitor => { monitor.OnThreatBlocked = async (context, threat) => { context.Response.StatusCode = 403; context.Response.Headers["X-Security-Incident"] = threat.ThreatId; await context.Response.WriteAsJsonAsync(new { error = "Security violation detected", incidentId = threat.ThreatId, type = threat.ModuleType.ToString(), timestamp = DateTime.UtcNow }); }; }); ``` ### HTML Response ```csharp monitor.OnThreatBlocked = async (context, threat) => { context.Response.StatusCode = 403; context.Response.ContentType = "text/html"; await context.Response.WriteAsync(@$" Access Denied

Security Violation Detected

Your request has been blocked due to a security policy.

Incident ID: {threat.ThreatId}

"); }; ``` ### Redirect Response ```csharp monitor.OnThreatBlocked = async (context, threat) => { // Redirect to custom error page context.Response.Redirect("/security-error?incident=" + threat.ThreatId); }; ``` --- ## Code Examples ### SQL Injection Protection ```csharp builder.Services.AddByteHideMonitor(monitor => { monitor.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block); monitor.OnThreatBlocked = async (context, threat) => { // Log to security team await securityLogger.LogCriticalAsync( "SQL injection blocked", threat.Metadata ); // Return 403 context.Response.StatusCode = 403; await context.Response.WriteAsJsonAsync(new { error = "Invalid request", incidentId = threat.ThreatId }); }; }); ``` ### XSS Protection with Logging ```csharp builder.Services.AddByteHideMonitor(monitor => { monitor.WithProtection(ProtectionModuleType.CrossSiteScripting, ActionType.Block); monitor.OnThreatBlocked = async (context, threat) => { // Log attack details await File.AppendAllTextAsync("logs/xss-attacks.log", $"[{DateTime.UtcNow}] XSS blocked: {threat.Description}\n" ); // Block request context.Response.StatusCode = 403; await context.Response.WriteAsync("Request blocked"); }; }); ``` ### Multiple Protection Types ```csharp builder.Services.AddByteHideMonitor(monitor => { // Block all web attacks monitor.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block); monitor.WithProtection(ProtectionModuleType.CrossSiteScripting, ActionType.Block); monitor.WithProtection(ProtectionModuleType.PathTraversal, ActionType.Block); monitor.WithProtection(ProtectionModuleType.CommandInjection, ActionType.Block); monitor.WithProtection(ProtectionModuleType.ServerSideRequestForgery, ActionType.Block); // Custom response for all monitor.OnThreatBlocked = async (context, threat) => { context.Response.StatusCode = 403; await context.Response.WriteAsJsonAsync(new { error = "Security violation", type = threat.ModuleType.ToString(), incidentId = threat.ThreatId, support = "contact@company.com" }); }; }); ``` --- ## Integration Examples ### With Application Insights ```csharp monitor.OnThreatBlocked = async (context, threat) => { // Track in Application Insights telemetryClient.TrackEvent("SecurityViolation", new Dictionary { ["ThreatType"] = threat.ModuleType.ToString(), ["IncidentId"] = threat.ThreatId, ["UserAgent"] = context.Request.Headers["User-Agent"], ["IpAddress"] = context.Connection.RemoteIpAddress?.ToString() }); context.Response.StatusCode = 403; await context.Response.WriteAsync("Forbidden"); }; ``` ### With SIEM Integration ```csharp monitor.OnThreatBlocked = async (context, threat) => { // Send to SIEM await siemClient.SendEventAsync(new { EventType = "WebAttackBlocked", Severity = "High", ThreatType = threat.ModuleType.ToString(), SourceIP = context.Connection.RemoteIpAddress?.ToString(), RequestPath = context.Request.Path, Timestamp = DateTime.UtcNow }); context.Response.StatusCode = 403; }; ``` ### Rate Limiting on Attacks ```csharp private static readonly Dictionary _attackCounts = new(); monitor.OnThreatBlocked = async (context, threat) => { var ip = context.Connection.RemoteIpAddress?.ToString(); lock (_attackCounts) { _attackCounts.TryGetValue(ip, out int count); _attackCounts[ip] = count + 1; // Ban after 5 attacks if (count >= 5) { await ipBanService.BanAsync(ip, TimeSpan.FromHours(24)); } } context.Response.StatusCode = 403; }; ``` --- ## Response Headers ### Security Headers ```csharp monitor.OnThreatBlocked = async (context, threat) => { context.Response.StatusCode = 403; context.Response.Headers["X-Content-Type-Options"] = "nosniff"; context.Response.Headers["X-Frame-Options"] = "DENY"; context.Response.Headers["X-Security-Incident"] = threat.ThreatId; await context.Response.WriteAsync("Forbidden"); }; ``` --- ## Best Practices 1. **Use Block for All Web Attacks** ```csharp // Block is the right choice for web protections monitor.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block); monitor.WithProtection(ProtectionModuleType.CrossSiteScripting, ActionType.Block); ``` 2. **Log All Blocked Attacks** ```csharp monitor.OnThreatBlocked = async (context, threat) => { await logger.LogWarningAsync($"Blocked {threat.ModuleType}: {threat.Description}"); context.Response.StatusCode = 403; }; ``` 3. **Don't Reveal Too Much Information** ```csharp // Good: Generic message await context.Response.WriteAsync("Forbidden"); // Bad: Reveals detection details await context.Response.WriteAsync($"SQL injection detected: {threat.Description}"); ``` 4. **Implement Rate Limiting** ```csharp // Track attack attempts and ban repeat offenders if (await IsRepeatAttacker(ipAddress)) { await BanIpAddressAsync(ipAddress); } ``` --- ## Related Actions - [Log](/platforms/dotnet/products/monitor/actions/log) - Log attack without blocking - [Custom](/platforms/dotnet/products/monitor/actions/custom) - Custom block logic - [Close](/platforms/dotnet/products/monitor/actions/close) - Terminate (desktop/mobile) --- # Close Action **Action Type:** `Close` Immediately terminates the application when a threat is detected. **Available for:** All platforms (Desktop, Mobile, Web) --- ## How It Works The Close action calls `Environment.Exit(-1)` immediately upon threat detection. **Behavior:** - Immediate termination (no graceful shutdown) - Fastest response time - No cleanup operations - Exit code: -1 --- ## When to Use **Recommended for:** - **Debugger Detection** - Prevent reverse engineering - **Tampering Detection** - Stop modified/cracked applications - **Jailbreak Detection** - Block compromised mobile devices - **Process Injection** - Prevent code injection attacks - **Critical security violations** - Any threat requiring immediate shutdown **Not recommended for:** - Web applications (use `block` instead) - Non-critical threats (use `log` instead) - Development environments (use `none` instead) --- ## Configuration ### JSON Configuration ```json { "protections": { "DebuggerDetection": { "enabled": true, "action": "close" }, "TamperingDetection": { "enabled": true, "action": "close" } } } ``` ### Code-Based Configuration ```csharp await Payload.ConfigureAsync(config => { config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close); config.AddProtection(ProtectionModuleType.TamperingDetection, ActionType.Close); }); ``` --- ## Platform-Specific Examples ### Desktop Application ```csharp await Payload.ConfigureAsync(config => { // Close on debugger detection config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close); // Close on tampering config.AddProtection(ProtectionModuleType.TamperingDetection, ActionType.Close); // Close on memory dump attempts config.AddProtection(ProtectionModuleType.MemoryDumpDetection, ActionType.Close); }); ``` ### Mobile Application (MAUI) ```csharp await Payload.ConfigureAsync(config => { // Close on jailbreak/root config.AddProtection(ProtectionModuleType.JailbreakDetection, ActionType.Close); // Close on debugger config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close); }); ``` ### Conditional Close (Development vs Production) ```csharp await Payload.ConfigureAsync(config => { #if DEBUG // Development: just log config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Log); #else // Production: close immediately config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close); #endif }); ``` --- ## Environment-Specific Configuration ```json { "environments": { "development": { "protections": { "DebuggerDetection": { "enabled": true, "action": "log" } } }, "production": { "protections": { "DebuggerDetection": { "enabled": true, "action": "close" } } } } } ``` --- ## Best Practices 1. **Use for Critical Threats Only** ```csharp // Close action is appropriate here config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close); config.AddProtection(ProtectionModuleType.TamperingDetection, ActionType.Close); // Log action is better for these config.AddProtection(ProtectionModuleType.VirtualMachineDetection, ActionType.Log); config.AddProtection(ProtectionModuleType.ClockTampering, ActionType.Log); ``` 2. **Different Actions for Different Environments** ```csharp var action = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production" ? ActionType.Close : ActionType.Log; config.AddProtection(ProtectionModuleType.DebuggerDetection, action); ``` 3. **Combine with Logging for Forensics** ```json { "logging": { "level": "warning", "file": { "enabled": true, "path": "logs/security.log" } }, "protections": { "DebuggerDetection": { "enabled": true, "action": "close" } } } ``` --- ## Execution Flow ``` 1. Threat Detected (e.g., Debugger attached) ↓ 2. Monitor triggers Close action ↓ 3. Log threat to backend (if configured) ↓ 4. Log threat to local file (if configured) ↓ 5. Environment.Exit(-1) called ↓ 6. Application terminates immediately ``` --- ## Related Actions - [Custom](/platforms/dotnet/products/monitor/actions/custom) - Execute custom logic before closing - [Erase](/platforms/dotnet/products/monitor/actions/erase) - Delete sensitive data before closing - [Log](/platforms/dotnet/products/monitor/actions/log) - Record threat without closing --- # Custom Action **Action Type:** `Custom` Execute custom logic when a threat is detected. Full control over response behavior. **Available for:** All platforms (Desktop, Mobile, Web) --- ## How It Works The Custom action executes your async delegate when a threat is detected. **Behavior:** - Executes your custom async function - Complete control over response logic - Can combine multiple actions (log + close, notify + block, etc.) - Can make external API calls - Can implement complex workflows --- ## When to Use **Recommended for:** - **Enterprise Integrations** - SIEM, SOC, ticketing systems - **Multi-step Workflows** - Notify → Confirm → Block → Log - **Notification Systems** - Email, Slack, SMS, PagerDuty - **Complex Business Logic** - Approval workflows, escalation - **Data Erasure** - Secure deletion before shutdown - **Graceful Shutdown** - Save state before terminating - **User Interaction** - Alerts, confirmation dialogs --- ## Configuration Methods ### Method 1: Register and Use in Code ```csharp await Payload.ConfigureAsync(config => { // 1. Register the custom action config.RegisterCustomAction("my-action", async (threat) => { // Your custom logic here await MySecurityHandler.ProcessAsync(threat); }); // 2. Assign to protection config.AddProtection(ProtectionModuleType.DebuggerDetection, "my-action"); }); ``` ### Method 2: Register in Code, Use in JSON Register your custom actions at application startup: ```csharp // Program.cs or Startup public static async Task Main(string[] args) { await Payload.ConfigureAsync(config => { // Register custom actions config.RegisterCustomAction("notify-security-team", async (threat) => { await emailService.SendAsync("security@company.com", $"Threat: {threat.Description}"); Environment.Exit(-1); }); config.RegisterCustomAction("slack-alert", async (threat) => { await slackClient.PostAsync("#security", $"🚨 {threat.ModuleType}: {threat.Description}"); Environment.Exit(-1); }); config.RegisterCustomAction("siem-integration", async (threat) => { await siemClient.LogAsync(threat); Environment.Exit(-1); }); }); // Application continues... } ``` Then reference them in your JSON configuration: ```json { "protections": { "DebuggerDetection": { "enabled": true, "action": "custom", "customActionName": "notify-security-team" }, "TamperingDetection": { "enabled": true, "action": "custom", "customActionName": "siem-integration" }, "JailbreakDetection": { "enabled": true, "action": "custom", "customActionName": "slack-alert" } } } ``` ### Method 3: Hybrid Approach Register some actions in code, configure others in JSON: ```csharp // Startup - Register reusable custom actions await Payload.ConfigureAsync(config => { config.RegisterCustomAction("email-alert", async (threat) => { await EmailService.SendAlertAsync(threat); }); config.RegisterCustomAction("pagerduty-alert", async (threat) => { await PagerDutyService.TriggerAsync(threat); }); }); // Load JSON configuration await Payload.LoadConfigurationAsync("monitor-config.json"); ``` **monitor-config.json:** ```json { "protections": { "DebuggerDetection": { "enabled": true, "action": "custom", "customActionName": "email-alert" }, "MemoryDumpDetection": { "enabled": true, "action": "custom", "customActionName": "pagerduty-alert" } } } ``` --- ## Code Examples ### Email Notification ```csharp config.RegisterCustomAction("email-security-team", async (threat) => { await emailService.SendAsync(new Email { To = "security@company.com", Subject = $"Security Alert: {threat.ModuleType}", Body = $@" Threat Detected: {threat.Description} Incident ID: {threat.ThreatId} Time: {DateTime.UtcNow} Metadata: {JsonSerializer.Serialize(threat.Metadata, new JsonSerializerOptions { WriteIndented = true })} " }); // Then close application Environment.Exit(-1); }); ``` ### SIEM Integration ```csharp config.RegisterCustomAction("siem-integration", async (threat) => { // Send to Splunk/ELK/QRadar await siemClient.SendEventAsync(new SecurityEvent { Severity = "Critical", Type = threat.ModuleType.ToString(), Description = threat.Description, ThreatId = threat.ThreatId, Timestamp = DateTime.UtcNow, Metadata = threat.Metadata, HostName = Environment.MachineName, UserName = Environment.UserName }); // Log locally await File.AppendAllTextAsync("logs/security.log", $"[{DateTime.UtcNow}] {threat.ModuleType}: {threat.Description}\n" ); // Terminate Environment.Exit(-1); }); ``` ### Slack Notification ```csharp config.RegisterCustomAction("slack-alert", async (threat) => { var slackMessage = new { channel = "#security-alerts", username = "ByteHide Monitor", icon_emoji = ":shield:", attachments = new[] { new { color = "danger", title = $"Security Threat: {threat.ModuleType}", text = threat.Description, fields = new[] { new { title = "Incident ID", value = threat.ThreatId, @short = true }, new { title = "Timestamp", value = DateTime.UtcNow.ToString(), @short = true }, new { title = "Machine", value = Environment.MachineName, @short = true }, new { title = "User", value = Environment.UserName, @short = true } } } } }; await httpClient.PostAsJsonAsync(slackWebhookUrl, slackMessage); Environment.Exit(-1); }); ``` ### Mobile Alert Dialog ```csharp config.RegisterCustomAction("mobile-alert", async (threat) => { // Show alert to user await Application.Current.MainPage.DisplayAlert( "Security Warning", $"Threat detected: {threat.Description}\n\nThe application will now close.", "OK" ); // Wait for user acknowledgment await Task.Delay(3000); // Terminate Environment.Exit(-1); }); ``` ### Conditional Response ```csharp config.RegisterCustomAction("conditional-response", async (threat) => { // Different actions based on threat type switch (threat.ModuleType) { case ProtectionModuleType.DebuggerDetection: // Critical: Close immediately Environment.Exit(-1); break; case ProtectionModuleType.VirtualMachineDetection: // Medium: Just log await Logger.LogWarningAsync($"VM detected: {threat.Description}"); break; case ProtectionModuleType.ClockTampering: // Low: Show warning but continue await ShowWarningAsync("System time appears incorrect"); break; } }); ``` ### Grace Period Implementation ```csharp config.RegisterCustomAction("grace-period", async (threat) => { var gracePeriodKey = $"grace_{threat.ModuleType}"; var lastDetection = await SecureStorage.GetAsync(gracePeriodKey); if (DateTime.TryParse(lastDetection, out var lastTime)) { var daysSince = (DateTime.UtcNow - lastTime).TotalDays; if (daysSince < 7) { var daysRemaining = 7 - (int)daysSince; await ShowWarningAsync( "Security Warning", $"Please address this security issue within {daysRemaining} days." ); return; // Don't close yet } } // Grace period expired or first detection await SecureStorage.SetAsync(gracePeriodKey, DateTime.UtcNow.ToString()); await ShowMessageAsync( "Security Violation", "The grace period has expired. The application will now close." ); Environment.Exit(-1); }); ``` ### User Confirmation ```csharp config.RegisterCustomAction("confirm-close", async (threat) => { var result = await Application.Current.MainPage.DisplayAlert( "Security Threat Detected", $"{threat.Description}\n\nClose the application?", "Yes, Close", "No, Continue" ); if (result) { await Logger.LogAsync($"User confirmed close for {threat.ModuleType}"); Environment.Exit(-1); } else { await Logger.LogAsync($"User chose to continue despite {threat.ModuleType}"); } }); ``` ### Enterprise Workflow ```csharp config.RegisterCustomAction("enterprise-workflow", async (threat) => { // 1. Log to database await dbContext.SecurityIncidents.AddAsync(new SecurityIncident { ThreatId = threat.ThreatId, Type = threat.ModuleType.ToString(), Description = threat.Description, Metadata = JsonSerializer.Serialize(threat.Metadata), DetectedAt = DateTime.UtcNow, MachineName = Environment.MachineName, UserName = Environment.UserName }); await dbContext.SaveChangesAsync(); // 2. Create ticket in ServiceNow var ticket = await serviceNowClient.CreateIncidentAsync(new { short_description = $"Security Threat: {threat.ModuleType}", description = threat.Description, severity = "1 - Critical", assignment_group = "security-operations" }); // 3. Send to PagerDuty await pagerDutyClient.TriggerIncidentAsync(new { routing_key = pagerDutyKey, event_action = "trigger", payload = new { summary = $"Security Threat: {threat.ModuleType}", severity = "critical", source = Environment.MachineName, custom_details = threat.Metadata } }); // 4. Notify Slack await slackClient.PostMessageAsync("#security", $"🚨 Security incident {ticket.Number} created: {threat.Description}" ); // 5. Log to SIEM await siemLogger.LogCriticalAsync(threat); // 6. Terminate application Environment.Exit(-1); }); ``` --- ## ASP.NET Core Web Example ```csharp builder.Services.AddByteHideMonitor(options => { options.OnThreatDetected = async (httpContext, threat) => { // Log attack details var attackInfo = new { ThreatType = threat.ModuleType.ToString(), Description = threat.Description, IpAddress = httpContext.Connection.RemoteIpAddress?.ToString(), UserAgent = httpContext.Request.Headers["User-Agent"].ToString(), Path = httpContext.Request.Path, Method = httpContext.Request.Method, Timestamp = DateTime.UtcNow }; await attackLogger.LogAsync(attackInfo); // Send to security team await emailService.SendAsync( "security@company.com", "Web Attack Blocked", JsonSerializer.Serialize(attackInfo, new JsonSerializerOptions { WriteIndented = true }) ); // Return custom 403 response httpContext.Response.StatusCode = 403; httpContext.Response.Headers["X-Incident-Id"] = threat.ThreatId; await httpContext.Response.WriteAsJsonAsync(new { error = "Security violation detected", incidentId = threat.ThreatId, support = "security@company.com" }); }; }); ``` --- ## Threat Object Properties ```csharp config.RegisterCustomAction("inspect-threat", async (threat) => { // Available properties: var threatId = threat.ThreatId; // "DBG-2025-12-28-1234" var moduleType = threat.ModuleType; // ProtectionModuleType.DebuggerDetection var description = threat.Description; // "Debugger detected" var confidence = threat.Confidence; // 0.95 var detectedAt = threat.DetectedAt; // DateTime.UtcNow var metadata = threat.Metadata; // Dictionary // Metadata examples: var debuggerName = threat.Metadata["debuggerName"]; // "Visual Studio" var processId = threat.Metadata["processId"]; // 12345 }); ``` --- ## Best Practices ### 1. Always Handle Exceptions ```csharp config.RegisterCustomAction("safe-handler", async (threat) => { try { await externalService.NotifyAsync(threat); } catch (Exception ex) { // Log error but still take security action await Logger.LogErrorAsync(ex); } finally { // Always close on critical threats Environment.Exit(-1); } }); ``` ### 2. Set Timeouts for External Calls ```csharp config.RegisterCustomAction("timeout-handler", async (threat) => { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); try { await emailService.SendAsync(threat, cts.Token); } catch (OperationCanceledException) { // Timeout - close anyway await Logger.LogAsync("Email notification timed out"); } Environment.Exit(-1); }); ``` ### 3. Don't Block on UI Thread ```csharp // Mobile applications config.RegisterCustomAction("ui-safe", async (threat) => { await Device.InvokeOnMainThreadAsync(async () => { await DisplayAlert("Security Alert", threat.Description, "OK"); }); }); ``` --- ## Enterprise Startup Configuration Register multiple custom actions at startup for use across JSON configurations: ```csharp public class Program { public static async Task Main(string[] args) { // Register all custom actions at startup await ConfigureMonitorActionsAsync(); var builder = WebApplication.CreateBuilder(args); // ... rest of app configuration } private static async Task ConfigureMonitorActionsAsync() { await Payload.ConfigureAsync(config => { // Email notification action config.RegisterCustomAction("email-security", async (threat) => { await EmailService.SendAsync(new { To = "security@company.com", Subject = $"Security Alert: {threat.ModuleType}", Body = threat.Description, Metadata = threat.Metadata }); Environment.Exit(-1); }); // Slack notification action config.RegisterCustomAction("slack-security", async (threat) => { await SlackService.PostAsync("#security-alerts", new { text = $"🚨 *{threat.ModuleType}*: {threat.Description}", incident_id = threat.ThreatId }); Environment.Exit(-1); }); // PagerDuty critical alert config.RegisterCustomAction("pagerduty-critical", async (threat) => { await PagerDutyService.TriggerIncidentAsync(new { severity = "critical", summary = $"Security: {threat.ModuleType}", details = threat.Metadata }); Environment.Exit(-1); }); // SIEM logging action config.RegisterCustomAction("siem-log", async (threat) => { await SiemService.LogSecurityEventAsync(new { event_type = "SecurityThreat", threat_type = threat.ModuleType.ToString(), description = threat.Description, metadata = threat.Metadata, timestamp = DateTime.UtcNow }); Environment.Exit(-1); }); // User notification (mobile) config.RegisterCustomAction("user-notify", async (threat) => { await Application.Current.MainPage.DisplayAlert( "Security Warning", threat.Description, "OK" ); await Task.Delay(2000); Environment.Exit(-1); }); // Analytics only (no shutdown) config.RegisterCustomAction("analytics-track", async (threat) => { await AnalyticsService.TrackEventAsync("SecurityThreat", new { type = threat.ModuleType.ToString(), confidence = threat.Confidence, metadata = threat.Metadata }); // Don't close - just track }); }); } } ``` **Then use in JSON:** ```json { "protections": { "DebuggerDetection": { "enabled": true, "action": "custom", "customActionName": "pagerduty-critical" }, "SqlInjection": { "enabled": true, "action": "custom", "customActionName": "siem-log" }, "VirtualMachineDetection": { "enabled": true, "action": "custom", "customActionName": "analytics-track" }, "JailbreakDetection": { "enabled": true, "action": "custom", "customActionName": "user-notify" } } } ``` --- ## Benefits of Register-in-Code + JSON Configuration 1. **Separation of Concerns**: Business logic in code, configuration in JSON 2. **Environment-Specific Config**: Different JSON files per environment 3. **Non-Developer Changes**: Ops team can adjust without code changes 4. **Reusable Actions**: Register once, use across multiple protections 5. **Type Safety**: C# type checking for action implementation 6. **Easy Testing**: Test custom actions independently --- ## Related Actions - [Close](/platforms/dotnet/products/monitor/actions/close) - Simple termination - [Erase](/platforms/dotnet/products/monitor/actions/erase) - Secure data deletion - [Log](/platforms/dotnet/products/monitor/actions/log) - Simple logging - [Block](/platforms/dotnet/products/monitor/actions/block) - Web request blocking --- # Erase Action **Action Type:** `Erase` Securely deletes sensitive data before terminating the application. **Available for:** All platforms (Desktop, Mobile, Server) --- ## How It Works The Erase action triggers custom data erasure logic before calling `Environment.Exit(-1)`. **Behavior:** - Executes custom erasure logic - Overwrites sensitive memory regions - Clears encryption keys - Deletes temporary files - Then terminates application > **Implementation Required** > You must implement the data erasure logic using custom actions. Monitor does not automatically know what data to erase. --- ## When to Use **Recommended for:** - **Financial Applications** - Credit card data, account credentials - **Healthcare Apps** - PII/PHI, patient records - **Encryption Key Storage** - AES keys, RSA private keys - **Password Managers** - Master passwords, vault keys - **Cryptocurrency Wallets** - Private keys, seed phrases - **High-security Environments** - Classified data, trade secrets **Not recommended for:** - Applications without sensitive in-memory data - Web applications (session data is request-scoped) --- ## Implementation ### Basic Erase Action ```csharp await Payload.ConfigureAsync(config => { config.RegisterCustomAction("secure-erase", async (threat) => { // 1. Erase encryption keys if (encryptionKeys != null) { Array.Clear(encryptionKeys, 0, encryptionKeys.Length); } // 2. Overwrite sensitive data if (userCredentials != null) { SecureMemory.Clear(userCredentials); } // 3. Delete temporary files if (Directory.Exists(tempDataPath)) { Directory.Delete(tempDataPath, recursive: true); } // 4. Log incident await SecurityLog.WriteAsync($"Erase triggered: {threat.Description}"); // 5. Terminate Environment.Exit(-1); }); config.AddProtection(ProtectionModuleType.DebuggerDetection, "secure-erase"); }); ``` --- ## Secure Memory Erasure ### Array Clearing ```csharp // Clear byte arrays (encryption keys, passwords) private static void SecureErase(byte[] data) { if (data != null) { Array.Clear(data, 0, data.Length); // Double-overwrite for extra security for (int i = 0; i < data.Length; i++) { data[i] = 0xFF; } Array.Clear(data, 0, data.Length); } } ``` ### String Clearing (Unsafe) ```csharp private static unsafe void SecureEraseString(string text) { if (text == null) return; fixed (char* ptr = text) { for (int i = 0; i < text.Length; i++) { ptr[i] = '\0'; } } } ``` ### Using SecureString ```csharp private static void ClearSecureString(SecureString secureString) { if (secureString != null && !secureString.IsReadOnly()) { secureString.Clear(); secureString.Dispose(); } } ``` --- ## Code Examples ### Financial Application ```csharp config.RegisterCustomAction("financial-erase", async (threat) => { try { // Erase credit card data if (paymentData != null) { SecureErase(paymentData.CardNumber); SecureErase(paymentData.CVV); paymentData = null; } // Erase session tokens if (authTokens != null) { foreach (var token in authTokens) { SecureEraseString(token); } authTokens.Clear(); } // Erase encryption keys SecureErase(aesKey); SecureErase(hmacKey); // Log incident to audit system await AuditLog.WriteAsync(new AuditEvent { Type = "SecurityShutdown", Reason = threat.Description, Timestamp = DateTime.UtcNow }); // Delete temporary transaction files if (Directory.Exists("temp/transactions")) { Directory.Delete("temp/transactions", true); } } finally { // Force garbage collection GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); // Terminate Environment.Exit(-1); } }); ``` ### Cryptocurrency Wallet ```csharp config.RegisterCustomAction("wallet-erase", async (threat) => { try { // Erase private keys if (privateKeys != null) { foreach (var key in privateKeys) { SecureErase(key.KeyData); } privateKeys.Clear(); } // Erase seed phrase if (seedPhrase != null) { for (int i = 0; i < seedPhrase.Length; i++) { SecureEraseString(seedPhrase[i]); seedPhrase[i] = null; } } // Erase cached balances and addresses walletCache?.Clear(); // Log to secure audit trail await BlockchainLogger.LogSecurityEventAsync( "WalletEmergencyShutdown", threat.ThreatId ); // Overwrite wallet file with zeros if (File.Exists(walletPath)) { var fileSize = new FileInfo(walletPath).Length; var zeros = new byte[fileSize]; File.WriteAllBytes(walletPath, zeros); File.Delete(walletPath); } } finally { Environment.Exit(-1); } }); ``` ### Healthcare Application ```csharp config.RegisterCustomAction("hipaa-erase", async (threat) => { try { // Erase patient PII/PHI if (patientData != null) { SecureEraseString(patientData.SSN); SecureEraseString(patientData.MedicalRecordNumber); SecureEraseString(patientData.DateOfBirth); patientData = null; } // Erase cached medical records if (medicalRecordsCache != null) { foreach (var record in medicalRecordsCache) { record.Value?.Clear(); } medicalRecordsCache.Clear(); } // Erase database connection strings SecureEraseString(dbConnectionString); // Log HIPAA security incident await HipaaAuditLog.RecordSecurityIncidentAsync(new { IncidentType = "EmergencyDataErasure", ThreatType = threat.ModuleType.ToString(), Timestamp = DateTime.UtcNow, UserId = CurrentUser.Id }); // Delete temporary medical image files if (Directory.Exists("temp/medical-images")) { foreach (var file in Directory.GetFiles("temp/medical-images")) { // Overwrite with random data before deletion var fileSize = new FileInfo(file).Length; var randomData = new byte[fileSize]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(randomData); } File.WriteAllBytes(file, randomData); File.Delete(file); } Directory.Delete("temp/medical-images"); } } finally { GC.Collect(); Environment.Exit(-1); } }); ``` --- ## Best Practices ### 1. Multi-Pass Overwriting ```csharp private static void SecureEraseMultiPass(byte[] data, int passes = 3) { if (data == null) return; using (var rng = RandomNumberGenerator.Create()) { for (int pass = 0; pass < passes; pass++) { // Random data rng.GetBytes(data); // All ones for (int i = 0; i < data.Length; i++) data[i] = 0xFF; // All zeros Array.Clear(data, 0, data.Length); } } } ``` ### 2. Force Garbage Collection ```csharp // After erasing, force GC to clean up GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); ``` ### 3. Erase Before Exception ```csharp config.RegisterCustomAction("safe-erase", async (threat) => { try { // Erase sensitive data EraseAllSensitiveData(); } catch (Exception ex) { // Log error but still terminate await Logger.LogErrorAsync(ex); } finally { // Always terminate even if erase fails Environment.Exit(-1); } }); ``` ### 4. Audit Logging ```csharp // Always log erasure events for compliance await AuditLog.WriteAsync(new { EventType = "DataErasure", Reason = threat.Description, ItemsErased = new[] { "EncryptionKeys", "UserCredentials", "SessionTokens" }, Timestamp = DateTime.UtcNow }); ``` --- ## Platform Compatibility | Platform | Support | Notes | |----------|---------|-------| | Windows | ✔ | Full support | | Linux | ✔ | Full support | | macOS | ✔ | Full support | | Android | ✔ | Full support | | iOS | ✔ | Full support | | .NET 6+ | ✔ | Full support | | .NET Framework | ✔ | Full support | --- ## Security Considerations > **Memory Residency** > Even after `Array.Clear()`, data may remain in memory due to garbage collection delays or memory paging. For maximum security, use multi-pass overwriting and force garbage collection. > **Disk Caching** > If sensitive data was written to disk, use secure file deletion (multiple overwrites) before deleting files. --- ## Related Actions - [Close](/platforms/dotnet/products/monitor/actions/close) - Terminate without erasure - [Custom](/platforms/dotnet/products/monitor/actions/custom) - Implement custom erasure logic - [Log](/platforms/dotnet/products/monitor/actions/log) - Record without terminating --- # Log Action **Action Type:** `Log` Records the threat to backend and/or local files, then continues execution. **Available for:** All platforms (Desktop, Mobile, Web) --- ## How It Works The Log action records threat information without disrupting application execution. **Behavior:** - Logs to ByteHide backend (if API key configured) - Logs to local file (if file logging enabled) - Logs to console (if console logging enabled) - Application continues normally - No user disruption --- ## When to Use **Recommended for:** - **Non-critical threats** - VM detection, container detection - **Analytics and monitoring** - Gathering threat intelligence - **Development environments** - Testing without disruption - **Cloud metadata detection** - Deployment environment tracking - **License binding** - Monitoring hardware changes **Not recommended for:** - Critical security threats (use `close` instead) - Production web attacks (use `block` instead) --- ## Configuration ### JSON Configuration ```json { "logging": { "level": "warning", "console": true, "file": { "enabled": true, "path": "logs/monitor.log" } }, "protections": { "VirtualMachineDetection": { "enabled": true, "action": "log" }, "ContainerDetection": { "enabled": true, "action": "log" } } } ``` ### Code-Based Configuration ```csharp await Payload.ConfigureAsync(config => { config.AddProtection(ProtectionModuleType.VirtualMachineDetection, ActionType.Log); config.AddProtection(ProtectionModuleType.ContainerDetection, ActionType.Log); config.AddProtection(ProtectionModuleType.CloudMetadata, ActionType.Log); }); ``` --- ## Logging Destinations ### Backend Logging (ByteHide Cloud) ```json { "apiKey": "your-api-key", "logging": { "backend": { "enabled": true, "endpoint": "https://api.bytehide.com/v1/monitor" } } } ``` ### File Logging ```json { "logging": { "file": { "enabled": true, "path": "logs/monitor.log", "maxSizeKB": 10240, "maxFiles": 5, "format": "json" } } } ``` ### Console Logging ```json { "logging": { "console": true, "level": "warning" } } ``` --- ## Code Examples ### Basic Logging ```csharp await Payload.ConfigureAsync(config => { // Log VM detection for analytics config.AddProtection(ProtectionModuleType.VirtualMachineDetection, ActionType.Log); // Log emulator detection config.AddProtection(ProtectionModuleType.EmulatorDetection, ActionType.Log); }); ``` ### Custom Log Processing ```csharp await Payload.ConfigureAsync(config => { config.RegisterCustomAction("custom-logger", async (threat) => { // Log to your custom system await MyLogger.LogSecurityEventAsync(new { Type = threat.ModuleType.ToString(), Description = threat.Description, Metadata = threat.Metadata, Timestamp = DateTime.UtcNow }); // Continue execution - don't close }); config.AddProtection(ProtectionModuleType.VirtualMachineDetection, "custom-logger"); }); ``` ### Analytics Integration ```csharp config.RegisterCustomAction("analytics-logger", async (threat) => { // Send to analytics platform await analyticsClient.TrackEventAsync("SecurityThreat", new { ThreatType = threat.ModuleType.ToString(), Severity = "Medium", Environment = Environment.GetEnvironmentVariable("ENVIRONMENT"), Platform = RuntimeInformation.OSDescription }); }); ``` --- ## Log Format ### JSON Format ```json { "timestamp": "2025-12-28T22:30:00Z", "threatId": "VM-2025-12-28-1234", "moduleType": "VirtualMachineDetection", "action": "Log", "description": "Virtual machine detected", "confidence": 0.95, "metadata": { "hypervisor": "VMware", "productName": "VMware Virtual Platform", "biosVendor": "Phoenix Technologies LTD" } } ``` ### Plain Text Format ``` [2025-12-28 22:30:00] [WARN] VirtualMachineDetection: Virtual machine detected (VMware) ``` --- ## Platform-Specific Examples ### Desktop Application ```csharp await Payload.ConfigureAsync(config => { // Log for analytics, don't disrupt users config.AddProtection(ProtectionModuleType.VirtualMachineDetection, ActionType.Log); config.AddProtection(ProtectionModuleType.RemoteDesktop, ActionType.Log); config.AddProtection(ProtectionModuleType.ContainerDetection, ActionType.Log); }); ``` ### Mobile Application ```csharp await Payload.ConfigureAsync(config => { // Development: log everything #if DEBUG config.AddProtection(ProtectionModuleType.JailbreakDetection, ActionType.Log); config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Log); #else // Production: close on critical threats config.AddProtection(ProtectionModuleType.JailbreakDetection, ActionType.Close); config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close); #endif }); ``` ### Web Application ```csharp builder.Services.AddByteHideMonitor(monitor => { // Log LLM prompt injection attempts without blocking monitor.WithProtection(ProtectionModuleType.LlmPromptInjection, ActionType.Log); // Block actual attacks monitor.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block); }); ``` --- ## Log Levels | Level | Description | Use Case | |-------|-------------|----------| | **Error** | Critical security violations | Tampering, debugger | | **Warning** | Potential threats | VM, emulator, clock tampering | | **Info** | Environment information | Container, cloud metadata | | **Debug** | Detailed detection info | Development, troubleshooting | ```json { "logging": { "level": "warning", "minimalSeverity": "medium" } } ``` --- ## Best Practices 1. **Use for Non-Critical Threats** ```csharp // Log action appropriate config.AddProtection(ProtectionModuleType.VirtualMachineDetection, ActionType.Log); config.AddProtection(ProtectionModuleType.ContainerDetection, ActionType.Log); // Close action better config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close); ``` 2. **Enable File Logging for Forensics** ```json { "logging": { "file": { "enabled": true, "path": "logs/monitor.log", "maxSizeKB": 10240 } } } ``` 3. **Integrate with Existing Logging** ```csharp config.RegisterCustomAction("serilog-integration", async (threat) => { Log.Warning("Security threat detected: {ThreatType} - {Description}", threat.ModuleType, threat.Description ); }); ``` 4. **Monitor Logs for Trends** ```csharp // Analyze logs to detect attack patterns var vmDetections = await LogAnalyzer.CountByTypeAsync("VirtualMachineDetection"); if (vmDetections > 100) { await SecurityTeam.NotifyAsync("High VM detection rate"); } ``` --- ## Related Actions - [None](/platforms/dotnet/products/monitor/actions/none) - Detect without logging (analytics only) - [Custom](/platforms/dotnet/products/monitor/actions/custom) - Custom logging logic - [Close](/platforms/dotnet/products/monitor/actions/close) - Log then terminate --- # None Action **Action Type:** `None` Detects threats but takes no action. Useful for testing, analytics, and development. **Available for:** All platforms (Desktop, Mobile, Web) --- ## How It Works The None action allows detection to run normally without any user-facing response. **Behavior:** - Detection runs as configured - No user disruption - No application termination - No request blocking - Still logs to backend (if configured) - Still logs to local files (if configured) --- ## When to Use **Recommended for:** - **Development Environments** - Test without disruption - **Testing Configurations** - Validate protection settings - **Analytics Collection** - Gather threat statistics - **False Positive Evaluation** - Assess detection accuracy - **Gradual Rollout** - Monitor before enforcing - **Debugging** - Understand detection triggers **Not recommended for:** - Production environments with critical threats - Applications requiring active protection --- ## Configuration ### JSON Configuration ```json { "protections": { "DebuggerDetection": { "enabled": true, "action": "none" }, "VirtualMachineDetection": { "enabled": true, "action": "none" } } } ``` ### Code-Based Configuration ```csharp await Payload.ConfigureAsync(config => { config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.None); config.AddProtection(ProtectionModuleType.VirtualMachineDetection, ActionType.None); }); ``` --- ## Use Cases ### Development Mode ```csharp await Payload.ConfigureAsync(config => { #if DEBUG // Development: detect but don't disrupt config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.None); config.AddProtection(ProtectionModuleType.VirtualMachineDetection, ActionType.None); #else // Production: enforce security config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close); config.AddProtection(ProtectionModuleType.VirtualMachineDetection, ActionType.Log); #endif }); ``` ### Testing Configuration ```csharp // Test all protections without disruption await Payload.ConfigureAsync(config => { config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.None); config.AddProtection(ProtectionModuleType.TamperingDetection, ActionType.None); config.AddProtection(ProtectionModuleType.JailbreakDetection, ActionType.None); config.AddProtection(ProtectionModuleType.MemoryDumpDetection, ActionType.None); }); // Check logs to see what would be detected // Then change to appropriate actions (Close, Log, etc.) ``` ### Analytics Collection ```json { "logging": { "backend": { "enabled": true, "endpoint": "https://api.bytehide.com/v1/monitor" }, "file": { "enabled": true, "path": "logs/analytics.log" } }, "protections": { "VirtualMachineDetection": { "enabled": true, "action": "none" }, "ContainerDetection": { "enabled": true, "action": "none" }, "CloudMetadata": { "enabled": true, "action": "none" }, "RemoteDesktop": { "enabled": true, "action": "none" } } } ``` ### Gradual Rollout ```csharp // Week 1: Monitor only (none action) // Week 2: Log only (log action) // Week 3: Enforce (close/block action) var rolloutPhase = await GetRolloutPhaseAsync(); var action = rolloutPhase switch { "monitor" => ActionType.None, "log" => ActionType.Log, "enforce" => ActionType.Close, _ => ActionType.None }; config.AddProtection(ProtectionModuleType.DebuggerDetection, action); ``` ### False Positive Evaluation ```csharp // Collect data to analyze false positive rate await Payload.ConfigureAsync(config => { config.AddProtection(ProtectionModuleType.SqlInjection, ActionType.None); config.RegisterCustomAction("analytics", async (threat) => { // Log all SQL injection detections await analyticsDb.LogDetectionAsync(new { ThreatId = threat.ThreatId, Query = threat.Metadata["query"], Confidence = threat.Confidence, Timestamp = DateTime.UtcNow }); }); }); // After analysis, switch to Block action ``` --- ## Platform-Specific Examples ### Desktop Application Testing ```csharp await Payload.ConfigureAsync(config => { // Test all desktop protections config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.None); config.AddProtection(ProtectionModuleType.VirtualMachineDetection, ActionType.None); config.AddProtection(ProtectionModuleType.MemoryDumpDetection, ActionType.None); config.AddProtection(ProtectionModuleType.ProcessInjection, ActionType.None); config.AddProtection(ProtectionModuleType.TamperingDetection, ActionType.None); }); // Run application and check logs // Verify detections are accurate // Then switch to Close action for critical threats ``` ### Mobile Development ```csharp await Payload.ConfigureAsync(config => { // Allow debugging on development devices #if DEBUG config.AddProtection(ProtectionModuleType.JailbreakDetection, ActionType.None); config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.None); #else config.AddProtection(ProtectionModuleType.JailbreakDetection, ActionType.Close); config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close); #endif }); ``` ### Web Application Testing ```csharp builder.Services.AddByteHideMonitor(monitor => { var environment = builder.Environment; if (environment.IsDevelopment()) { // Development: detect but don't block monitor.WithProtection(ProtectionModuleType.SqlInjection, ActionType.None); monitor.WithProtection(ProtectionModuleType.CrossSiteScripting, ActionType.None); } else { // Production: block attacks monitor.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block); monitor.WithProtection(ProtectionModuleType.CrossSiteScripting, ActionType.Block); } }); ``` --- ## Combining with Logging ### Backend Analytics ```json { "apiKey": "your-api-key", "logging": { "backend": { "enabled": true } }, "protections": { "DebuggerDetection": { "enabled": true, "action": "none" }, "VirtualMachineDetection": { "enabled": true, "action": "none" } } } ``` All detections will be sent to ByteHide backend for analytics, even with `action: "none"`. ### Local File Logging ```json { "logging": { "file": { "enabled": true, "path": "logs/detections.log", "format": "json" } }, "protections": { "SqlInjection": { "enabled": true, "action": "none" } } } ``` ### Custom Analytics ```csharp config.RegisterCustomAction("custom-analytics", async (threat) => { // Send to your analytics platform await analyticsClient.TrackEventAsync("ThreatDetected", new { Type = threat.ModuleType.ToString(), Description = threat.Description, Confidence = threat.Confidence, Environment = "Production", Action = "None" }); // Don't take any action - just track }); config.AddProtection(ProtectionModuleType.VirtualMachineDetection, "custom-analytics"); ``` --- ## Environment-Based Configuration ```json { "environments": { "development": { "protections": { "DebuggerDetection": { "enabled": true, "action": "none" }, "SqlInjection": { "enabled": true, "action": "none" } } }, "staging": { "protections": { "DebuggerDetection": { "enabled": true, "action": "log" }, "SqlInjection": { "enabled": true, "action": "log" } } }, "production": { "protections": { "DebuggerDetection": { "enabled": true, "action": "close" }, "SqlInjection": { "enabled": true, "action": "block" } } } } } ``` --- ## Best Practices ### 1. Use for Development Only ```csharp // Good: Environment-specific #if DEBUG config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.None); #else config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close); #endif ``` ### 2. Always Enable Logging ```json { "logging": { "file": { "enabled": true, "path": "logs/monitor.log" } }, "protections": { "DebuggerDetection": { "enabled": true, "action": "none" } } } ``` Without logging, `action: "none"` provides no value. ### 3. Transition to Active Actions ```csharp // Phase 1 (Week 1): Monitor config.AddProtection(ProtectionModuleType.TamperingDetection, ActionType.None); // Phase 2 (Week 2): Log config.AddProtection(ProtectionModuleType.TamperingDetection, ActionType.Log); // Phase 3 (Week 3): Enforce config.AddProtection(ProtectionModuleType.TamperingDetection, ActionType.Close); ``` ### 4. Document Why None is Used ```csharp // Using None action for initial analytics gathering // Will switch to Close after 2 weeks of data collection config.AddProtection(ProtectionModuleType.VirtualMachineDetection, ActionType.None); ``` --- ## Comparison with Other Actions | Scenario | None | Log | Close | |----------|------|-----|-------| | Development | ✔ Best | ✔ Good | ❌ Disruptive | | Testing | ✔ Best | ✔ Good | ❌ Disruptive | | Analytics | ✔ Best | ✔ Good | ❌ Loses data | | Production (critical) | ❌ No protection | ⚠️ Weak | ✔ Best | | Production (non-critical) | ❌ No protection | ✔ Best | ⚠️ Too strict | --- ## Related Actions - [Log](/platforms/dotnet/products/monitor/actions/log) - Next step after None - [Close](/platforms/dotnet/products/monitor/actions/close) - Production enforcement - [Custom](/platforms/dotnet/products/monitor/actions/custom) - Custom analytics logic --- # Understand how Monitor actions work Monitor actions define how your application responds when a protection module detects a threat. Each module can be assigned its own action, so you can log low-confidence detections, block confirmed attacks, and terminate the application for critical threats. {% .lead %} --- ## Action Types ### SDK Actions These actions are available in JSON configuration and the Configuration API. They execute inside the application at the point where the threat is detected. | Action | Behavior | Use Case | |--------|----------|----------| | **[Close](actions/close)** | Terminates the application immediately | Critical threats on desktop/mobile (debugger attached, tampering detected) | | **[Log](actions/log)** | Records the incident and continues execution | Non-critical threats, monitoring, analytics | | **[Block](actions/block)** | Blocks the request and returns HTTP 403 | Web/API attacks (SQL injection, XSS, path traversal) | | **[Erase](actions/erase)** | Securely deletes sensitive data, then terminates | Financial or healthcare applications on compromised devices | | **[Custom](actions/custom)** | Executes your own async handler | SIEM integration, Slack alerts, custom escalation workflows | | **[None](actions/none)** | Detects the threat but takes no action | Development, testing, shadow mode before enforcing | ### Cloud Dashboard Actions These actions are available when configuring [Workflow Rules](/platforms/dotnet/products/monitor/cloud-configuration#workflow-rules) in the Cloud Dashboard. They extend the SDK actions with network-level responses. | Action | Behavior | Use Case | |--------|----------|----------| | **Log incident** | Records the incident with full forensic context | Audit trail, compliance, analytics | | **Block** | Blocks the specific request or operation | Stop the attack in progress | | **Block session** | Invalidates the attacker's entire session | Prevent the attacker from continuing with a different payload | | **Block IP** | Blocks all traffic from the source IP address | Stop repeated attacks from the same origin | ![ByteHide Monitor workflow rules showing IF/THEN configuration for Command Injection and SQL Injection with Log, Block, Block session, and Block IP actions](/images/monitor/bytehide-monitor-rules.png) You can combine multiple actions in a single Workflow rule. For example, a SQL Injection rule can Log the incident, Block the request, and Block the IP simultaneously. --- ## Action Selection Guide ### By Threat Severity | Threat Severity | Development | Staging | Production | |----------------|-------------|---------|------------| | **Critical** (Debugger, Tampering) | None / Log | Close | Close | | **High** (Jailbreak, Memory Dump) | Log | Close | Close / Erase | | **Medium** (VM, Emulator) | None | Log | Log / Close | | **Low** (Clock Tampering, Cloud Metadata) | None | Log | Log | ### By Application Type | Application Type | Recommended Actions | |----------|-------------------| | **Desktop** (Console, WPF, WinForms) | Close, Log, Erase, Custom | | **Mobile** (MAUI, Xamarin, Android, iOS) | Close, Log, Custom | | **Web / API** (ASP.NET, Node.js) | Block, Log, Custom | | **IoT / On-Premise** | Close, Log, Custom | ### Common Scenarios | Scenario | Action | Why | |----------|--------|-----| | SQL Injection on a public API | Block | Stop the attack, keep the application running for other users | | Debugger attached in production | Close | Immediate shutdown to prevent reverse engineering | | VM detected on desktop app | Log | Track for analytics without disrupting legitimate users on VMs | | Jailbreak on a banking app | Close | Regulatory requirement, compromised device cannot be trusted | | Tampering detected with sensitive data | Erase | Delete credentials and keys before shutting down | | New protection in shadow mode | None | Observe detections before enforcing in production | | Any threat on a monitored API | Log + Block + Block IP | Full Cloud Dashboard workflow: record, stop, and ban the source | --- ## Configuring Actions Actions can be assigned per protection module from any configuration source: - **[Cloud Dashboard](/platforms/dotnet/products/monitor/cloud-configuration)**: Assign actions in Workflow rules with the IF/THEN editor. Supports all cloud actions including Block session and Block IP. - **[JSON Configuration](/platforms/dotnet/products/monitor/json-configuration)**: Set the `action` field per protection in your configuration file. - **[Configuration API](/platforms/dotnet/products/monitor/configuration-api)**: Pass the action type when registering protections in code. ```json { "protections": { "SqlInjection": { "enabled": true, "action": "block" }, "DebuggerDetection": { "enabled": true, "action": "close" }, "VirtualMachineDetection": { "enabled": true, "action": "log" } } } ``` See [JSON Configuration](/platforms/dotnet/products/monitor/json-configuration) for the full schema reference. --- ## Next Steps --- # Monitor Best Practices Recommendations for deploying ByteHide Monitor effectively in production on .NET. {% .lead %} --- ## Token Security - **Never hardcode tokens** in source code. Use environment variables or secure vaults - **Use separate tokens** for development, staging, and production environments - **Rotate tokens** periodically and after any suspected compromise - **Restrict token scope**: each token should be linked to a single project --- ## Action Strategy ### Development Environment Use permissive actions to avoid disrupting the development workflow: ``` Debugger Detection → NONE (developers use debuggers) Emulator Detection → NONE (testing on emulators) VM Detection → NONE (may develop on VMs) All Others → LOG ``` ### Staging Environment Use logging actions to gather data without blocking: ``` All Protections → LOG ``` Review the incident dashboard to tune which protections to enforce in production. ### Production Environment Use a graduated approach based on threat severity. **Desktop and Mobile protections:** ``` Debugger Detection → CLOSE (high severity) Root/Jailbreak → CLOSE (high severity) Tampering Detection → CLOSE (high severity) Memory Dump Detection → CLOSE (high severity) Process Injection → CLOSE (high severity) Emulator Detection → LOG (medium severity) VM Detection → LOG (medium severity) Clock Tampering → LOG (medium severity) Network Tampering → LOG (medium severity) ``` **Web and Cloud protections:** ``` SQL Injection → BLOCK (high severity) XSS → BLOCK (high severity) Command Injection → BLOCK (high severity) Path Traversal → BLOCK (high severity) SSRF → BLOCK (high severity) NoSQL Injection → BLOCK (high severity) LLM Prompt Injection → LOG (evaluate before enforcing) ``` For web protections, configure [Workflow Rules](/platforms/dotnet/products/monitor/cloud-configuration#workflow-rules) in the Cloud Dashboard to combine actions: Log + Block + Block IP for critical threats. --- ## Protection Selection ### Mobile Applications (Android/iOS) Prioritize these protections: 1. **Root/Jailbreak Detection**: compromised devices are the top mobile threat 2. **Debugger Detection**: prevents dynamic analysis 3. **Tampering Detection**: verifies app integrity 4. **Emulator Detection**: blocks automated analysis ### Desktop Applications Prioritize these protections: 1. **Debugger Detection**: blocks reverse engineering 2. **VM Detection**: prevents sandboxed analysis 3. **Tampering Detection**: verifies binary integrity 4. **Memory Dump Detection**: protects in-memory secrets ### Web Applications (.NET) Prioritize these protections: 1. **SQL Injection**: the most common web attack vector 2. **XSS**: protects user sessions 3. **Path Traversal**: prevents file system access 4. **SSRF**: blocks internal network access --- ## Configuration Management - **Use [cloud configuration](/platforms/dotnet/products/monitor/cloud-configuration) as the primary method**. It allows instant updates without redeploying - **Keep [JSON configuration](/platforms/dotnet/products/monitor/json-configuration) as a fallback** for offline or air-gapped environments - **Use hybrid configuration** in production: cloud for protection rules, [Configuration API](/platforms/dotnet/products/monitor/configuration-api) for custom action handlers - **Version-control your JSON configuration** alongside your application code. Export from the Cloud Dashboard to keep them in sync --- ## Monitoring and Response - **Review the [incident dashboard](/platforms/dotnet/products/monitor/cloud-panel/incidences) regularly**. Look for patterns and anomalies - **Set up [Workflow Rules](/platforms/dotnet/products/monitor/cloud-panel/workflow)** to automate responses with notifications to Slack or webhooks - **Use [custom actions](/platforms/dotnet/products/monitor/custom-actions)** to integrate with your alerting system (PagerDuty, Slack, SIEM) - **Track incident trends**: a sudden spike may indicate an active attack campaign - **Enable [Anomaly Detection](/platforms/dotnet/products/monitor/protections/anomaly-detection)**: it learns normal behavior and flags deviations automatically --- ## Performance Optimization - **Set appropriate intervals**: 60 seconds is a good default for most protections - **Increase intervals for low-risk protections**: VM and emulator detection can run every 120 seconds - **Decrease intervals for high-risk protections**: debugger detection can run every 30 seconds - **Disable irrelevant protections**: don't enable VM detection on mobile devices --- ## Deployment Checklist Before deploying to production: - [ ] Token is stored as an environment variable or secret (not hardcoded) - [ ] Protection modules are selected based on your application type - [ ] Action types are appropriate for production (not all set to `NONE`) - [ ] Logging level is set to `Info` or higher (not `Debug`) - [ ] Cloud configuration is working and accessible - [ ] Incident dashboard is accessible to your security team - [ ] Custom actions are tested and functioning - [ ] CI/CD pipeline includes the token as a secret - [ ] Debug logging is disabled - [ ] Anomaly Detection is enabled --- ## Next Steps --- # Cloud Configuration Configure Monitor protections, response actions, logging, and advanced settings from the ByteHide Cloud Dashboard. Changes sync to your application in real-time without redeployment. {% .lead %} --- ## Overview Cloud configuration is the recommended way to manage Monitor. Instead of editing JSON files or writing code, you define protection rules, response actions, and operational settings from the web dashboard. Every change propagates instantly to all running instances of your application. > **Configuration Priority** > Cloud configuration takes the highest priority. Any configuration applied through the dashboard will override both the protections defined in `monitor.config.json` and those written directly in code. --- ## Workflow Rules The Workflow tab is where you define how Monitor responds to each type of threat. Rules follow an **IF/THEN** pattern: if a specific threat type is detected, then execute one or more actions. ![ByteHide Monitor workflow rules showing IF/THEN configuration for Command Injection and SQL Injection with Log, Block, Block session, and Block IP actions](/images/monitor/bytehide-monitor-rules.png) ### Creating a Rule 1. Go to the **Workflow** tab in your Monitor project 2. Click **+ Add Rule** 3. Select the protection type (SQL Injection, XSS, Command Injection, etc.) 4. Check the actions to execute when this threat is detected: - **Log incident**: Record the incident with full forensic context - **Block**: Block the specific request or operation - **Block session**: Invalidate the attacker's entire session - **Block IP**: Block all traffic from the source IP address ### Notifications Each rule can also trigger notifications: - **Slack**: Connect your Slack workspace to receive real-time alerts when incidents match the rule - **Webhook**: Send incident data to any HTTP endpoint (SIEM, PagerDuty, custom systems) ### Exporting Configuration Click **Export config** to download your current workflow rules as a JSON file. This is useful for: - Version-controlling your configuration alongside your application code - Copying rules between projects - Using as a base for [JSON Configuration](/platforms/dotnet/products/monitor/json-configuration) in offline environments --- ## Advanced Settings Click **Advanced Config** in the Workflow tab to open the advanced configuration panel. These settings control Monitor's operational behavior. ![ByteHide Monitor advanced configuration panel with logging levels, anomaly detection, rate limiting, and debug mode settings](/images/monitor/bytehide-monitor-advanced-rules.png) ### Logging | Setting | Options | Description | |---------|---------|-------------| | **Logging** | On/Off | Enable or disable Monitor logging | | **Minimum Level** | Debug, Info, Warning, Error, Critical | Controls which events are recorded. Use Info for production, Debug for troubleshooting | | **Console Output** | On/Off | Write log events to standard output | | **Debug Logging** | On/Off | Verbose diagnostic output. Not recommended for production | | **Local Logging** | On/Off | Write events to a local log file on disk | | **ByteHide Logs** | On/Off | Send events to [ByteHide Logs](/platforms/dotnet/products/monitor/logging) for centralized, immutable logging. Recommended | ### Anomaly Detection Toggle to enable or disable [Anomaly Detection](/platforms/dotnet/products/monitor/protections/anomaly-detection). When enabled, Monitor automatically learns your application's normal behavior and flags deviations: authentication anomalies, abnormal request rates, unexpected payload structures, and suspicious session activity. Enabled by default. ### Rate Limit Toggle to enable request rate limiting. When enabled, Monitor limits the number of requests processed within a configurable time window, providing protection against brute force and denial of service attempts. ### Debug Mode Enables verbose debugging output and additional diagnostic information. Marked as "Not in production" in the dashboard for a reason: it generates significant overhead and should only be used during development or active troubleshooting. ### Throw On Failure When enabled, Monitor will throw exceptions if it encounters internal errors instead of silently logging them. Useful during development to catch configuration issues early. --- ## Project Settings The Settings tab contains project-level configuration. ![ByteHide Monitor project settings showing project token, session duration configuration, and token reset options](/images/monitor/bytehide-monitor-settings.png) ### Project Token Your project token (`bh_...`) authenticates your application with the ByteHide platform. Copy it into your environment variables or configuration file. ```bash # Set as environment variable export BYTEHIDE_API_TOKEN="bh_your_token_here" ``` See [Create a Monitor Project](/platforms/dotnet/products/monitor/create-monitor-project) for details on token management. ### Session Duration Configure how long a session remains active before expiring. Default is 60 seconds of inactivity. Sessions group related requests and incidents from the same device, making it easier to trace attack patterns. ### Reset Token Generates a new project token and invalidates the previous one. Use this if your token has been compromised or leaked. After resetting, update the token in all deployed applications. ### Unlink Project Removes the Monitor integration from this project. This is a destructive action that cannot be undone. --- ## How Configuration Syncs 1. You make changes in the Cloud Dashboard (workflow rules, advanced settings, firewall rules) 2. Monitor agents running in your applications periodically sync with the ByteHide API 3. Updated configuration is applied immediately, without restarting the application 4. If the application cannot reach the API (offline, network issues), it continues operating with the last known configuration This means your security team can update response policies, add firewall rules, or adjust logging levels across every running instance of your application without involving the development team or redeploying. --- ## Configuration Priority Monitor supports three configuration methods. When multiple are present, they are applied in this priority order: | Priority | Method | When to Use | |----------|--------|-------------| | 1 (highest) | **Cloud Dashboard** | Production. Real-time updates, team collaboration, no code changes | | 2 | **JSON File** (`monitor.config.json`) | Offline environments, air-gapped deployments, version-controlled config | | 3 (lowest) | **Code (Configuration API)** | Custom actions, programmatic logic, development-time defaults | You can combine methods. For example, use the Configuration API to register custom action handlers in code, and use the Cloud Dashboard to assign those handlers to specific protection modules and define escalation rules. --- ## Next Steps --- # Creating a Monitor Project Create a Monitor project to get your project token and start protecting your .NET application. {% .lead %} --- ## Create a Project 1. Go to [cloud.bytehide.com](https://cloud.bytehide.com) and log in 2. Click **+ Create Project** ![ByteHide Cloud dashboard with Create Project button to start a new Monitor project](/images/monitor/bytehide-monitor-create-project.png) 3. Select **.NET** as the language 4. Select **Monitor** as the product ![ByteHide project creation modal showing language and product selection with Monitor highlighted](/images/monitor/bytehide-monitor-select-product.png) 5. Choose the project type: - **On-Premise / IoT / Edge / Mobile**: For desktop applications, mobile apps, IoT devices, and edge computing - **Cloud / API / Web**: For web applications, REST APIs, and cloud services 6. Enter a project name and assign a team 7. Click **Create** The project type determines which protections and firewall features are available. See [Cloud Panel Overview](/platforms/dotnet/products/monitor/cloud-panel) for the differences between project types. --- ## Get Your Token After creation, your project token is available in the [Settings tab](/platforms/dotnet/products/monitor/cloud-panel/settings). Copy it and set it as an environment variable: ```bash export BYTEHIDE_API_TOKEN="bh_your_token_here" ``` > **Token Security** > Never commit tokens to source control. Use environment variables or a secret manager. See [Best Practices](/platforms/dotnet/products/monitor/best-practices#token-security) for token management recommendations. --- ## Next Steps --- # Cloud Firewall Protect your API and web application with multiple firewall layers: bot blocking, threat intelligence feeds, geo-blocking, custom IP blocklists, and user agent filtering. {% .lead %} > **Cloud Projects Only** > This page applies to Cloud / Web / API project types. For Desktop, Mobile, and IoT projects, see [On-Premise Firewall](/platforms/dotnet/products/monitor/cloud-panel/firewall/on-premise). --- ## Firewall Overview The Cloud Firewall is organized into five protection layers. The first three are managed lists provided by ByteHide. The last two are custom blocklists you define. ![ByteHide Monitor Cloud Firewall showing Block Bots, Block Threat Actors, Block Countries cards and custom blocklist options](/images/monitor/bytehide-monitor-firewall-cloud.png) --- ## Block Bots Block known bot user agents across 21 categories. Each category can be toggled individually to Block or Ignore. ![ByteHide Monitor bot blocking modal showing 21 bot categories with Block and Ignore toggles](/images/monitor/bytehide-monitor-firewall-bots.png) Categories include: - **AI Data Scrapers**: AI training crawlers and data collection bots - **Vulnerability Scanners**: Automated security scanning tools - **Data Harvesters**: Content scraping and data extraction bots - **Search Engines**: Google, Bing, Yahoo, and other search engine crawlers - **SEO Crawlers**: SEO analysis and monitoring tools - **Social Media Bots**: Social platform crawlers and preview generators - **Headless Browsers**: Automated browser instances (Puppeteer, Playwright) - And 14 more categories > **Selective Blocking** > You probably want to block AI scrapers and vulnerability scanners but allow search engine crawlers. Toggle each category independently based on your needs. --- ## Block Threat Actors Block IPs from seven threat intelligence feeds maintained by ByteHide. Lists are updated daily at midnight. ![ByteHide Monitor threat actor feeds showing seven intelligence lists with IP counts and Block or Ignore options](/images/monitor/bytehide-monitor-firewall-threat-actors.png) | Feed | Total IPs | Description | |------|-----------|-------------| | **Bruteforce Attackers** | 137,694 | IPs observed performing brute force attacks | | **Public Internet Scanners** | 600,071 | IPs running mass internet scans | | **HTTP DoS Attackers** | 614M+ | IPs involved in HTTP denial of service attacks | | **HTTP Exploit Attackers** | 614M+ | IPs attempting HTTP-based exploits | | **Proxy & VPN** | 357M+ | Known proxy and VPN exit nodes | | **WordPress Attackers** | 614M+ | IPs targeting WordPress vulnerabilities | | **Botnet Actors** | 614M+ | IPs participating in botnet activity | Each feed can be toggled individually to Block or Ignore. Blocking is instant with no performance impact on your application. --- ## Block Countries Block all traffic from specific countries using geo-blocking. Search and select countries from the list. Each blocked country is shown with its flag. ![ByteHide Monitor country blocking modal showing searchable country list with flags and block toggles](/images/monitor/bytehide-monitor-firewall-countries.png) Use cases: - Comply with regulations that restrict service to certain regions - Block traffic from countries where you have no users - Respond to attack campaigns originating from specific regions --- ## Custom IP Blocklist Block specific IP addresses or CIDR ranges. IPs can be added manually or automatically through [Workflow Rules](/platforms/dotnet/products/monitor/cloud-panel/workflow) using the **Block IP** action. ![ByteHide Monitor custom IP blocklist showing input field for adding IPs and CIDR ranges](/images/monitor/bytehide-monitor-firewall-custom-ip.png) Supported formats: - Single IP: `192.168.1.100` - CIDR range: `192.168.1.0/24` When a Workflow rule includes the Block IP action, the attacker's IP is automatically added to this list. --- ## Custom User Agent Blocklist Block traffic matching custom user agent patterns. Patterns support regex for flexible matching. ![ByteHide Monitor custom user agent blocklist showing regex pattern input and blocked user agents list](/images/monitor/bytehide-monitor-firewall-custom-useragent.png) Examples: ``` bot.* # Block anything containing "bot" curl/.* # Block curl requests python-requests/.* # Block Python requests library scrapy/.* # Block Scrapy crawler ``` --- ## Next Steps --- # Firewall Block malicious traffic at the network and device level. The Firewall tab provides different capabilities depending on your project type. {% .lead %} --- ## Firewall by Project Type The Firewall tab adapts to your project type: | Feature | On-Premise / Desktop / Mobile | Cloud / Web / API | |---------|-------------------------------|-------------------| | **Block devices** | Yes (device-level blocklist) | No (use IP/session blocking) | | **Block bots** | No | Yes (390+ user agents, 21 categories) | | **Block threat actor IPs** | No | Yes (600M+ IPs, 7 intelligence feeds) | | **Block by country** | No | Yes (geo-blocking) | | **Custom IP blocklist** | No | Yes (single IPs or CIDR ranges) | | **Custom user agent blocklist** | No | Yes (regex patterns) | All firewall changes apply instantly without restarting your application. --- ## On-Premise Firewall For Desktop, Mobile, and IoT projects, the Firewall tab shows a **Blocked Devices** list. Devices can be blocked manually from the [Device Details](/platforms/dotnet/products/monitor/cloud-panel/overview#device-actions) page or automatically by Workflow rules. ![ByteHide Monitor On-Premise Firewall showing Blocked Devices table with device name, ID, operating system, block reason, and date](/images/monitor/bytehide-monitor-firewall-onpremise.png) | Column | Description | |--------|-------------| | **Device Name** | Name of the blocked device | | **Device ID** | Unique device identifier | | **Operating System** | OS and version of the device | | **Block Reason** | Why the device was blocked | | **Blocked Date** | When the device was blocked | | **Actions** | Unblock button to remove the device from the blocklist | [On-Premise Firewall details](/platforms/dotnet/products/monitor/cloud-panel/firewall/on-premise) --- ## Cloud Firewall For Web and API projects, the Firewall tab provides multiple protection layers that work together to filter malicious traffic before it reaches your application. ![ByteHide Monitor Cloud Firewall showing Block Bots, Block Threat Actors, Block Countries cards and custom blocklist options](/images/monitor/bytehide-monitor-firewall-cloud.png) | Layer | Description | Update Frequency | |-------|-------------|-----------------| | **Block Bots** | Block known bot user agents across 21 categories | Static list | | **Block Threat Actors** | Block IPs from 7 threat intelligence feeds (600M+ IPs) | Updated daily at midnight | | **Block Countries** | Block all traffic from specific countries | Real-time | | **Custom IP Blocklist** | Block specific IP addresses or CIDR ranges | Real-time | | **Custom User Agent Blocklist** | Block traffic matching custom user agent patterns | Real-time | [Cloud Firewall details](/platforms/dotnet/products/monitor/cloud-panel/firewall/cloud) --- ## Next Steps --- # On-Premise Firewall Manage devices that have been blocked due to security policy violations. View block reasons, unblock devices, and understand how devices get added to the blocklist. {% .lead %} > **On-Premise Projects Only** > This page applies to On-Premise, Desktop, Mobile, and IoT project types. For Cloud / Web / API projects, see [Cloud Firewall](/platforms/dotnet/products/monitor/cloud-panel/firewall/cloud). --- ## Blocked Devices The Firewall tab for on-premise projects shows a single table listing all devices that have been blocked. ![ByteHide Monitor On-Premise Firewall showing Blocked Devices table with device name, ID, operating system, block reason, and date](/images/monitor/bytehide-monitor-firewall-onpremise.png) | Column | Description | |--------|-------------| | **Device Name** | Name of the blocked device | | **Device ID** | Unique device identifier (full hash) | | **Operating System** | OS and version (e.g., Windows 10.0.26200.0) | | **Block Reason** | Why the device was blocked (e.g., security policy violation, manual block) | | **Blocked Date** | Timestamp of when the block was applied | | **Actions** | Unblock button to remove the device from the blocklist | --- ## How Devices Get Blocked Devices can be blocked in two ways: ### Manual Block From the [Device Details](/platforms/dotnet/products/monitor/cloud-panel/overview#device-actions) page, click **Block Device** to manually add a device to the firewall blocklist. This is useful when you identify a compromised device through the incident dashboard or session analysis. ### Automatic Block Configure [Workflow Rules](/platforms/dotnet/products/monitor/cloud-panel/workflow) to automatically block devices when specific threats are detected. For example, you can create a rule that blocks any device where Tampering Detection or Debugger Detection triggers with a Close action. --- ## Unblocking a Device To unblock a device: 1. Find the device in the Blocked Devices table 2. Click the unblock button in the Actions column 3. The device is immediately removed from the blocklist and can connect again You can also unblock a device from the [Device Details](/platforms/dotnet/products/monitor/cloud-panel/overview#device-actions) page by clicking **Unblock Device**. --- ## Device Actions In addition to blocking and unblocking, you can take other actions on devices from the Device Details page: | Action | Description | |--------|-------------| | **Clear Memory** | Remotely clear sensitive data from the device's application memory | | **Delete Files** | Remotely wipe application files on the device | | **Block Device** | Add the device to the firewall blocklist | | **Unblock Device** | Remove the device from the firewall blocklist | See [Devices & Sessions](/platforms/dotnet/products/monitor/cloud-panel/overview) for full details on device management. --- ## Next Steps --- # Incidences View all detected security threats in real-time. Every incident includes full context: severity, payload, origin, stacktrace, and AI-powered analysis. {% .lead %} --- ## Incidences Dashboard The Incidences tab shows all threats detected across every device and session running your application. ![ByteHide Monitor Incidences dashboard showing threat statistics cards and incidents table with severity levels, detection types, and actions taken](/images/monitor/bytehide-monitor-incidences.png) ### Statistics Cards Four cards at the top summarize your current security status: | Card | Description | |------|-------------| | **Total Incidences** | Total number of detected threats | | **Critical Threats** | Incidents classified as High or Critical severity | | **Blocked Threats** | Percentage of threats that were automatically mitigated (Block, Close, Erase) | | **Pending Review** | Incidents awaiting manual review | ### Incidences Table Each row represents a detected threat with the following columns: | Column | Description | |--------|-------------| | **Type** | Protection module that triggered the detection (SqlInjection, DebuggerDetection, PathTraversal, etc.) with a color-coded badge | | **Level** | Severity badge: Critical (red), High (orange), Medium (yellow) | | **Description** | Summary of the detected threat | | **Origin** | Source IP address with platform icon | | **Date** | Timestamp of when the threat was detected | | **Action** | Action that was executed: Log (green), Block (red), Close (grey) | | **Options** | Menu with Mark as Read and Delete | --- ## Filters Use the filter bar above the table to narrow down incidents: ![ByteHide Monitor incidence filters showing Date Range, Level, Type, and Action dropdown menus](/images/monitor/bytehide-monitor-incidences-filters.png) | Filter | Options | |--------|---------| | **Date Range** | Custom date range picker | | **Level** | Critical, High, Medium, Low | | **Type** | All protection modules: Command Injection, Cross-Site Scripting (XSS), LDAP Injection, LLM Prompt Injection, NoSQL Injection, Path Traversal, SQL Injection, SSRF, XXE, and all desktop/mobile modules | | **Action** | All, Block, Close, Log | --- ## Incident Details Click any incident row to open the detail panel with full forensic context. ![ByteHide Monitor incident detail panel showing confidence gauge, technical details, SQL injection payload, stacktrace, and origin information](/images/monitor/bytehide-monitor-incident-details.png) ### Incident Information The header displays: - **Confidence gauge**: Semicircular gauge showing the detection confidence percentage (e.g., 90%) - **Severity label**: Critical, High, Medium, or Low - **Protection module**: The type of threat detected (e.g., SqlInjection) - **Detection timestamp** - **Status badge**: Current status of the incident (e.g., TO DO) - **"Help me to understand it"** button: Opens the AI Security Analysis ### Technical Details The technical details vary depending on the protection module type. **Web protection example (SQL Injection):** | Field | Example | |-------|---------| | Module Type | SqlInjection | | User Input | `' OR '1'='1` | | Injected Content | `select from where and or` | | SQL Query | `SELECT * FROM Users WHERE Username = 'admin' AND Password = '' OR '1'='1'` | **Desktop protection example (Debugger Detection):** | Field | Example | |-------|---------| | Module Type | DebuggerDetection | | Payload | Debugger type and detection method | ### Stacktrace A code block showing the execution call chain at the time of detection. This shows exactly which code path was executing when the threat was intercepted, from the Monitor interception point back to the application entry point. ### Origin Information | Field | Description | |-------|-------------| | **IP Address** | Source IP of the request or device | | **Device** | Device or server name | | **User Agent** | Full user agent string | | **Device ID** | Unique device identifier | | **Platform** | Application platform (web, mobile, desktop) | | **Session ID** | Session identifier (for tracking related incidents) | > **Tip** > Review the stacktrace and payload to understand the attack vector. Consider implementing additional validation and sanitization measures for the affected code path. --- ## AI Security Analysis Click **"Help me to understand it"** on any incident to get an AI-powered explanation of the threat. ![ByteHide Monitor AI Security Analysis modal showing attack explanation, business impact, attack vector, and severity analysis](/images/monitor/bytehide-monitor-ai-analysis.png) ### Analysis Tab | Section | Description | |---------|-------------| | **What Happened** | Plain-language explanation of the attack | | **Why It Matters** | Potential business impact: data breaches, compliance violations, reputational damage | | **Attack Vector** | Technique used, entry point, and why it worked | | **Severity Explanation** | Why the incident is rated at its severity level | | **Confidence Level** | AI model confidence in the analysis (High, Medium, Low) | ### Protection Status Tab ![ByteHide Monitor AI Protection Status tab showing current protection level, Monitor capabilities, limitations, and action taken](/images/monitor/bytehide-monitor-ai-protection-status.png) | Section | Description | |---------|-------------| | **Is Protected** | Whether the application is fully protected, partially protected, or in detection-only mode | | **What Monitor Does** | Capabilities of Monitor for this type of threat | | **What Monitor Doesn't Do** | Limitations (Monitor does not fix code, does not modify application logic) | | **Action Taken** | Detailed description of the response action that was executed | | **Configuration Required** | Whether additional configuration is needed to improve protection | --- ## Incident Actions Each incident row has an options menu (three dots) with: - **Mark as Read**: Removes the incident from the Pending Review count - **Delete**: Permanently removes the incident from the dashboard --- ## Next Steps --- # Cloud Panel The Cloud Panel is the web dashboard for managing Monitor projects, monitoring threats in real-time, configuring automated responses, and analyzing security incidents. {% .lead %} --- ![ByteHide Monitor Cloud Panel dashboard showing Incidences tab with threat statistics, severity levels, and detected security incidents](/images/monitor/bytehide-monitor-cloud-panel.png) ## Dashboard Tabs The Cloud Panel is organized into six tabs. Each tab focuses on a specific aspect of your application's runtime security. | Tab | Description | |-----|-------------| | **[Incidences](/platforms/dotnet/products/monitor/cloud-panel/incidences)** | All detected threats with severity, origin, action taken, and AI-powered analysis | | **[Firewall](/platforms/dotnet/products/monitor/cloud-panel/firewall)** | Block bots, threat actor IPs, countries, custom IPs, and user agents | | **[Routes](/platforms/dotnet/products/monitor/cloud-panel/routes)** | API endpoint usage and request patterns (web/cloud projects only) | | **[Overview](/platforms/dotnet/products/monitor/cloud-panel/overview)** | Devices, sessions, geographic distribution map, and recent incidents | | **[Workflow](/platforms/dotnet/products/monitor/cloud-panel/workflow)** | Automation rules (IF threat THEN action) and advanced configuration | | **[Settings](/platforms/dotnet/products/monitor/cloud-panel/settings)** | Project token, session duration, token reset, and project management | --- ## Project Types When creating a Monitor project, you choose the project type based on your application. This determines which protections and firewall features are available. | | On-Premise / Desktop / Mobile | Cloud / Web / API | |--|-------------------------------|-------------------| | **Protections** | 13 passive detectors (debugger, VM, jailbreak, tampering, etc.) | 9 active interceptors (SQL injection, XSS, SSRF, etc.) | | **Actions** | Log, Close, Erase, Notifications | Log, Block, Block session, Block IP, Notifications | | **Firewall** | Device-level blocking | Bots, threat actor IPs, countries, custom IPs, user agents | | **Routes tab** | Not available | Available | Both project types include the Incidences, Firewall, Overview, Workflow, and Settings tabs. See [Protection Modules](/platforms/dotnet/products/monitor/protection-modules) for the full list of available protections. --- ## Getting Started 1. **[Create a Project](/platforms/dotnet/products/monitor/cloud-panel/creating-project)**: Choose your platform and project type 2. **Copy your token**: Get the project token from the Settings tab 3. **Install Monitor**: Add the SDK to your application with the token 4. **Configure rules**: Set up [Workflow Rules](/platforms/dotnet/products/monitor/cloud-panel/workflow) to define automated responses 5. **Monitor incidents**: Threats appear in real-time in the [Incidences](/platforms/dotnet/products/monitor/cloud-panel/incidences) tab --- ## Explore the Cloud Panel --- # Devices & Sessions Monitor every device and server running your application. View geographic distribution, inspect device security status, drill into individual sessions, and take action on compromised devices. {% .lead %} --- ## Overview Dashboard The Overview tab provides a high-level view of all application instances and their activity. ![ByteHide Monitor Overview tab showing device count, sessions graph, geographic map, and last incidences](/images/monitor/bytehide-monitor-overview-dashboard.png) ![ByteHide Monitor Devices table showing status, version, device name, device ID, monitor version, sessions, and blocked status](/images/monitor/bytehide-monitor-overview-devices.png) ### Statistics | Card | Description | |------|-------------| | **Devices** | Total number of devices and servers running your application | | **Sessions** | Session activity graph over the last 30 days | ### Geographic Map An interactive world map showing the geographic location of all devices running your application. Each marker represents a device or server, positioned based on IP geolocation. ### Last Incidences A summary of the 5 most recent security incidents detected across all devices, with the protection module name and timestamp. ### Devices Table | Column | Description | |--------|-------------| | **Status** | Active (green check) or Blocked (red) | | **Version** | Operating system version | | **Device** | Device or server name | | **Device ID** | Unique device identifier (truncated hash) | | **Monitor Version** | Version of the Monitor SDK installed | | **Sessions** | Number of sessions recorded for this device (badge with count) | | **Blocked** | Whether the device is currently blocked (red X if blocked) | | **Details** | View button to open the device detail page | --- ## Device Details Click the view button on any device row to open its detail page. ![ByteHide Monitor Device Detail page showing session info, device info, app info, security status checks, and last incidences](/images/monitor/bytehide-monitor-device-details.png) ### Information Cards **Last Session Info:** - Session ID, IP address, uptime - Country (with flag) and city - Interactive map showing the device location **Device Info:** - IPv4 and IPv6 addresses, uptime, country **App Info:** - Application version and Monitor SDK version ### Security Status Six security checks showing the current state of the device: | Check | Description | |-------|-------------| | **Virtual Machine** | Whether the device is running inside a VM | | **Root Device** | Whether the device is rooted or jailbroken | | **Sandbox** | Whether the application is running in a sandbox | | **Deobfuscator tools** | Whether deobfuscation tools are detected | | **Debugger tools** | Whether debugging tools are attached | | **Intercept packages** | Whether network interception tools are detected | Each check shows a green checkmark (safe) or a red warning (detected). ### Device Actions Actions you can take on a specific device: | Action | Description | |--------|-------------| | **Clear Memory** | Remotely clear sensitive data from the device's application memory | | **Delete Files** | Remotely wipe application files on the device | | **Block Device** | Add the device to the firewall blocklist, preventing further connections | | **Unblock Device** | Remove the device from the firewall blocklist | ### Sessions Table Below the device information, a table lists all sessions recorded for this device: | Column | Description | |--------|-------------| | **Incidences** | Number of incidents in the session. Green badge (0) for clean sessions, orange badge (1+) for sessions with threats | | **Start Hour** | Session start timestamp | | **End Hour** | Session end timestamp | | **View** | View button to open the session detail page | **Filters:** IP Address, Date Range, Incidences. --- ## Session Details Click any session row to open the session detail page with a full timeline of events. ![ByteHide Monitor Session Detail page showing visual timeline with start, threat detected, and end events](/images/monitor/bytehide-monitor-session-details.png) ### Session Timeline A visual horizontal timeline showing: - **Start session** (blue): When the session began, with timestamp - **Threat detected** (red): Each security incident during the session, with protection module name and timestamp - **End session** (blue): When the session ended, with timestamp ### Session Actions Two actions available at the top of the session detail page: - **Block Session**: Invalidate this session immediately - **Block User Agent**: Block the user agent string associated with this session ### Session Incidences Table A filtered table showing only the incidents that occurred during this specific session, with the same columns as the main [Incidences table](/platforms/dotnet/products/monitor/cloud-panel/incidences): Type, Level, Description, Origin, Date, and Status. **Filters:** Date Range, Level, Type, Status. --- ## Next Steps --- # Monitor Project Configuration Configure your Monitor project settings from the ByteHide Cloud panel for centralized management across all your applications. {% .lead %} > **Coming Soon**: This page will include detailed screenshots and step-by-step guides for configuring your Monitor project in the ByteHide Cloud panel. The configuration applies to all applications using the same project token. --- ## Protection Modules Configuration Enable or disable specific protection modules for all applications in your project: ### Desktop & Mobile Modules - **Debugger Detection** - Detect attached debuggers - **Virtual Machine Detection** - Identify VM environments - **Emulator Detection** - Detect emulators and sandboxes - **Jailbreak Detection** - Identify rooted/jailbroken devices - **Clock Tampering** - Detect system clock manipulation - **Memory Dump Detection** - Identify memory dumping attempts ### Web & Cloud Modules - **SQL Injection Protection** - Intercept SQL queries - **XSS Protection** - Validate user input/output - **Path Traversal Protection** - Intercept file operations - **Command Injection Protection** - Validate process execution - **SSRF Protection** - Intercept HTTP requests --- ## Action Policies Configure default actions for different threat types: - **Critical Threats** (Debugger, VM): Close application - **Medium Threats** (Clock Tampering): Log incident - **Low Priority** (Analytics): None (detect only) --- ## Notifications & Alerts Configure how your team receives incident notifications: - **Email Alerts** - Receive emails for specific threat types - **Webhook Integration** - Send incidents to external systems - **Slack/Teams Integration** - Real-time team notifications --- ## Team Access Control Manage who can access your Monitor project: - **Admin** - Full control over project settings - **Developer** - View incidents and analytics - **Viewer** - Read-only access to incidents --- ## Analytics Dashboard View real-time statistics and trends: - **Incident Count** - Total threats detected over time - **Threat Distribution** - Breakdown by module type - **Device Statistics** - Active devices and sessions - **Geographic Distribution** - Where threats are being detected --- ## Next Steps - [Create your first Monitor project](/platforms/dotnet/products/monitor/create-monitor-project) - [Install Monitor in your application](/platforms/dotnet/products/monitor/standalone-installation) - [Configure protection modules in code](/platforms/dotnet/products/monitor/configuration-api) --- # Routes Track all API endpoints your application exposes and their request volumes. Identify which routes receive the most traffic and correlate with incident data to find potential attack surfaces. {% .lead %} > **Cloud Projects Only** > The Routes tab is only available for Cloud / Web / API project types. On-Premise, Desktop, Mobile, and IoT projects do not have HTTP route tracking. --- ## Routes Dashboard ![ByteHide Monitor Routes tab showing total API endpoints, request counts, and route table with HTTP methods](/images/monitor/bytehide-monitor-routes.png) ### Statistics Two cards at the top summarize your API surface: | Card | Description | |------|-------------| | **Total Routes** | Number of unique API endpoints detected | | **Total Requests** | Total request count over the last 7 days | ### Routes Table The table lists every endpoint Monitor has observed, with the following columns: | Column | Description | |--------|-------------| | **Method** | HTTP method badge: GET (green), POST (blue), PUT (yellow), DELETE (red) | | **Route** | API endpoint path (e.g., `/api/users/search`) | | **Total Requests** | Number of requests to this endpoint | Routes are sorted by request volume (most requested first). The table includes pagination for large API surfaces. --- ## How Routes Are Collected Monitor automatically discovers and tracks routes as your application receives requests. No manual configuration is needed. Every HTTP request that passes through Monitor's middleware is recorded with its method and path. This gives you visibility into: - **Your full API surface**: See every endpoint your application exposes, including ones you may not have documented - **Traffic distribution**: Identify which endpoints receive the most traffic - **Attack surface analysis**: Correlate high-traffic endpoints with incidents from the [Incidences tab](/platforms/dotnet/products/monitor/cloud-panel/incidences) to prioritize protection - **Unused endpoints**: Find endpoints with zero or minimal traffic that could be candidates for removal --- ## Next Steps --- # Settings Manage your project token, session configuration, and administrative operations from the Settings tab. {% .lead %} --- ## Settings Tab ![ByteHide Monitor project settings showing project token, session duration configuration, and token reset options](/images/monitor/bytehide-monitor-settings.png) --- ## Project Token Your project token (`bh_...`) authenticates your application with the ByteHide platform. Copy it and set it as an environment variable: ```bash export BYTEHIDE_API_TOKEN="bh_your_token_here" ``` > **Token Security** > Never commit tokens to source control. Use environment variables or a secret manager. See [Best Practices](/platforms/dotnet/products/monitor/best-practices#token-security) for recommendations. The token is displayed partially masked in the dashboard. Click the copy button to copy the full token to your clipboard. --- ## Session Duration Configure how long a session remains active before expiring due to inactivity. The default is **60 seconds**. Sessions group related requests and incidents from the same device or client. A longer session duration means more events are grouped together, making it easier to trace attack patterns across multiple requests. Enter the desired duration in seconds and click **Save**. --- ## Reset Token Generates a new project token and immediately invalidates the previous one. Use this if your token has been compromised or leaked. > **Immediate Impact** > Resetting the token immediately invalidates the old one. All running applications using the old token will lose connectivity with the ByteHide platform until they are updated with the new token. After resetting: 1. Copy the new token from the Settings tab 2. Update the environment variable or configuration file in all deployments 3. Restart or redeploy your applications 4. Verify that devices reappear in the [Overview tab](/platforms/dotnet/products/monitor/cloud-panel/overview) --- ## Danger Zone ### Unlink Project Permanently removes the Monitor integration from this project and deletes all associated data: - All devices and device history - All sessions - All incidents and forensic data - All Workflow rules and firewall configurations - The project token (invalidated) > **Permanent Data Loss** > This action cannot be undone. All data will be permanently deleted. Export your configuration and back up any incident data before unlinking. --- ## Next Steps --- # Workflow Actions Actions define what Monitor does when a Workflow rule matches a detected threat. Multiple actions can be combined in a single rule. {% .lead %} --- ## Actions by Project Type Available actions depend on your project type: | Action | On-Premise | Cloud | Description | |--------|-----------|-------|-------------| | **Log incident** | Yes | Yes | Record the threat in the dashboard and logs without disrupting execution | | **Close app** | Yes | No | Terminate the application immediately | | **Erase app data** | Yes | No | Securely delete sensitive data from memory and disk before terminating | | **Block** | No | Yes | Block the current HTTP request and return 403 Forbidden | | **Block session** | No | Yes | Block all requests from this session ID | | **Block IP** | No | Yes | Block all traffic from the source IP (added to [Custom IP Blocklist](/platforms/dotnet/products/monitor/cloud-panel/firewall/cloud#custom-ip-blocklist)) | | **Send notification** | Yes | Yes | Alert via Slack or Webhook | --- ## On-Premise Actions ### Log Incident Records the threat in the Cloud Panel and local logs. The application continues running normally. Use this for development, low-severity threats, and data collection before deciding which protections to enforce. ### Close App Immediately terminates the application. Use this for critical threats where continued execution is dangerous: debugger attached, tampering detected, jailbreak detected. ### Erase App Data Securely deletes sensitive data from memory and disk, then terminates the application. Use this for applications that handle financial data, credentials, or other sensitive information on compromised devices. --- ## Cloud Actions ### Log Incident Records the threat in the Cloud Panel without blocking the request. The response is sent normally. Use this for monitoring new protections before enforcing, or for low-confidence detections you want to review. ### Block Blocks the current request and returns HTTP 403 Forbidden. The attacker receives a generic blocked response. Use this for confirmed attacks: SQL injection, XSS, path traversal, command injection. ### Block Session Blocks the current request and invalidates the entire session. All future requests with the same session ID are blocked. Use this for persistent attackers who try different payloads within the same session. ### Block IP Blocks the current request and adds the source IP address to the [Custom IP Blocklist](/platforms/dotnet/products/monitor/cloud-panel/firewall/cloud#custom-ip-blocklist) in the Firewall tab. All future traffic from this IP is blocked. Use this for repeated attacks or high-severity threats. --- ## Combining Actions You can select multiple actions in a single Workflow rule. They execute simultaneously when the rule matches. Example for maximum protection on a SQL Injection rule: ``` IF: SQL Injection detected THEN: Log incident Block request Block session Block IP Send notification (Slack + Webhook) ``` This logs the incident for forensic review, blocks the request, invalidates the attacker's session, bans their IP from all future traffic, and notifies your team via Slack and webhook. --- ## Notifications ### Slack Connect your Slack workspace to receive real-time alerts when Workflow rules match. Each notification includes the threat type, severity, action taken, and origin information. 1. Check the **Slack** checkbox on the rule 2. Click **Link Slack with ByteHide** to authorize the integration 3. Select the channel to receive alerts ### Webhook Send incident data to any HTTP endpoint. Monitor sends a POST request with the full incident payload when the rule matches. 1. Check the **Webhook** checkbox on the rule 2. Select a webhook endpoint from the dropdown (or create one) Use webhooks to integrate with SIEM systems (Splunk, ELK, Datadog), ticketing platforms (Jira, ServiceNow, PagerDuty), or custom alerting pipelines. --- ## Related For the full reference of all Monitor action types (including SDK-level actions like Custom and None), see [Actions Overview](/platforms/dotnet/products/monitor/actions). --- # Advanced Configuration Configure Monitor's operational behavior from the Cloud Panel. These settings control logging, error handling, anomaly detection, and rate limiting. Changes apply in real-time without restarting your application. {% .lead %} --- ## Access Open the **Workflow** tab and click the **Advanced Config** button in the top right corner. ![ByteHide Monitor advanced configuration panel with logging levels, anomaly detection, rate limiting, and debug mode settings](/images/monitor/bytehide-monitor-advanced-rules.png) > **Configuration Priority** > Advanced Configuration settings in the Cloud Panel override JSON and code-based configuration. See [Configuration Priority](/platforms/dotnet/products/monitor/cloud-configuration#configuration-priority) for details. --- ## Logging Configuration ### Minimum Level Select the minimum severity level for log output. Events below this level are discarded. | Level | Use case | |-------|----------| | **Trace** | Maximum detail, framework internals | | **Debug** | Development troubleshooting | | **Info** | General operational events | | **Warning** | Potential issues that need attention | | **Error** | Failures that need investigation | **Recommended:** `info` or `warning` for production. `debug` for development only. ### Console Output Toggle console logging to stdout/stderr. Enable this when running in containers (Docker, Kubernetes) or cloud environments where logs are collected from stdout (CloudWatch, Azure Monitor, Google Cloud Logging). ### Local Logging (File) Toggle file-based logging with automatic rotation. - **File Path:** `logs/bytehide-monitor.log` - **Max Size:** 10 MB per file before rotation ### ByteHide Logs Integration Send Monitor logs to [ByteHide Logs](/platforms/dotnet/products/logs) for encrypted cloud storage with AI-powered analysis and data masking. 1. Toggle **ByteHide Logs** on 2. Select your Logs project from the dropdown (or create one) For the full logging reference including log levels, output destinations, and sensitive data masking, see [Logging](/platforms/dotnet/products/monitor/logging). --- ## Throw On Failure > **Use with caution** > When enabled, any Monitor service error (network timeout, API failure, configuration error) will crash the application instead of logging the error and continuing. Only enable this in development to catch integration issues early. **Default:** Disabled. Monitor logs errors internally and continues normal execution. --- ## Debug Mode > **Never enable in production** > Debug mode includes detailed threat information in HTTP responses, which exposes your security configuration to attackers. See [Debug Logging](/platforms/dotnet/products/monitor/logging#debug-logging) for what gets exposed and why it matters. Toggle verbose request/response logging for development troubleshooting. When enabled, blocked responses include the full `threatInfo` object with protection module, confidence score, and matched patterns. --- ## Anomaly Detection AI-powered detection of unusual patterns that don't match a specific attack signature but indicate suspicious behavior. Detects: - **IP address changes mid-session** - Same session ID used from different IPs - **Geographic impossibilities** - Requests from locations that are physically impossible given the time between them - **Request pattern anomalies** - Unusual request frequency, timing, or sequencing When anomalies are detected, they appear as incidents in the [Incidences](/platforms/dotnet/products/monitor/cloud-panel/incidences) tab and can trigger [Workflow Rules](/platforms/dotnet/products/monitor/cloud-panel/workflow). --- ## Rate Limiting Limit the number of requests per IP address within a time window. Requests that exceed the limit receive HTTP `429 Too Many Requests`. | Setting | Description | Default | |---------|-------------|---------| | **Max Requests** | Maximum requests allowed per IP | 100 | | **Time Window** | Time period in milliseconds | 60000 (1 minute) | Example: With the defaults, each IP can make up to 100 requests per minute. The 101st request within the same minute window returns 429. --- ## Next Steps --- # Workflow Define automatic actions when threats are detected. Create IF/THEN rules that respond to each type of threat with logging, blocking, notifications, or custom workflows. Changes apply in real-time. {% .lead %} --- > **Configuration Priority** > Workflow rules configured in the Cloud Panel override both `monitor.config.json` and code-based configuration. See [Configuration Priority](/platforms/dotnet/products/monitor/cloud-configuration#configuration-priority) for details. ## Workflow Rules The Workflow tab lists all active automation rules for your project, with three buttons in the top right: - **+ Add Rule**: Create a new automation rule - **Export config**: Download all rules as a JSON file - **Advanced Config**: Open the advanced configuration panel **Cloud / Web / API projects:** ![ByteHide Monitor Workflow rules for cloud projects showing IF/THEN configuration with Log, Block, Block session, and Block IP actions](/images/monitor/bytehide-monitor-workflow-cloud.png) **On-Premise / Desktop / Mobile projects:** ![ByteHide Monitor Workflow rules for on-premise projects showing IF/THEN configuration with Log, Close, and Erase actions](/images/monitor/bytehide-monitor-workflow-onpremise.png) ### Creating a Rule Each rule follows an **IF/THEN** pattern: 1. Click **+ Add Rule** 2. **IF**: Select the protection module (SQL Injection, Debugger Detection, Command Injection, etc.) 3. **THEN**: Check the actions to execute when this threat is detected Available actions depend on your project type: | Action | On-Premise | Cloud | |--------|-----------|-------| | **Log incident** | Yes | Yes | | **Close app** | Yes | No | | **Erase app data** | Yes | No | | **Block request** | No | Yes | | **Block session** | No | Yes | | **Block IP** | No | Yes | You can select multiple actions per rule. For example, a SQL Injection rule can Log the incident, Block the request, and Block the IP simultaneously. ### Deleting a Rule Click the trash icon on any rule to remove it. The change applies immediately. --- ## Notifications Each rule can trigger notifications to alert your team in real-time. ### Slack 1. Check the **Slack** checkbox on the rule 2. Click **Link Slack with ByteHide** to connect your workspace 3. Select the channel to receive alerts ### Webhook 1. Check the **Webhook** checkbox on the rule 2. Select a webhook from the dropdown (or create one) 3. Monitor sends a POST request with the full incident data to your endpoint Use webhooks to integrate with: - SIEM systems (Splunk, ELK, Datadog) - Ticketing (Jira, ServiceNow, PagerDuty) - Custom alerting pipelines --- ## Export Configuration Click **Export config** to download your current workflow rules as a JSON file. This is useful for: - Version-controlling your security configuration - Copying rules between projects - Using as a base for [JSON Configuration](/platforms/dotnet/products/monitor/json-configuration) in offline environments --- ## Advanced Configuration Click **Advanced Config** to open the advanced settings panel. These settings control Monitor's operational behavior beyond individual threat rules. ![ByteHide Monitor advanced configuration panel with logging levels, anomaly detection, rate limiting, and debug mode settings](/images/monitor/bytehide-monitor-advanced-rules.png) See [Advanced Configuration](/platforms/dotnet/products/monitor/cloud-panel/workflow/advanced-configuration) for the full reference of all settings. --- ## Next Steps --- # .NET Configuration API Monitor for .NET provides a fluent configuration API for standalone applications and middleware integration for ASP.NET Core. {% .lead %} --- ## Standalone Configuration (Console, Desktop, Mobile, IoT) Use `Bytehide.Monitor.Payload.ConfigureAsync` for non-web applications: ```csharp using Bytehide.Monitor.Core.Actions; using Bytehide.Monitor.Core.Protection; await Bytehide.Monitor.Payload.ConfigureAsync(config => { // Enable all protections with a default action config.EnableAllProtections(ActionType.Close, intervalMs: 60000); }); ``` ### Protection Group Methods ```csharp // Enable all protections (desktop + mobile + web) config.EnableAllProtections(ActionType.Close, intervalMs: 60000); // Enable only desktop-specific protections config.EnableDesktopProtections(ActionType.Close, intervalMs: 60000); // Enable only mobile-specific protections config.EnableMobileProtections(ActionType.Close, intervalMs: 60000); ``` ### Individual Protection Selection ```csharp config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close, intervalMs: 30000); config.AddProtection(ProtectionModuleType.VirtualMachineDetection, ActionType.Close, intervalMs: 120000); config.AddProtection(ProtectionModuleType.EmulatorDetection, ActionType.Log, intervalMs: 60000); config.AddProtection(ProtectionModuleType.JailbreakDetection, ActionType.Close, intervalMs: 60000); config.AddProtection(ProtectionModuleType.ClockTampering, ActionType.Log, intervalMs: 60000); config.AddProtection(ProtectionModuleType.MemoryDumpDetection, ActionType.Close, intervalMs: 60000); config.AddProtection(ProtectionModuleType.TamperingDetection, ActionType.Close, intervalMs: 60000); config.AddProtection(ProtectionModuleType.ProcessInjection, ActionType.Close, intervalMs: 60000); config.AddProtection(ProtectionModuleType.NetworkTampering, ActionType.Log, intervalMs: 60000); ``` --- ## ASP.NET Core Configuration Use dependency injection and middleware for web applications: ```csharp // Program.cs builder.Services.AddByteHideMonitor(monitor => monitor .WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block) .WithProtection(ProtectionModuleType.CrossSiteScripting, ActionType.Block) .WithProtection(ProtectionModuleType.PathTraversal, ActionType.Block) .WithProtection(ProtectionModuleType.CommandInjection, ActionType.Block) .WithProtection(ProtectionModuleType.ServerSideRequestForgery, ActionType.Block) .WithProtection(ProtectionModuleType.LdapInjection, ActionType.Block) .WithProtection(ProtectionModuleType.XmlExternalEntity, ActionType.Block) .WithProtection(ProtectionModuleType.NoSqlInjection, ActionType.Block) .WithProtection(ProtectionModuleType.LlmPromptInjection, ActionType.Block) ); // Add middleware to the pipeline app.UseByteHideMonitor(); ``` --- ## Custom Action Handlers Create custom threat response logic with named handlers: ```csharp config.RegisterCustomAction("secure-shutdown", async (threat) => { // 1. Log incident await LogIncidentAsync(threat); // 2. Encrypt sensitive data await EncryptSensitiveDataAsync(); // 3. Notify administrators await NotifyAdminsAsync(threat); // 4. Secure shutdown await SecureShutdownAsync(); }); config.EnableDesktopProtections( action: "secure-shutdown", intervalMs: 60000 ); ``` ### Inline Custom Actions ```csharp config.AddProtection( ProtectionModuleType.DebuggerDetection, "secure-shutdown", intervalMs: 30000 ); ``` --- ## Available Action Types | Type | Description | Use Case | |---|---|---| | **Close** | Terminates application immediately | Critical threats | | **Log** | Logs incident locally and to backend | Monitoring and analytics | | **None** | Detects but takes no action | Testing and development | | **Block** | Blocks the specific operation | Web interceptors (SQL injection, XSS) | | **Erase** | Erases sensitive data before closing | Data protection scenarios | | **Custom** | Executes your custom handler | Advanced scenarios | --- ## Configuration Loading Order When combining cloud, JSON, and programmatic configuration: 1. Monitor checks for `monitor-config.json` in the application directory 2. If no JSON file, fetches configuration from cloud (dashboard) 3. Applies programmatic configuration (`ConfigureAsync` / `AddByteHideMonitor`) 4. Programmatic configuration overrides automatic configuration --- # Create a Monitor Project ## What are ByteHide Monitor Projects? ByteHide Monitor projects are the foundation for organizing and managing runtime protection across your applications. Projects allow you to: - **Organize your applications** by service or environment - **Configure protection modules** (Debugger Detection, VM Detection, SQL Injection, etc.) - **Define action responses** for detected threats - **Monitor security incidents** in real-time - **Control access** for team members with different permission levels - **View analytics** on detected threats and protection effectiveness - **Manage device sessions** and track deployment statistics Each project provides a unique token that authenticates your applications with the ByteHide Monitor service. --- ## Create Your Project 1. Sign in to [ByteHide Cloud](https://cloud.bytehide.com) 2. Go to **Projects** section 3. Click **Create Project** in the dashboard > **Coming Soon**: Screenshots will be added here showing the exact UI flow for creating a Monitor project. 4. Select **Monitor** as the project type 5. Choose **.NET** as your platform 6. Enter a project name and description 7. Click **Create** --- ## Get Your Project Token > **Security Notice** > Keep your project token secure and never commit it to source control. Use environment variables or secret managers like ByteHide Secrets to store it safely. After creating your project, you'll need the project token for your applications: 1. Go to your Monitor project dashboard 2. In the main view you will see the **Project Token** box 3. Copy your project token > **Coming Soon**: Screenshot showing where to find the project token in the ByteHide Cloud panel. --- ## Storing Your Token Securely ### Option 1: Environment Variables ```bash # Windows (PowerShell) $env:BYTEHIDE_MONITOR_TOKEN="your-token-here" # Linux/macOS export BYTEHIDE_MONITOR_TOKEN="your-token-here" ``` Then in your code: ```csharp await Bytehide.Monitor.Payload.ConfigureAsync(config => { config.EnableAllProtections(ActionType.Close, intervalMs: 60000); }); ``` ### Option 2: User Secrets (Development) ```bash dotnet user-secrets set "ByteHide:Monitor:Token" "your-token-here" ``` ```csharp // In Program.cs or Startup.cs await Bytehide.Monitor.Payload.ConfigureAsync(config => { config.EnableAllProtections(ActionType.Close, intervalMs: 60000); }); ``` ### Option 3: ByteHide Secrets (Recommended for Production) Use ByteHide Secrets Manager to securely store and retrieve your Monitor token: ```csharp await Bytehide.Monitor.Payload.ConfigureAsync(config => { config.EnableAllProtections(ActionType.Close, intervalMs: 60000); }); ``` --- ## Project Settings In the ByteHide Cloud panel, you can configure: - **Protection Modules**: Enable/disable specific detection modules - **Action Policies**: Configure default actions for different threat types - **Access Control**: Manage team access and permissions - **Notifications**: Configure alerts for security incidents - **Analytics**: View threat detection statistics and trends - **Device Management**: Monitor registered devices and active sessions > **Coming Soon**: Detailed documentation on configuring each setting in the ByteHide Cloud panel will be added here with screenshots. --- ## Next Steps Choose your application type to get started: - [Desktop Applications](/platforms/dotnet/products/monitor/standalone-installation) — Console, WPF, WinForms applications - [Mobile Applications](/platforms/dotnet/products/monitor/mobile-installation) — MAUI and Xamarin applications - [Web Applications](/platforms/dotnet/products/monitor/aspnet-core-installation) — ASP.NET Core applications - [IoT Applications](/platforms/dotnet/products/monitor/iot-installation) — Embedded and edge devices --- # Monitor Custom Actions Create sophisticated custom threat response actions for enterprise security workflows. {% .lead %} --- > **Coming Soon** > Detailed custom action patterns and examples are being written. ## Overview Custom actions allow you to define exactly how your application responds to security threats, enabling integration with: - SIEM systems (Splunk, QRadar, Azure Sentinel) - Incident management (PagerDuty, Opsgenie) - Communication platforms (Slack, Teams, Email) - Forensic tools - Custom logging systems --- ## Basic Custom Action ```csharp config.RegisterCustomAction("enterprise-response", async (threat) => { // 1. Log to SIEM await LogToSiemAsync(threat); // 2. Notify security team await SendSecurityAlertAsync(threat); // 3. Create forensic snapshot await CreateForensicSnapshotAsync(); // 4. Terminate safely Environment.Exit(-1); }); config.AddProtection( ProtectionModuleType.DebuggerDetection, "enterprise-response", intervalMs: 30000 ); ``` --- ## Common Patterns ### SIEM Integration ```csharp config.RegisterCustomAction("siem-integration", async (threat) => { var syslogClient = new SyslogClient("siem.company.com", 514); await syslogClient.SendAsync(new { Severity = "CRITICAL", Application = "MyApp", ThreatType = threat.ModuleType.ToString(), Description = threat.Description, Timestamp = DateTime.UtcNow }); Environment.Exit(-1); }); ``` --- ### Slack Notification ```csharp config.RegisterCustomAction("slack-alert", async (threat) => { var webhookUrl = "https://hooks.slack.com/services/YOUR/WEBHOOK/URL"; var payload = new { text = $"🚨 Security Threat Detected", attachments = new[] { new { color = "danger", fields = new[] { new { title = "Threat", value = threat.Description, @short = false }, new { title = "Module", value = threat.ModuleType.ToString(), @short = true }, new { title = "Time", value = threat.DetectedAt.ToString(), @short = true } } } } }; using var http = new HttpClient(); await http.PostAsJsonAsync(webhookUrl, payload); Environment.Exit(-1); }); ``` --- ## Next Steps --- # ASP.NET Core Installation Install ByteHide Monitor in your ASP.NET Core application using dependency injection and middleware for real-time web protection. {% .lead %} --- ## Requirements - **ASP.NET Core** 3.1, 5.0, 6.0, 7.0, 8.0, or 9.0 - **NuGet**: `ByteHide.Monitor` package --- ## Step 1: Install the Package ```bash dotnet add package ByteHide.Monitor ``` ## Step 2: Configure Services In your `Program.cs` (or `Startup.cs` for older projects): ```csharp builder.Services.AddByteHideMonitor(monitor => { // Enable web protection modules monitor.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block); monitor.WithProtection(ProtectionModuleType.CrossSiteScripting, ActionType.Block); monitor.WithProtection(ProtectionModuleType.PathTraversal, ActionType.Block); monitor.WithProtection(ProtectionModuleType.CommandInjection, ActionType.Block); monitor.WithProtection(ProtectionModuleType.ServerSideRequestForgery, ActionType.Block); }); ``` ## Step 3: Add Middleware ```csharp app.UseByteHideMonitor(); ``` Place it early in the middleware pipeline, before `app.UseRouting()` and `app.UseAuthorization()`, so Monitor can intercept requests before they reach your application logic. ## Step 4: Run ```bash dotnet run ``` Monitor is now intercepting and validating all incoming requests against the enabled protection modules. --- ## Full Example (Program.cs) ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddByteHideMonitor(monitor => { monitor.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block); monitor.WithProtection(ProtectionModuleType.CrossSiteScripting, ActionType.Block); monitor.WithProtection(ProtectionModuleType.PathTraversal, ActionType.Block); monitor.WithProtection(ProtectionModuleType.ServerSideRequestForgery, ActionType.Block); monitor.WithProtection(ProtectionModuleType.NoSqlInjection, ActionType.Block); monitor.WithProtection(ProtectionModuleType.LdapInjection, ActionType.Block); monitor.WithProtection(ProtectionModuleType.XmlExternalEntity, ActionType.Block); monitor.WithProtection(ProtectionModuleType.CommandInjection, ActionType.Block); monitor.WithProtection(ProtectionModuleType.LlmPromptInjection, ActionType.Block); }); var app = builder.Build(); app.UseByteHideMonitor(); app.UseRouting(); app.UseAuthorization(); app.MapControllers(); app.Run(); ``` --- ## Combining with Desktop Protections You can enable both web interceptors and desktop protection modules in the same ASP.NET Core application: ```csharp builder.Services.AddByteHideMonitor(monitor => { // Web protections (middleware-based) monitor.WithProtection(ProtectionModuleType.SqlInjection, ActionType.Block); monitor.WithProtection(ProtectionModuleType.CrossSiteScripting, ActionType.Block); }); // Additionally enable desktop protections (background checks) await Bytehide.Monitor.Payload.ConfigureAsync(config => { config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close, intervalMs: 60000); config.AddProtection(ProtectionModuleType.TamperingDetection, ActionType.Log, intervalMs: 120000); }); ``` --- ## Next Steps - [Configuration API reference](/platforms/dotnet/products/monitor/configuration-api) - [JSON Configuration](/platforms/dotnet/products/monitor/json-configuration) - [All protection modules](/platforms/dotnet/products/monitor/protection-modules) - [CI/CD & Docker setup](/platforms/dotnet/products/monitor/installation/cicd) --- # ASP.NET Framework Installation Install ByteHide Monitor in your ASP.NET Framework application for runtime web protection. {% .lead %} --- ## Requirements - **.NET Framework** 4.6.2 or later - **NuGet**: `ByteHide.Monitor` package - ASP.NET Web API or MVC application --- ## Step 1: Install the Package Via NuGet Package Manager Console: ``` Install-Package ByteHide.Monitor ``` Or via .NET CLI: ```bash dotnet add package ByteHide.Monitor ``` ## Step 2: Configure in Global.asax ```csharp using Bytehide.Monitor.Core.Actions; using Bytehide.Monitor.Core.Protection; protected void Application_Start() { // Standard ASP.NET setup AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); // Configure ByteHide Monitor Task.Run(async () => { await Bytehide.Monitor.Payload.ConfigureAsync(config => { config.EnableAllProtections(ActionType.Close, intervalMs: 60000); }); }).Wait(); } ``` ## Step 3: Run Build and run your project. Monitor is now active and protecting your application. --- ## Next Steps - [Configuration API reference](/platforms/dotnet/products/monitor/configuration-api) - [All protection modules](/platforms/dotnet/products/monitor/protection-modules) - [CI/CD setup](/platforms/dotnet/products/monitor/installation/cicd) --- # .NET CI/CD & Docker Integration Integrate ByteHide Monitor into your .NET CI/CD pipeline for automated protected builds. {% .lead %} --- ## Overview Monitor is included as a NuGet package, so it is restored and built automatically in your CI/CD pipeline. No special build steps are needed. Just ensure your project builds successfully. If you use cloud configuration, set the `BYTEHIDE_TOKEN` environment variable so the application can fetch its configuration at runtime. --- ## GitHub Actions ```yaml name: Build .NET App on: push: branches: [main] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Setup .NET uses: actions/setup-dotnet@v4 with: dotnet-version: '8.0.x' - name: Restore & Build run: dotnet build --configuration Release - name: Test run: dotnet test --configuration Release --no-build - name: Publish run: dotnet publish --configuration Release --output ./publish ``` --- ## Docker ```dockerfile FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /src COPY . . RUN dotnet restore RUN dotnet publish -c Release -o /app FROM mcr.microsoft.com/dotnet/aspnet:8.0 WORKDIR /app COPY --from=build /app . # Set token for cloud configuration (or use monitor-config.json) ENV BYTEHIDE_TOKEN="" ENTRYPOINT ["dotnet", "YourApp.dll"] ``` > **Token in Docker** > For Docker deployments, pass the token at runtime via environment variable rather than baking it into the image: `docker run -e BYTEHIDE_TOKEN=your-token your-image`. --- ## Azure DevOps ```yaml trigger: - main pool: vmImage: 'ubuntu-latest' steps: - task: UseDotNet@2 inputs: packageType: 'sdk' version: '8.0.x' - script: dotnet build --configuration Release displayName: 'Build' - script: dotnet test --configuration Release --no-build displayName: 'Test' - script: dotnet publish --configuration Release --output $(Build.ArtifactStagingDirectory) displayName: 'Publish' - task: PublishBuildArtifacts@1 inputs: pathToPublish: $(Build.ArtifactStagingDirectory) artifactName: 'app' ``` --- ## GitLab CI ```yaml build_dotnet: stage: build image: mcr.microsoft.com/dotnet/sdk:8.0 script: - dotnet restore - dotnet build --configuration Release - dotnet publish --configuration Release --output ./publish artifacts: paths: - publish/ ``` --- ## Key Points - Monitor is a standard NuGet package, no special build steps required - For cloud configuration, ensure `BYTEHIDE_TOKEN` is available at runtime (not build time) - For JSON configuration, include `monitor-config.json` in your published output - Store tokens as secrets in your CI/CD platform. Never commit them to source control --- # Desktop Application Installation Install ByteHide Monitor in your .NET desktop application for runtime protection against debuggers, VM detection, tampering, and more. {% .lead %} --- ## Requirements - **.NET** 6.0+ or .NET Framework 4.6.2+ - **NuGet**: `ByteHide.Monitor` package - Application type: Console, WPF, WinForms, or any standalone .NET application --- ## Step 1: Install the Package ```bash dotnet add package ByteHide.Monitor ``` ## Step 2: Configure Monitor ### Console Application ```csharp using Bytehide.Monitor.Core.Actions; using Bytehide.Monitor.Core.Protection; class Program { static async Task Main(string[] args) { await Bytehide.Monitor.Payload.ConfigureAsync(config => { config.EnableDesktopProtections(ActionType.Close, intervalMs: 60000); }); // Your application logic Console.WriteLine("Application running with Monitor protection"); Console.ReadKey(); } } ``` ### WPF Application ```csharp using Bytehide.Monitor.Core.Actions; public partial class App : Application { protected override async void OnStartup(StartupEventArgs e) { base.OnStartup(e); await Bytehide.Monitor.Payload.ConfigureAsync(config => { config.EnableDesktopProtections(ActionType.Close, intervalMs: 60000); }); } } ``` ### WinForms Application ```csharp using Bytehide.Monitor.Core.Actions; static class Program { [STAThread] static async Task Main() { await Bytehide.Monitor.Payload.ConfigureAsync(config => { config.EnableDesktopProtections(ActionType.Close, intervalMs: 60000); }); ApplicationConfiguration.Initialize(); Application.Run(new MainForm()); } } ``` ## Step 3: Run ```bash dotnet run ``` Monitor is now active and running background detection checks at the configured interval. --- ## Recommended Protections for Desktop ```csharp config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close, intervalMs: 30000); config.AddProtection(ProtectionModuleType.VirtualMachineDetection, ActionType.Close, intervalMs: 120000); config.AddProtection(ProtectionModuleType.TamperingDetection, ActionType.Close, intervalMs: 60000); config.AddProtection(ProtectionModuleType.ProcessInjection, ActionType.Close, intervalMs: 60000); config.AddProtection(ProtectionModuleType.MemoryDumpDetection, ActionType.Close, intervalMs: 60000); config.AddProtection(ProtectionModuleType.RemoteDesktop, ActionType.Log, intervalMs: 60000); ``` --- ## Next Steps - [Configuration API reference](/platforms/dotnet/products/monitor/configuration-api) - [All protection modules](/platforms/dotnet/products/monitor/protection-modules) - [CI/CD setup](/platforms/dotnet/products/monitor/installation/cicd) --- # Mobile Application Installation (MAUI/Xamarin) Install ByteHide Monitor in your .NET MAUI or Xamarin mobile application for runtime protection against mobile-specific threats. {% .lead %} --- ## Requirements - **.NET MAUI** (.NET 7+) or **Xamarin** (Xamarin.Forms 5.0+) - **NuGet**: `ByteHide.Monitor` package - Target platforms: Android and/or iOS --- ## Step 1: Install the Package ```bash dotnet add package ByteHide.Monitor ``` ## Step 2: Configure Monitor ### .NET MAUI ```csharp using Bytehide.Monitor.Core.Actions; public static class MauiProgram { public static MauiApp CreateMauiApp() { var builder = MauiApp.CreateBuilder(); builder.UseMauiApp(); // Configure Monitor Task.Run(async () => { await Bytehide.Monitor.Payload.ConfigureAsync(config => { config.EnableMobileProtections(ActionType.Close, intervalMs: 60000); }); }); return builder.Build(); } } ``` ### Xamarin.Forms ```csharp using Bytehide.Monitor.Core.Actions; public partial class App : Application { public App() { InitializeComponent(); Task.Run(async () => { await Bytehide.Monitor.Payload.ConfigureAsync(config => { config.EnableMobileProtections(ActionType.Close, intervalMs: 60000); }); }); MainPage = new MainPage(); } } ``` ## Step 3: Build and Deploy ```bash dotnet build -f net8.0-android dotnet build -f net8.0-ios ``` --- ## Recommended Protections for Mobile ```csharp config.AddProtection(ProtectionModuleType.JailbreakDetection, ActionType.Close, intervalMs: 60000); config.AddProtection(ProtectionModuleType.DebuggerDetection, ActionType.Close, intervalMs: 30000); config.AddProtection(ProtectionModuleType.EmulatorDetection, ActionType.Log, intervalMs: 120000); config.AddProtection(ProtectionModuleType.TamperingDetection, ActionType.Close, intervalMs: 60000); config.AddProtection(ProtectionModuleType.NetworkTampering, ActionType.Log, intervalMs: 60000); config.AddProtection(ProtectionModuleType.MemoryDumpDetection, ActionType.Close, intervalMs: 60000); ``` --- ## Next Steps - [Configuration API reference](/platforms/dotnet/products/monitor/configuration-api) - [All protection modules](/platforms/dotnet/products/monitor/protection-modules) - [CI/CD setup](/platforms/dotnet/products/monitor/installation/cicd) --- # Agent CLI Reference The `bytehide-agent` CLI manages the ByteHide Server Agent. Use it to install, configure, monitor, and uninstall the agent. {% .lead %} --- ## Commands | Command | Description | |---------|-------------| | `bytehide-agent install` | Install the agent and configure protection | | `bytehide-agent uninstall` | Remove the agent completely | | `bytehide-agent status` | Show current agent status | | `bytehide-agent config` | View or modify configuration | | `bytehide-agent logs` | View agent logs | | `bytehide-agent --version` | Show version | | `bytehide-agent --help` | Show help | --- ## install Installs the agent DLLs, sets environment variables, and writes the default configuration. ```bash bytehide-agent install --token [--force] ``` | Option | Description | |--------|-------------| | `--token`, `-t` | **(required)** Your ByteHide API token | | `--force`, `-f` | Reinstall even if already installed | ### What it does 1. Extracts agent DLLs to the install directory 2. Creates the log directory 3. Sets system-wide environment variables (`DOTNET_STARTUP_HOOKS`, `ASPNETCORE_HOSTINGSTARTUPASSEMBLIES`, `BYTEHIDE_MONITOR_TOKEN`, `BYTEHIDE_MONITOR_CONFIG`) 4. Writes `monitor.config.json` with default settings ### Example ```bash $ sudo bytehide-agent install --token bh_LYkAhiIrlXQMHALfU8NDILAKx0K9oDcPQ ── Installing ByteHide Server Agent ── [1/4] Extracting agent files... OK (7 files) [2/4] Creating directories... OK [3/4] Configuring environment... OK [4/4] Writing configuration... OK ✓ ByteHide Server Agent installed successfully! Install path: /opt/bytehide/agent Hook DLL: /opt/bytehide/agent/Bytehide.Monitor.ServerAgent.dll Config: /opt/bytehide/agent/monitor.config.json Logs: /opt/bytehide/agent/logs IMPORTANT: Restart any running .NET applications for protection to take effect. ``` --- ## uninstall Removes the agent completely: deletes DLLs, removes environment variables, and cleans up configuration files. ```bash bytehide-agent uninstall [--yes] ``` | Option | Description | |--------|-------------| | `--yes`, `-y` | Skip confirmation prompt | ### Example ```bash $ sudo bytehide-agent uninstall ── Uninstalling ByteHide Server Agent ── Are you sure you want to uninstall? This will remove all protection. [y/N] y [1/2] Removing environment variables... OK [2/2] Removing agent files... OK ✓ ByteHide Server Agent uninstalled. Running applications will continue to be protected until they are restarted. ``` --- ## status Shows the current installation state, environment variables, and protection status. ```bash bytehide-agent status ``` ### Example ```bash $ bytehide-agent status ── ByteHide Server Agent Status ── Installed: Yes Install path: /opt/bytehide/agent Agent files: 7 DLLs Environment Variables: DOTNET_STARTUP_HOOKS = /opt/bytehide/agent/Bytehide.Monitor.ServerAgent.dll ASPNETCORE_HOSTINGSTARTUPASSEMBLIES = Bytehide.Monitor.ServerAgent BYTEHIDE_MONITOR_TOKEN = bh_LYk...oDcPQ Protection: Active — all new .NET processes are protected Config file: /opt/bytehide/agent/monitor.config.json Log files: 2 file(s) in /opt/bytehide/agent/logs ``` ### Status Indicators | Status | Meaning | |--------|---------| | **Active** | Agent is installed and environment variables are configured correctly | | **Inactive** | Agent files exist but environment variables are missing or incorrect | | **Disabled** | Agent is installed but `BYTEHIDE_DISABLE=true` is set | | **Not installed** | No agent files found | --- ## config View or modify agent configuration. ### Show configuration ```bash bytehide-agent config show ``` Displays the contents of `monitor.config.json`: ```json { "token": "bh_LYkAhiIrlXQMHALfU8NDILAKx0K9oDcPQ", "logging": { "console": true, "level": "info", "file": { "enabled": true, "path": "/opt/bytehide/agent/logs/monitor.log", "maxSizeMB": 50 } } } ``` ### Set a configuration value ```bash bytehide-agent config set ``` | Key | Description | Example | |-----|-------------|---------| | `token` | Update your ByteHide API token | `bytehide-agent config set token bh_newtoken` | | `debug` | Enable/disable debug logging | `bytehide-agent config set debug true` | | `disabled` | Disable agent without uninstalling | `bytehide-agent config set disabled true` | ### Examples **Change token:** ```bash $ bytehide-agent config set token bh_newtoken123 Token updated. Restart .NET applications for changes to take effect. ``` **Enable debug mode:** ```bash $ bytehide-agent config set debug true Debug mode set to: true ``` **Temporarily disable protection:** ```bash $ bytehide-agent config set disabled true Agent disabled. New .NET processes will NOT be protected. ``` **Re-enable protection:** ```bash $ bytehide-agent config set disabled false Agent enabled. New .NET processes will be protected. ``` --- ## logs View agent logs from protected applications. ```bash bytehide-agent logs [--follow] [--lines ] ``` | Option | Default | Description | |--------|---------|-------------| | `--follow`, `-f` | `false` | Follow log output in real-time (like `tail -f`) | | `--lines`, `-n` | `50` | Number of lines to show | ### Examples **Show last 50 lines:** ```bash bytehide-agent logs ``` **Show last 100 lines:** ```bash bytehide-agent logs --lines 100 ``` **Follow logs in real-time:** ```bash bytehide-agent logs --follow ``` --- ## Install Paths | Platform | Agent DLLs | CLI Binary | |----------|-----------|------------| | **Linux** | `/opt/bytehide/agent/` | `/usr/local/bin/bytehide-agent` | | **macOS** | `/usr/local/share/bytehide/agent/` | `/usr/local/bin/bytehide-agent` | | **Windows** | `C:\Program Files\ByteHide\Agent\` | `C:\Program Files\ByteHide\CLI\bytehide-agent.exe` | --- ## Environment Variables These are the environment variables managed by the agent: | Variable | Description | |----------|-------------| | `DOTNET_STARTUP_HOOKS` | Path to the startup hook DLL. Set by `install`, removed by `uninstall`. | | `ASPNETCORE_HOSTINGSTARTUPASSEMBLIES` | Assembly name for ASP.NET Core hosting startup. | | `BYTEHIDE_MONITOR_TOKEN` | Your ByteHide API token. Changed via `config set token`. | | `BYTEHIDE_MONITOR_CONFIG` | Path to `monitor.config.json`. | | `BYTEHIDE_DISABLE` | Set to `true` to disable protection. Changed via `config set disabled`. | | `BYTEHIDE_DEBUG` | Set to `true` for verbose debug output. Changed via `config set debug`. | --- ## Common Workflows ### Update token on a running server ```bash bytehide-agent config set token bh_newtoken # Then restart your apps sudo systemctl restart myapp ``` ### Temporarily disable protection for debugging ```bash bytehide-agent config set disabled true # Restart your app without protection sudo systemctl restart myapp # Re-enable when done bytehide-agent config set disabled false sudo systemctl restart myapp ``` ### Check if agent is working ```bash # 1. Check install status bytehide-agent status # 2. Enable debug mode bytehide-agent config set debug true # 3. Restart your app and check logs sudo systemctl restart myapp bytehide-agent logs --follow # 4. Look for: [ByteHide Server Agent] Initialized (PID: xxxxx) ``` --- ## Next Steps - [Server Agent Overview](/platforms/dotnet/products/monitor/installation/server-agent) - What is the Server Agent - [JSON Configuration](/platforms/dotnet/products/monitor/json-configuration) - Customize protection rules - [Troubleshooting](/platforms/dotnet/products/monitor/troubleshooting) - General troubleshooting guide --- # Server Agent - Docker Install the ByteHide Server Agent inside Docker containers for zero-code runtime protection. The agent is installed at image build time and protects all .NET 6+ processes in the container. {% .lead %} --- ## Key Difference vs Bare Metal On a normal server, you run the installer once and it persists permanently. In Docker, the install happens at **image build time**, and you need to explicitly load the environment variables because Docker doesn't source `/etc/profile.d/` or read the Windows Registry at runtime. --- ## Linux Containers ### Shell Script (No SDK Needed in Runtime Image) ```dockerfile FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /src COPY . . RUN dotnet publish -c Release -o /app FROM mcr.microsoft.com/dotnet/aspnet:8.0 WORKDIR /app COPY --from=build /app . # Install ByteHide Agent RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates \ && rm -rf /var/lib/apt/lists/* \ && curl -sSL https://raw.githubusercontent.com/bytehide/monitor-dotnet-agent/main/install.sh \ | bash -s -- --token # Docker doesn't source /etc/profile.d/, so load env vars in entrypoint ENTRYPOINT ["/bin/bash", "-c", "source /etc/profile.d/bytehide-agent.sh && exec dotnet myapp.dll"] ``` ### dotnet tool (If SDK Available in Build Stage) ```dockerfile FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /src COPY . . RUN dotnet publish -c Release -o /app # Install agent in the build stage (has SDK) RUN dotnet tool install -g Bytehide.Monitor.AgentCli --version 1.0.5 \ && /root/.dotnet/tools/bytehide-agent install --token FROM mcr.microsoft.com/dotnet/aspnet:8.0 WORKDIR /app COPY --from=build /app . # Copy agent files from build stage COPY --from=build /opt/bytehide/agent /opt/bytehide/agent COPY --from=build /etc/profile.d/bytehide-agent.sh /etc/profile.d/bytehide-agent.sh ENTRYPOINT ["/bin/bash", "-c", "source /etc/profile.d/bytehide-agent.sh && exec dotnet myapp.dll"] ``` ### Alpine Linux The installer auto-detects musl/Alpine. The only difference is using `apk` instead of `apt`: ```dockerfile FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine WORKDIR /app COPY --from=build /app . RUN apk add --no-cache curl bash \ && curl -sSL https://raw.githubusercontent.com/bytehide/monitor-dotnet-agent/main/install.sh \ | bash -s -- --token ENTRYPOINT ["/bin/bash", "-c", "source /etc/profile.d/bytehide-agent.sh && exec dotnet myapp.dll"] ``` --- ## Windows Containers ### Windows Server Core ```dockerfile FROM mcr.microsoft.com/dotnet/sdk:8.0-windowsservercore-ltsc2022 AS build WORKDIR /src COPY . . RUN dotnet publish -c Release -o /app FROM mcr.microsoft.com/dotnet/aspnet:8.0-windowsservercore-ltsc2022 WORKDIR /app COPY /app . # Install ByteHide Agent SHELL ["powershell", "-Command"] RUN & ([scriptblock]::Create((Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/bytehide/monitor-dotnet-agent/main/install.ps1' -UseBasicParsing).Content)) -Token '' # Docker doesn't propagate Registry changes to runtime. Set env vars explicitly: ENV DOTNET_STARTUP_HOOKS="C:\\Program Files\\ByteHide\\Agent\\Bytehide.Monitor.ServerAgent.dll" ENV ASPNETCORE_HOSTINGSTARTUPASSEMBLIES="Bytehide.Monitor.ServerAgent" ENV BYTEHIDE_MONITOR_TOKEN="" ENV BYTEHIDE_MONITOR_CONFIG="C:\\Program Files\\ByteHide\\Agent\\monitor.config.json" ENTRYPOINT ["dotnet", "myapp.dll"] ``` ### Windows Nano Server Nano Server doesn't have PowerShell by default. Use the dotnet tool approach in a multi-stage build: ```dockerfile FROM mcr.microsoft.com/dotnet/sdk:8.0-nanoserver-ltsc2022 AS build WORKDIR /src COPY . . RUN dotnet publish -c Release -o /app # Install agent (SDK available in build stage) RUN dotnet tool install -g Bytehide.Monitor.AgentCli --version 1.0.5 RUN bytehide-agent install --token FROM mcr.microsoft.com/dotnet/aspnet:8.0-nanoserver-ltsc2022 WORKDIR /app COPY --from=build /app . # Copy agent DLLs from build stage COPY --from=build ["C:/Program Files/ByteHide/Agent", "C:/Program Files/ByteHide/Agent"] ENV DOTNET_STARTUP_HOOKS="C:\\Program Files\\ByteHide\\Agent\\Bytehide.Monitor.ServerAgent.dll" ENV ASPNETCORE_HOSTINGSTARTUPASSEMBLIES="Bytehide.Monitor.ServerAgent" ENV BYTEHIDE_MONITOR_TOKEN="" ENV BYTEHIDE_MONITOR_CONFIG="C:\\Program Files\\ByteHide\\Agent\\monitor.config.json" ENTRYPOINT ["dotnet", "myapp.dll"] ``` --- ## Docker Compose ### Environment Variables via .env File Instead of hardcoding the token in the Dockerfile, use Docker Compose with an env file: **docker-compose.yml:** ```yaml services: myapp: build: . env_file: - bytehide.env ports: - "8080:8080" ``` **bytehide.env:** ```env DOTNET_STARTUP_HOOKS=/opt/bytehide/agent/Bytehide.Monitor.ServerAgent.dll ASPNETCORE_HOSTINGSTARTUPASSEMBLIES=Bytehide.Monitor.ServerAgent BYTEHIDE_MONITOR_TOKEN=bh_xxxxxxxxxxxx BYTEHIDE_MONITOR_CONFIG=/opt/bytehide/agent/monitor.config.json ``` This way the Dockerfile only installs the agent files, and the environment variables come from Compose. Useful when the token differs per environment (staging, production). --- ## Build Arguments for Tokens Avoid hardcoding tokens in the Dockerfile: ```dockerfile ARG BYTEHIDE_TOKEN RUN curl -sSL https://raw.githubusercontent.com/bytehide/monitor-dotnet-agent/main/install.sh \ | bash -s -- --token ${BYTEHIDE_TOKEN} ``` Build with: ```bash docker build --build-arg BYTEHIDE_TOKEN=bh_xxxxxxxxxxxx -t myapp . ``` Or in CI/CD, inject from a secret: ```bash docker build --build-arg BYTEHIDE_TOKEN=${{ secrets.BYTEHIDE_TOKEN }} -t myapp . ``` --- ## Verifying the Agent in Docker After building and running the container: ```bash # Check if the agent files are in the image docker run --rm myapp ls /opt/bytehide/agent/ # Check if environment variables are set docker run --rm myapp printenv | grep -E "DOTNET_STARTUP|BYTEHIDE|ASPNETCORE_HOSTING" # Run the app and check for the agent init message docker run --rm -e BYTEHIDE_DEBUG=true myapp # Look for: [ByteHide Server Agent] Initialized (PID: xxxxx) ``` --- ## Platform Summary | Container OS | Install Method | Env Vars | |-------------|---------------|----------| | Linux (Debian/Ubuntu) | `curl \| bash` install.sh | `source /etc/profile.d/bytehide-agent.sh` in entrypoint | | Linux (Alpine) | `curl \| bash` install.sh (auto-detects musl) | `source /etc/profile.d/bytehide-agent.sh` in entrypoint | | Windows Server Core | PowerShell install.ps1 | `ENV` in Dockerfile | | Windows Nano Server | `dotnet tool install` + multi-stage copy | `ENV` in Dockerfile | --- ## Troubleshooting ### Agent not loading in container 1. Check the entrypoint sources the env vars: ```bash docker run --rm myapp printenv DOTNET_STARTUP_HOOKS ``` If empty, the entrypoint isn't loading them. 2. For Linux containers, make sure the entrypoint uses bash: ```dockerfile # Wrong - doesn't source profile ENTRYPOINT ["dotnet", "myapp.dll"] # Correct - sources profile first ENTRYPOINT ["/bin/bash", "-c", "source /etc/profile.d/bytehide-agent.sh && exec dotnet myapp.dll"] ``` 3. For Windows containers, `ENV` in Dockerfile is the most reliable approach. ### curl not found Some minimal images don't include curl. Install it first: `apt-get install -y curl ca-certificates` (Debian/Ubuntu) or `apk add --no-cache curl bash` (Alpine). ### Permission denied during install The agent installs to `/opt/bytehide/agent/` which requires root. Docker `RUN` commands run as root by default. If you're using a non-root user: ```dockerfile USER root RUN curl -sSL ... | bash -s -- --token USER appuser ``` --- ## Next Steps - [Agent CLI Reference](/platforms/dotnet/products/monitor/installation/server-agent/agent-cli) - Manage the agent (status, config, logs, uninstall) - [JSON Configuration](/platforms/dotnet/products/monitor/json-configuration) - Customize protection rules - [Windows Installation](/platforms/dotnet/products/monitor/installation/server-agent/windows) - Install on Windows Server - [Linux & macOS Installation](/platforms/dotnet/products/monitor/installation/server-agent/linux-mac) - Install on bare metal --- # Server Agent Overview The ByteHide Server Agent protects all .NET applications on a server automatically. Install once, restart your apps, and every .NET 6+ process gets runtime protection without any code changes. {% .lead %} --- ## What Is the Server Agent? The Server Agent is an alternative to the [in-app NuGet package](/platforms/dotnet/products/monitor/installation/aspnet-core) installation. Instead of adding a dependency to each project, you install a system-wide agent that hooks into every .NET process on the machine. | Feature | In-App (NuGet) | Server Agent | |---------|---------------|--------------| | Installation | Per-project NuGet package | One-time system install | | Code changes | Add package + configure | None | | Scope | Single application | All .NET apps on the server | | Best for | Fine-grained per-app control | Blanket server protection | | Supported frameworks | .NET 6+, .NET Framework 4.6.2+ | .NET 6+ | --- ## How It Works The agent uses two .NET runtime mechanisms to inject protection automatically: 1. **`DOTNET_STARTUP_HOOKS`** - The .NET runtime loads the agent DLL before `Main()` in every .NET process. This works for all .NET 6+ applications: console apps, web APIs, services, and more. 2. **`ASPNETCORE_HOSTINGSTARTUPASSEMBLIES`** - For ASP.NET Core apps, the agent registers middleware (WAF, request inspection) via `IHostingStartup` without any code changes. Since the environment variables are set at the **system level**, every .NET process picks them up automatically: - IIS application pools - Windows Services - systemd services - Console applications - Apps launched from any terminal --- ## Installation Guides Choose the guide that matches your server environment: --- ## Agent CLI Reference After installation, use the `bytehide-agent` CLI to manage the agent: ```bash bytehide-agent status # Check if agent is installed and active bytehide-agent config show # View current configuration bytehide-agent logs # View agent logs ``` See the [Agent CLI Reference](/platforms/dotnet/products/monitor/installation/server-agent/agent-cli) for all available commands. --- ## Configuration The agent reads its protection rules from `monitor.config.json`, created automatically during installation. You can customize protections using the same JSON schema as the in-app configuration. See [JSON Configuration](/platforms/dotnet/products/monitor/json-configuration) for the full schema reference. --- ## Next Steps - [Windows Installation](/platforms/dotnet/products/monitor/installation/server-agent/windows) - Install on Windows Server - [Linux & macOS Installation](/platforms/dotnet/products/monitor/installation/server-agent/linux-mac) - Install on Linux or macOS - [Docker Installation](/platforms/dotnet/products/monitor/installation/server-agent/docker) - Install in Docker containers - [Agent CLI Reference](/platforms/dotnet/products/monitor/installation/server-agent/agent-cli) - All CLI commands --- # Server Agent - Linux & macOS Install the ByteHide Server Agent on Linux or macOS for zero-code runtime protection of all .NET applications. Install once, and every .NET 6+ process on the machine is automatically protected. {% .lead %} --- ## Requirements - Linux (x64, ARM64, Alpine) or macOS (x64, Apple Silicon) - .NET 6+ runtime installed (for the apps you want to protect) - `curl` or `wget` - `sudo` access (for writing to `/opt/` and `/etc/`) - A ByteHide account with a Monitor project ([create one here](/platforms/dotnet/products/monitor/cloud-panel/creating-project)) - Your **ByteHide Project Token** from [app.bytehide.com](https://app.bytehide.com) --- ## Option 1: Shell Script (Recommended) No .NET SDK required. Downloads a self-contained binary from GitHub. ```bash curl -sSL https://raw.githubusercontent.com/bytehide/monitor-dotnet-agent/main/install.sh | bash -s -- --token bh_xxxxxxxxxxxx ``` This single command: 1. Detects your OS and architecture automatically 2. Downloads the correct binary from GitHub Releases 3. Extracts agent DLLs to the install directory 4. Configures environment variables system-wide 5. Installs `bytehide-agent` to `/usr/local/bin/` ### Script Options | Option | Default | Description | |--------|---------|-------------| | `--token`, `-t` | *(required)* | Your ByteHide API token | | `--version` | `1.0.5` | Agent version to install | | `--install-dir` | `/usr/local/bin` | Where to place the CLI binary | | `--no-install` | `false` | Only download binary, don't run install | ### Private Hosting If you host the binary on a private server: ```bash BYTEHIDE_AGENT_URL=https://your-server.com/bytehide-agent-1.0.5-linux-x64.tar.gz \ curl -sSL https://raw.githubusercontent.com/bytehide/monitor-dotnet-agent/main/install.sh | bash -s -- --token bh_xxxxxxxxxxxx ``` --- ## Option 2: dotnet tool Requires the .NET SDK installed on the server. ```bash # Install the CLI tool dotnet tool install -g Bytehide.Monitor.AgentCli # Run the agent installer bytehide-agent install --token bh_xxxxxxxxxxxx ``` If using a private NuGet feed: ```bash dotnet nuget add source "https://pkgs.dev.azure.com/bytehide/Monitor/_packaging/bytehide-monitor-enterprise/nuget/v3/index.json" \ --name bytehide --username bytehide --password "YOUR_PAT" --store-password-in-clear-text dotnet tool install -g Bytehide.Monitor.AgentCli --version 1.0.5 bytehide-agent install --token bh_xxxxxxxxxxxx ``` --- ## What Gets Installed ### Linux | Item | Path | |------|------| | Agent DLLs | `/opt/bytehide/agent/` | | CLI binary | `/usr/local/bin/bytehide-agent` | | Configuration | `/opt/bytehide/agent/monitor.config.json` | | Logs | `/opt/bytehide/agent/logs/` | ### macOS | Item | Path | |------|------| | Agent DLLs | `/usr/local/share/bytehide/agent/` | | CLI binary | `/usr/local/bin/bytehide-agent` | | Configuration | `/usr/local/share/bytehide/agent/monitor.config.json` | | Logs | `/usr/local/share/bytehide/agent/logs/` | ### Environment Variables The installer configures environment variables in multiple locations to cover all scenarios: **Linux:** | File | Purpose | |------|---------| | `/etc/profile.d/bytehide-agent.sh` | Interactive shell sessions (SSH, bash) | | `/etc/environment.d/bytehide-agent.conf` | systemd services | | `/etc/environment` | Universal fallback | **macOS:** | File | Purpose | |------|---------| | `/etc/zshenv` | All zsh sessions (default shell on macOS) | | `launchctl setenv` | Immediate effect in current session | ### Variables Set | Variable | Value (Linux) | |----------|---------------| | `DOTNET_STARTUP_HOOKS` | `/opt/bytehide/agent/Bytehide.Monitor.ServerAgent.dll` | | `ASPNETCORE_HOSTINGSTARTUPASSEMBLIES` | `Bytehide.Monitor.ServerAgent` | | `BYTEHIDE_MONITOR_TOKEN` | Your token | | `BYTEHIDE_MONITOR_CONFIG` | `/opt/bytehide/agent/monitor.config.json` | --- ## Verify Installation ```bash bytehide-agent status ``` Expected output: ``` Installed: Yes Install path: /opt/bytehide/agent Agent files: 7 DLLs Environment Variables: DOTNET_STARTUP_HOOKS = /opt/bytehide/agent/Bytehide.Monitor.ServerAgent.dll ASPNETCORE_HOSTINGSTARTUPASSEMBLIES = Bytehide.Monitor.ServerAgent BYTEHIDE_MONITOR_TOKEN = bh_xxx...xxxx Protection: Active — all new .NET processes are protected ``` > **Restart Required** > After installing the agent, you must **restart** any running .NET applications for protection to take effect. Existing processes do not pick up environment variable changes automatically. --- ## Platform-Specific Notes ### systemd Services For .NET apps running as systemd services, the agent environment is loaded automatically from `/etc/environment.d/bytehide-agent.conf`. No changes to your service files needed. If you want to set variables per-service instead of system-wide: ```ini [Service] Environment=DOTNET_STARTUP_HOOKS=/opt/bytehide/agent/Bytehide.Monitor.ServerAgent.dll Environment=ASPNETCORE_HOSTINGSTARTUPASSEMBLIES=Bytehide.Monitor.ServerAgent Environment=BYTEHIDE_MONITOR_TOKEN=bh_xxxxxxxxxxxx ``` ### Alpine Linux (musl) The installer automatically detects Alpine/musl and downloads the `linux-musl-x64` binary. No extra configuration needed. ### SSH Sessions After installing, new SSH sessions automatically pick up the environment variables from `/etc/profile.d/bytehide-agent.sh`. For the current session: ```bash source /etc/profile.d/bytehide-agent.sh ``` --- ## Supported Platforms | Platform | Architecture | RID | |----------|-------------|-----| | Linux (glibc) | x64 | `linux-x64` | | Linux (glibc) | ARM64 | `linux-arm64` | | Linux (musl/Alpine) | x64 | `linux-musl-x64` | | macOS | Intel | `osx-x64` | | macOS | Apple Silicon | `osx-arm64` | --- ## Troubleshooting ### Agent not loading 1. Check that environment variables are set: ```bash echo $DOTNET_STARTUP_HOOKS ``` If empty, source the profile: ```bash source /etc/profile.d/bytehide-agent.sh ``` 2. Verify the DLL exists: ```bash ls -la /opt/bytehide/agent/Bytehide.Monitor.ServerAgent.dll ``` 3. Make sure you **restarted** the application after installing the agent. ### Permission errors Run with `sudo`: ```bash curl -sSL https://raw.githubusercontent.com/bytehide/monitor-dotnet-agent/main/install.sh | sudo bash -s -- --token bh_xxxxxxxxxxxx ``` ### systemd service not picking up variables Reload systemd after install: ```bash sudo systemctl daemon-reload sudo systemctl restart your-app.service ``` --- ## Next Steps - [Agent CLI Reference](/platforms/dotnet/products/monitor/installation/server-agent/agent-cli) - Manage the agent (status, config, logs, uninstall) - [JSON Configuration](/platforms/dotnet/products/monitor/json-configuration) - Customize protection rules - [Docker Installation](/platforms/dotnet/products/monitor/installation/server-agent/docker) - Install in Docker containers --- # Server Agent - Windows Install the ByteHide Server Agent on Windows for zero-code runtime protection of all .NET applications. Install once, and every .NET 6+ process on the machine is automatically protected. {% .lead %} --- ## Requirements - Windows Server 2019, 2022, or 2025 (or Windows 10/11) - .NET 6+ runtime installed (for the apps you want to protect) - PowerShell running as **Administrator** - A ByteHide account with a Monitor project ([create one here](/platforms/dotnet/products/monitor/cloud-panel/creating-project)) - Your **ByteHide Project Token** from [app.bytehide.com](https://app.bytehide.com) --- ## Option 1: PowerShell Script (Recommended) No .NET SDK required. Downloads a self-contained binary from GitHub. ```powershell & ([scriptblock]::Create((irm https://raw.githubusercontent.com/bytehide/monitor-dotnet-agent/main/install.ps1))) -Token "bh_xxxxxxxxxxxx" ``` This single command: 1. Downloads the `bytehide-agent.exe` binary for Windows x64 2. Extracts agent DLLs to `C:\Program Files\ByteHide\Agent\` 3. Sets machine-level environment variables (Registry) 4. Installs `bytehide-agent.exe` to `C:\Program Files\ByteHide\CLI\` and adds it to PATH 5. Loads environment variables into the current PowerShell session ### Script Options | Parameter | Default | Description | |-----------|---------|-------------| | `-Token` | *(prompted)* | Your ByteHide API token | | `-Version` | `1.0.5` | Agent version to install | | `-InstallDir` | `C:\Program Files\ByteHide\CLI` | Where to place the CLI binary | | `-NoInstall` | `false` | Only download binary, don't run install | ### Private Hosting If you host the binary on a private server: ```powershell $env:BYTEHIDE_AGENT_URL = "https://your-server.com/bytehide-agent-1.0.5-win-x64.zip" & ([scriptblock]::Create((irm https://raw.githubusercontent.com/bytehide/monitor-dotnet-agent/main/install.ps1))) -Token "bh_xxxxxxxxxxxx" ``` --- ## Option 2: dotnet tool Requires the .NET SDK installed on the server. ```powershell # Install the CLI tool dotnet tool install -g Bytehide.Monitor.AgentCli # Run the agent installer bytehide-agent install --token bh_xxxxxxxxxxxx ``` If using a private NuGet feed: ```powershell dotnet nuget add source "https://pkgs.dev.azure.com/bytehide/Monitor/_packaging/bytehide-monitor-enterprise/nuget/v3/index.json" ` --name bytehide --username bytehide --password "YOUR_PAT" --store-password-in-clear-text dotnet tool install -g Bytehide.Monitor.AgentCli --version 1.0.5 bytehide-agent install --token bh_xxxxxxxxxxxx ``` --- ## What Gets Installed | Item | Path | |------|------| | Agent DLLs | `C:\Program Files\ByteHide\Agent\` | | CLI binary | `C:\Program Files\ByteHide\CLI\bytehide-agent.exe` | | Configuration | `C:\Program Files\ByteHide\Agent\monitor.config.json` | | Logs | `C:\Program Files\ByteHide\Agent\logs\` | ### Environment Variables (Registry, Machine Level) | Variable | Value | |----------|-------| | `DOTNET_STARTUP_HOOKS` | `C:\Program Files\ByteHide\Agent\Bytehide.Monitor.ServerAgent.dll` | | `ASPNETCORE_HOSTINGSTARTUPASSEMBLIES` | `Bytehide.Monitor.ServerAgent` | | `BYTEHIDE_MONITOR_TOKEN` | Your token | | `BYTEHIDE_MONITOR_CONFIG` | `C:\Program Files\ByteHide\Agent\monitor.config.json` | --- ## Verify Installation ```powershell bytehide-agent status ``` Expected output: ``` Installed: Yes Install path: C:\Program Files\ByteHide\Agent Agent files: 7 DLLs Environment Variables: DOTNET_STARTUP_HOOKS = C:\Program Files\ByteHide\Agent\Bytehide.Monitor.ServerAgent.dll ASPNETCORE_HOSTINGSTARTUPASSEMBLIES = Bytehide.Monitor.ServerAgent BYTEHIDE_MONITOR_TOKEN = bh_xxx...xxxx Protection: Active — all new .NET processes are protected ``` > **Restart Required** > After installing the agent, you must **restart** any running .NET applications for protection to take effect. Existing processes do not pick up Registry changes automatically. --- ## IIS Configuration For IIS-hosted applications, the machine-level environment variables apply automatically. No additional IIS configuration is needed. If you need to set variables per-application instead of machine-wide, use `web.config`: ```xml ``` --- ## Troubleshooting ### Agent not loading 1. Check that environment variables are set: ```powershell [Environment]::GetEnvironmentVariable("DOTNET_STARTUP_HOOKS", "Machine") ``` 2. Verify the DLL exists: ```powershell Test-Path "C:\Program Files\ByteHide\Agent\Bytehide.Monitor.ServerAgent.dll" ``` 3. Make sure you **restarted** the application after installing the agent. Existing processes don't pick up Registry changes. 4. For the current PowerShell session, env vars are loaded automatically by `install.ps1`. If you opened a new terminal after install, the vars are inherited from the Registry. ### Permission errors during install Run PowerShell as Administrator. The installer needs admin rights to write to `C:\Program Files\` and set machine-level environment variables in the Registry. ### Antivirus blocking If Windows Defender or another antivirus blocks the agent DLLs, add an exclusion for `C:\Program Files\ByteHide\Agent\`. --- ## Next Steps - [Agent CLI Reference](/platforms/dotnet/products/monitor/installation/server-agent/agent-cli) - Manage the agent (status, config, logs, uninstall) - [JSON Configuration](/platforms/dotnet/products/monitor/json-configuration) - Customize protection rules - [Docker Installation](/platforms/dotnet/products/monitor/installation/server-agent/docker) - Install in Docker containers --- # JSON Configuration Configure Monitor using local JSON configuration files. Ideal for version-controlled setups, offline environments, and CI/CD pipelines. {% .lead %} --- ## Overview JSON configuration lets you define protections, logging, rate limiting, and other Monitor settings in a file that lives alongside your application code. This is useful for: - **Version control**: Track configuration changes in git alongside your codebase - **Environment-specific configs**: Different files per environment (dev, staging, production) - **Offline deployments**: No dependency on the ByteHide Cloud API - **CI/CD pipelines**: Automate configuration as part of your build and deploy process > **Configuration Priority** > When multiple configuration sources are present, they are applied in this priority order: **Cloud Dashboard** (highest) > **JSON File** > **Code (Configuration API)** (lowest). Cloud configuration overrides JSON settings. See [Cloud Configuration](/platforms/dotnet/products/monitor/cloud-configuration) for details. > **Export from Cloud Dashboard** > If you already have rules configured in the Cloud Dashboard, click **Export config** in the Workflow tab to download them as a JSON file. This gives you a ready-to-use configuration file that matches your current cloud setup. --- ## Configuration Files Monitor searches for configuration files in your project root directory, in this order: 1. `monitor.config.json` 2. `bytehide.monitor.json` 3. `bytehide.monitor.config.json` 4. `monitor-config.json` 5. `bytehide-monitor-config.json` The first file found is used. Place any one of these in your project root directory. --- ## Basic Configuration ### Desktop/Mobile Application ```json { "name": "My Desktop App", "enabled": true, "projectToken": "${BYTEHIDE_API_TOKEN}", "preset": "desktop", "protections": { "DebuggerDetection": { "enabled": true, "action": "close" }, "VirtualMachineDetection": { "enabled": true, "action": "log" } } } ``` ### Web Application ```json { "name": "My Web API", "enabled": true, "projectToken": "${BYTEHIDE_API_TOKEN}", "preset": "cloud", "protections": { "SqlInjection": { "enabled": true, "action": "block" }, "CrossSiteScripting": { "enabled": true, "action": "block" }, "PathTraversal": { "enabled": true, "action": "block" } } } ``` --- ## Complete Schema Reference ### Root Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `name` | string | - | Configuration name/description | | `enabled` | boolean | `true` | Enable/disable monitoring | | `projectToken` | string | - | ByteHide project token (can use env vars) | | `preset` | string | - | `"cloud"`, `"desktop"`, `"mobile"`, `"videogame"`, `"custom"` | | `debugResponses` | boolean | `false` | Include threat details in responses (dev only) | | `autoIntegration` | boolean | `true` | Auto-register middleware (.NET web frameworks only) | | `throwOnConnectionFailure` | boolean | `false` | Fail startup if backend unreachable | | `logging` | object | - | Logging configuration | | `protections` | object | - | Protection module configurations | | `cloud` | object | - | Cloud-specific settings (web apps only) | --- ### Protection Configuration Each protection can be configured individually: ```json { "protections": { "SqlInjection": { "enabled": true, "action": "block", "customActionName": "my-action", "intervalMs": 30000, "config": {} } } } ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `true` | Enable this protection | | `action` | string | `"block"` | `"none"`, `"log"`, `"block"`, `"close"`, `"erase"`, `"custom"` | | `customActionName` | string | - | Name of custom action (when `action="custom"`) | | `intervalMs` | number | - | Check interval in ms (desktop/mobile only) | | `config` | object | - | Module-specific configuration | > **Interval Configuration** > `intervalMs` only applies to desktop/mobile protections (DebuggerDetection, VirtualMachineDetection, etc.). Web protections run per-request. --- ### Available Presets Presets enable a predefined group of protections. See [Protection Modules](/platforms/dotnet/products/monitor/protection-modules) for the full reference of all available modules. #### `"cloud"` - Web Applications Enables web-focused protections: - SqlInjection - CrossSiteScripting - PathTraversal - CommandInjection - SSRF - LdapInjection - XxeInjection - NoSqlInjection - LlmPromptInjection #### `"desktop"` - Desktop Applications Enables desktop-focused protections: - DebuggerDetection - VirtualMachineDetection - EmulatorDetection - ClockTampering - MemoryDumpDetection - ProcessInjection #### `"mobile"` - Mobile Applications Enables mobile-focused protections: - JailbreakDetection (iOS/Android root) - DebuggerDetection - EmulatorDetection - ClockTampering - MemoryDumpDetection - HookingDetection #### `"videogame"` - Game Applications Enables game-focused protections: - DebuggerDetection - MemoryDumpDetection - SpeedHackDetection - CheatEngineDetection #### `"custom"` - Manual Configuration No default protections. Specify all protections manually. --- ## Logging Configuration ```json { "logging": { "level": "warning", "console": true, "debug": false, "file": { "enabled": true, "path": "logs/monitor.log", "maxSizeMB": 10, "maxFiles": 5 }, "bytehideLogs": { "enabled": false, "token": "${BYTEHIDE_LOGS_TOKEN}", "persist": true, "filePath": "logs/bytehide-logs-offline.json", "maskSensitiveData": ["password", "token", "apiKey"] } } } ``` ### Logging Fields | Field | Type | Default | Description | |-------|------|---------|-------------| | `level` | string | `"info"` | `"trace"`, `"debug"`, `"info"`, `"warning"`, `"error"` | | `console` | boolean | `false` | Enable console logging (stdout) | | `debug` | boolean | `false` | Enable debug output | | `file` | object | - | File logging configuration | | `bytehideLogs` | object | - | ByteHide Logs integration | ### File Logging | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `false` | Enable file logging | | `path` | string | `"logs/bytehide-monitor.log"` | Log file path | | `maxSizeMB` | number | `10` | Max file size before rotation | | `maxFiles` | number | `5` | Number of backup files | ### ByteHide Logs Integration Requires the ByteHide Logger integration. | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `false` | Enable ByteHide Logs | | `token` | string | - | ByteHide Logs API token | | `persist` | boolean | `true` | Persist logs locally when offline | | `filePath` | string | - | Offline persistence path | | `maskSensitiveData` | array | - | Patterns to mask (e.g., `["password"]`) | --- ## Cloud Configuration (Web Applications) Advanced settings for web/API applications: ```json { "cloud": { "rateLimit": { "enabled": true, "maxRequests": 100, "windowSizeInMS": 60000 }, "anomalyDetection": { "enabled": true, "detectIpChanges": true, "detectUserAgentChanges": true, "detectSuspiciousPatterns": true }, "endpoints": [ { "method": "POST", "route": "/api/admin/*", "protections": { "SqlInjection": { "enabled": true, "action": "block" } } }, { "method": "*", "route": "/health", "forceProtectionOff": true } ] } } ``` ### Rate Limiting | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `false` | Enable rate limiting | | `maxRequests` | number | `100` | Max requests per window | | `windowSizeInMS` | number | `60000` | Time window in milliseconds | ### Anomaly Detection | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `false` | Enable anomaly detection | | `detectIpChanges` | boolean | `true` | Detect IP address changes | | `detectUserAgentChanges` | boolean | `true` | Detect User-Agent changes | | `detectSuspiciousPatterns` | boolean | `true` | Detect suspicious patterns | ### Endpoint-Specific Configuration Override protections for specific routes: | Field | Type | Description | |-------|------|-------------| | `method` | string | `"GET"`, `"POST"`, `"PUT"`, `"DELETE"`, `"*"` (all) | | `route` | string | Route pattern (e.g., `"/api/users/{id}"`, `"/admin/*"`) | | `forceProtectionOff` | boolean | Disable ALL protections for this endpoint | | `protections` | object | Endpoint-specific protection overrides | | `rateLimit` | object | Endpoint-specific rate limit | --- ## Environment Variables You can reference environment variables in any string value using `${VARIABLE_NAME}` syntax: ```json { "projectToken": "${BYTEHIDE_API_TOKEN}", "logging": { "bytehideLogs": { "token": "${BYTEHIDE_LOGS_TOKEN}" } } } ``` This avoids hardcoding sensitive values in configuration files. ### Token Resolution Order The project token is resolved in this order: 1. `BYTEHIDE_MONITOR_TOKEN` environment variable 2. `BYTEHIDE_API_TOKEN` environment variable 3. `projectToken` value in the JSON file --- ## Complete Example Desktop application with comprehensive configuration: ```json { "name": "My Production App", "enabled": true, "projectToken": "${BYTEHIDE_API_TOKEN}", "preset": "desktop", "debugResponses": false, "throwOnConnectionFailure": false, "logging": { "level": "warning", "console": false, "file": { "enabled": true, "path": "logs/monitor.log", "maxSizeMB": 50, "maxFiles": 10 } }, "protections": { "DebuggerDetection": { "enabled": true, "action": "close" }, "VirtualMachineDetection": { "enabled": true, "action": "log" }, "ClockTampering": { "enabled": true, "action": "close" }, "MemoryDumpDetection": { "enabled": true, "action": "erase" }, "ProcessInjection": { "enabled": true, "action": "close" } } } ``` Web application with cloud features: ```json { "name": "My Web API", "enabled": true, "projectToken": "${BYTEHIDE_API_TOKEN}", "preset": "cloud", "autoIntegration": true, "debugResponses": false, "logging": { "level": "info", "console": true, "bytehideLogs": { "enabled": true, "token": "${BYTEHIDE_LOGS_TOKEN}", "persist": true, "maskSensitiveData": ["password", "token", "apiKey", "secret"] } }, "protections": { "SqlInjection": { "enabled": true, "action": "block" }, "CrossSiteScripting": { "enabled": true, "action": "block" }, "PathTraversal": { "enabled": true, "action": "block" }, "CommandInjection": { "enabled": true, "action": "block" }, "SSRF": { "enabled": true, "action": "block" }, "LlmPromptInjection": { "enabled": true, "action": "log" } }, "cloud": { "rateLimit": { "enabled": true, "maxRequests": 1000, "windowSizeInMS": 60000 }, "anomalyDetection": { "enabled": true, "detectIpChanges": true, "detectUserAgentChanges": true, "detectSuspiciousPatterns": true }, "endpoints": [ { "method": "*", "route": "/health", "forceProtectionOff": true }, { "method": "POST", "route": "/api/admin/*", "rateLimit": { "enabled": true, "maxRequests": 10, "windowSizeInMS": 60000 } }, { "method": "POST", "route": "/api/public/search", "protections": { "SqlInjection": { "enabled": true, "action": "block" }, "NoSqlInjection": { "enabled": true, "action": "block" } } } ] } } ``` --- ## Advanced Interval Configuration For desktop/mobile protections, you can specify check intervals: ```json { "protections": { "DebuggerDetection": { "enabled": true, "action": "close", "intervalMs": 30000 }, "VirtualMachineDetection": { "enabled": true, "action": "log", "intervalMs": 120000 }, "ClockTampering": { "enabled": true, "action": "close", "intervalMs": 300000 } } } ``` **Recommended intervals:** - DebuggerDetection: 30000ms (30 seconds) - VirtualMachineDetection: 120000ms (2 minutes, runs once typically) - ClockTampering: 300000ms (5 minutes) - MemoryDumpDetection: 60000ms (1 minute) - JailbreakDetection: 120000ms (2 minutes, runs once typically) > **Performance Impact** > Lower intervals mean more frequent checks but higher CPU usage. Balance security needs with performance requirements. --- ## Next Steps --- # Monitor Logging Configure how Monitor logs security events, threat detections, and operational information. Multiple output destinations, configurable log levels, and integration with ByteHide Logs for centralized forensic logging. {% .lead %} --- ## Overview Monitor generates log events for every security-relevant action: protection module initialization, threat detections, response actions taken, cloud sync status, and internal errors. You control what gets logged, at what level, and where the output goes. Logging can be configured from three sources: - **[Cloud Dashboard](/platforms/dotnet/products/monitor/cloud-configuration)**: Toggle logging settings in the Advanced Configuration panel of the Workflow tab - **[JSON file](/platforms/dotnet/products/monitor/json-configuration)**: Define logging in the `logging` object of your configuration file - **[Configuration API](/platforms/dotnet/products/monitor/configuration-api)**: Set logging options programmatically in code --- ## Log Levels Monitor supports five log levels, from most to least verbose: | Level | Description | When to Use | |---|---|---| | **Debug** | Detailed diagnostic information including internal state | Development and active troubleshooting only | | **Info** | General operational events: module loaded, config synced, incident reported | Default for production | | **Warning** | Potential issues that do not prevent operation | Staging environments, early detection of misconfigurations | | **Error** | Errors that affect functionality but do not stop Monitor | Production minimum recommended level | | **Critical** | Severe errors requiring immediate attention | Always logged regardless of configured level | Set the minimum level to control which events are recorded. For example, setting the level to **Warning** records Warning, Error, and Critical events, but ignores Debug and Info. --- ## Output Destinations ### Console Output Outputs Monitor events to standard output (stdout). Useful during development and in containerized environments where logs are collected from stdout (Docker, Kubernetes). ```json { "logging": { "level": "info", "console": true } } ``` ### File Logging Writes Monitor events to a log file on disk with automatic rotation. When the log file reaches the configured size limit, it rotates to a backup file. ```json { "logging": { "file": { "enabled": true, "path": "logs/monitor.log", "maxSizeMB": 10, "maxFiles": 5 } } } ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `false` | Enable file logging | | `path` | string | `"logs/bytehide-monitor.log"` | Log file path | | `maxSizeMB` | number | `10` | Max file size before rotation | | `maxFiles` | number | `5` | Number of backup files to keep | ### ByteHide Logs Send Monitor events to [ByteHide Logs](/platforms/dotnet/products/logs) for centralized, immutable, cryptographically secured logging. This is the recommended option for production environments. When enabled, every security incident Monitor detects is recorded in ByteHide Logs with full context: timestamp, detection type, payload, affected code, device fingerprint, confidence score, and response action taken. Events appear in your ByteHide Logs dashboard alongside application logs from other ByteHide modules. ![ByteHide Logs dashboard showing centralized log entries with severity levels, timestamps, and source details](/images/dotnet/logs/dashboard/main-dashboard.png) ```json { "logging": { "bytehideLogs": { "enabled": true, "token": "${BYTEHIDE_LOGS_TOKEN}", "persist": true, "filePath": "logs/bytehide-logs-offline.json", "maskSensitiveData": ["password", "token", "apiKey", "secret"] } } } ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | boolean | `false` | Enable ByteHide Logs integration | | `token` | string | - | ByteHide Logs API token | | `persist` | boolean | `true` | Store events locally when the API is unreachable, and sync when connectivity returns | | `filePath` | string | - | Path for offline event storage | | `maskSensitiveData` | array | - | Field names to mask in log output (e.g., `["password", "token"]`) | > **Offline Persistence** > When `persist` is enabled, Monitor stores events locally if it cannot reach the ByteHide Logs API. Events are automatically synced when connectivity is restored. No events are lost during network outages. --- ## Debug Logging Debug logging is a separate toggle from the log level. When enabled, Monitor includes detailed threat information in API responses and log output: attack type, confidence score, payload, source parameter, and internal reference codes. > **Security Risk in Production** > Debug logging exposes security-sensitive information in HTTP responses. An attacker receiving detailed threat analysis in the response body learns exactly what Monitor detected, how confident it is, and which parameter triggered the detection. This information helps attackers refine their payloads to bypass protection. Never enable debug logging in production. ### What Changes with Debug Enabled With debug logging **disabled**, blocked requests return a generic response with no internal details: ```json { "status": 403, "message": "Request blocked.", "info": "This application is protected by ByteHide Monitor. Learn more at https://bytehide.com", "reference": "BHM-A1B2C3D4" } ``` With debug logging **enabled**, the same blocked request returns full threat context: ```json { "type": "https://docs.bytehide.com/monitor/errors/sql-injection", "title": "SQL Injection Detected", "status": 403, "detail": "SQLite SQL Injection detected - query execution blocked", "instance": "/api/users?id=1 OR 1=1", "threatInfo": { "code": "BHM-T001", "category": "injection", "attackType": "SQL Injection", "confidence": 0.95, "payload": "1 OR 1=1 --", "source": "query.id", "reference": "BHM-A1B2C3D4" } } ``` The `threatInfo` object is only included when debug logging is active. This level of detail is invaluable during development to verify that Monitor is detecting and categorizing threats correctly, but it must be disabled before deploying to any environment accessible to external users. ### JSON Configuration ```json { "logging": { "debug": true } } ``` ### When to Use - Verifying that a protection module detects a specific attack pattern during development - Troubleshooting false positives or missed detections in a staging environment - Confirming that cloud configuration sync applies the expected rules - Diagnosing startup failures or configuration loading issues --- ## Cloud Dashboard Configuration You can configure all logging settings from the [Advanced Configuration](/platforms/dotnet/products/monitor/cloud-configuration#advanced-settings) panel in the Workflow tab of the Cloud Dashboard: ![ByteHide Monitor advanced configuration panel with logging levels, anomaly detection, rate limiting, and debug mode settings](/images/monitor/bytehide-monitor-advanced-rules.png) | Setting | Description | |---------|-------------| | **Logging** | Master toggle to enable or disable all logging | | **Minimum Level** | Select the minimum log level (Debug, Info, Warning, Error, Critical) | | **Console Output** | Toggle stdout output | | **Debug Logging** | Toggle verbose diagnostic output (not for production) | | **Local Logging** | Toggle file logging to disk | | **ByteHide Logs** | Toggle integration with ByteHide Logs (recommended) | Changes made in the Cloud Dashboard apply immediately to all running instances without redeployment. --- ## Log Output Format Monitor log entries include: - **Timestamp**: When the event occurred - **Level**: Log level (Debug, Info, Warning, Error, Critical) - **Module**: Which protection module generated the event - **Message**: Description of the event - **Threat Details**: For detection events, includes threat type, confidence score, and action taken Example console output: ``` [2025-01-15 10:23:45.123] [INFO] Monitor initialized successfully [2025-01-15 10:23:45.456] [INFO] Protection modules loaded: 6 active [2025-01-15 10:24:12.789] [WARN] SqlInjection detected - Action: BLOCK - Confidence: 0.95 [2025-01-15 10:24:12.790] [INFO] Incident reported to ByteHide Cloud ``` --- ## Best Practices - Set the minimum level to **Info** in production for a balance between visibility and log volume - Enable **ByteHide Logs** in production for centralized, immutable forensic records - Enable **console logging** in containerized environments (Docker, Kubernetes) where log collectors read from stdout - Enable **file logging** in on-premise or offline deployments where cloud logging is not available - Use `maskSensitiveData` to prevent passwords, tokens, and API keys from appearing in log output - Keep **debug logging disabled** in production. Enable it temporarily when troubleshooting, then disable it again - Configure file rotation (`maxSizeMB`, `maxFiles`) to prevent disk space issues in long-running applications --- ## Next Steps --- # Monitor Offline Mode Deploy Monitor in air-gapped environments without internet connectivity. {% .lead %} --- ## Overview Monitor works completely offline with no runtime dependencies: **Build Requirements:** - First build requires internet (license validation) - Subsequent builds use cached license (valid 7 days) - Air-gapped CI/CD fully supported **Runtime:** - Zero internet connectivity required - All protections work offline - Local incident logging only - No external API calls --- ## How It Works ### Initial Build (Internet Required) First build validates license and caches it: ```bash export BYTEHIDE_TOKEN="your-token" dotnet build ``` **Process:** 1. Validates license with ByteHide API 2. Downloads Cloud configuration (optional) 3. Caches license in `.bytehide-cache/` (7 day validity) 4. Embeds signature and config in assembly ### Subsequent Builds (Offline) After initial build, no internet needed: ```bash dotnet build # Works offline ``` **Process:** 1. Uses cached license from `.bytehide-cache/` 2. Uses local or cached configuration 3. Embeds signature in assembly Cache expires after 7 days - rebuild with internet to refresh. ### Runtime (Always Offline) Applications run with zero connectivity: - License verified from embedded signature - Configuration loaded from embedded resources - No backend communication - All incidents logged locally - Complete RASP protection offline --- ## Local Logging Configure file logging in `bytehide.monitor.json`: ```json { "logging": { "level": "warning", "file": { "enabled": true, "path": "logs/monitor.log", "maxSizeMB": 50, "maxFiles": 10 } } } ``` **Default locations:** | Platform | Path | |----------|------| | Linux | `/var/log/bytehide-monitor/incidents.log` | | Windows | `C:\ProgramData\ByteHide\Monitor\incidents.log` | | macOS | `/var/log/bytehide-monitor/incidents.log` | **Log entry format:** ``` [2025-12-28 10:30:45] THREAT DebuggerDetection: Debugger attached Action: Close Confidence: 1.0 Metadata: {"ProcessId":1234} ``` --- ## Air-Gapped CI/CD ### Option 1: License Cache Copy `.bytehide-cache/` directory to air-gapped environment: ```bash # Internet-connected machine export BYTEHIDE_TOKEN="your-token" dotnet build # Creates .bytehide-cache/ (valid 7 days) # Transfer to air-gapped machine scp -r .bytehide-cache/ user@airgapped:/project/ ``` ### Option 2: Self-Hosted Runner Use self-hosted GitHub Actions runner with persistent cache: ```yaml jobs: build: runs-on: self-hosted-airgapped steps: - uses: actions/checkout@v3 - name: Build run: dotnet build --configuration Release ``` Cache persists on runner, refreshed every 7 days. ### Option 3: Pre-Built Assembly Build with internet, deploy signed assembly: ```bash # Internet-connected build server dotnet publish -c Release -o ./publish # Transfer signed DLLs to air-gapped environment scp -r ./publish/ user@airgapped:/deploy/ ``` --- ## Next Steps --- # Understand how Monitor protections work Monitor protection modules are runtime detectors that identify threats, attacks, and security violations as they happen inside your application. {% .lead %} --- Each module operates independently and can be enabled, disabled, and configured with its own [response action](/platforms/dotnet/products/monitor/actions). Modules are organized into two categories based on how they operate: - **Passive Detectors** (Desktop and Mobile): Run at configurable intervals to monitor the runtime environment for threats like debuggers, virtual machines, jailbreaks, and tampering. - **Active Interceptors** (Web and Cloud): Hook into operations at the execution layer and validate them in real-time before they complete. SQL queries, file access, HTTP requests, XML parsing, and process execution are all intercepted and analyzed. --- ## Desktop & Mobile Protections Passive detectors that run at configurable intervals (`intervalMs`) to monitor the runtime environment. These modules detect reverse engineering, device compromise, and integrity violations on devices where your application runs. --- ## Web & Cloud Protections Active interceptors that hook into operations at the execution layer and validate them before they complete. These modules protect APIs and web applications against injection attacks, request forgery, and other OWASP Top 10 threats. --- ## Anomaly Detection Active by default in every project. Anomaly Detection learns your application's normal behavior patterns and flags deviations without requiring predefined rules. It operates across all application types (desktop, mobile, web). --- ## Configuring Protections Each module can be enabled individually with its own response action. You can configure protections from the [Cloud Dashboard](/platforms/dotnet/products/monitor/cloud-configuration), a [JSON configuration file](/platforms/dotnet/products/monitor/json-configuration), or the [Configuration API](/platforms/dotnet/products/monitor/configuration-api). Use presets to enable a group of protections at once, or configure each module individually: ```json { "preset": "cloud", "protections": { "SqlInjection": { "enabled": true, "action": "block" }, "LlmPromptInjection": { "enabled": true, "action": "log" } } } ``` See [JSON Configuration](/platforms/dotnet/products/monitor/json-configuration#available-presets) for the full list of presets and configuration options. --- ## Next Steps --- # Anomaly Detection Anomaly Detection is active by default in every Monitor project. It learns your application's normal behavior and automatically flags activity that deviates from it, detecting unknown threats, abnormal authentication patterns, and suspicious access. {% .lead %} --- ## What It Does Anomaly Detection builds a behavioral baseline from your application's real traffic and continuously analyzes it to identify suspicious activity. It monitors: - **Authentication patterns**: failed login spikes, credential rotation, login attempts from unusual locations or at unusual times - **Request behavior**: abnormal request rates, non-human navigation sequences, automated enumeration of endpoints - **Payload structure**: request bodies that don't match expected schemas, unexpected parameter combinations - **Error patterns**: sudden spikes in 4xx/5xx responses that indicate scanning or fuzzing - **Session behavior**: geographic jumps within a session, concurrent sessions from different locations --- ## Why It's Always On Anomaly Detection doesn't require configuration because it doesn't rely on predefined rules. It builds its baseline automatically from your application's real traffic and flags deviations. This means it can detect: - **Zero-day attacks** that no signature exists for yet - **Credential stuffing** campaigns using leaked credential databases - **Brute force attempts** against authentication endpoints - **API abuse** like enumeration, scraping, or data harvesting - **Account takeover patterns** where attackers test stolen credentials - **Reconnaissance activity** before a targeted attack --- ## What Gets Reported When Anomaly Detection identifies suspicious behavior, it creates an incident in your [Cloud Panel](/platforms/dotnet/products/monitor/cloud-panel/incidences) with: - The type of anomaly detected (authentication, rate, payload, etc.) - Confidence score based on how far the behavior deviates from baseline - Source IP, user agent, and session details - Timeline of the suspicious activity You can review these incidents alongside incidents from other protection modules in the same dashboard. --- ## Configuration ### ASP.NET Core Anomaly Detection works out of the box, but you can enable explicit configuration: ```csharp builder.Services.AddBytehideMonitor(monitor => monitor .WithAnomalyDetection(detectIpChanges: true, detectUserAgentChanges: true, detectSuspiciousPatterns: true) ); ``` ### JSON Configuration You can also adjust its sensitivity through the Cloud Panel or JSON configuration: ```json { "protections": { "AnomalyDetection": { "sensitivity": "medium", "authEndpoints": ["/api/login", "/api/auth/token", "/account/signin"] } } } ``` | Setting | Options | Default | Description | |---------|---------|---------|-------------| | `sensitivity` | `low`, `medium`, `high` | `medium` | How aggressively deviations are flagged | | `authEndpoints` | string[] | Auto-detected | Endpoints to monitor for authentication anomalies. Monitor auto-detects common patterns, but you can specify them explicitly | ### Sensitivity Levels | Level | Behavior | Best For | |-------|----------|----------| | **Low** | Only extreme deviations trigger incidents | High-traffic apps where minor variations are normal | | **Medium** | Balanced detection with few false positives | Most applications (default) | | **High** | Flags subtle anomalies, more incidents to review | Security-critical applications (finance, healthcare) | --- ## Related - [Protection Modules Overview](/platforms/dotnet/products/monitor/protection-modules) - [Cloud Panel: Incidences](/platforms/dotnet/products/monitor/cloud-panel/incidences) - [Cloud Panel: Workflow Actions](/platforms/dotnet/products/monitor/cloud-panel/workflow/actions) --- # Clock Tampering Detection **Protection Module:** `ClockTampering` Detects if the system clock has been manipulated to bypass time-based restrictions. **Available for:** - Desktop Applications - Mobile Applications - Server Applications --- ## How It Works Clock Tampering Detection monitors system time changes to identify manipulation attempts used to bypass trial periods, licenses, or time-based features. **Detection Methods:** - **Time Jump Detection** - Identifies sudden backward/forward time changes - **Monotonic Clock Validation** - Compares system time vs monotonic clock - **NTP Server Validation** - Optional verification against network time servers - **Boot Time Analysis** - Detects system time set before boot time - **Time Consistency Checks** - Validates time progression between checks **Common Tampering Scenarios:** - Trial period extension by setting clock backward - License expiration bypass - Time-limited feature abuse - Subscription validation circumvention - Session timeout bypass --- ## Configuration ### JSON Configuration ```json { "protections": { "ClockTampering": { "enabled": true, "action": "close" } } } ``` ### Code-Based Configuration ```csharp await Payload.ConfigureAsync(config => { config.AddProtection(ProtectionModuleType.ClockTampering, ActionType.Close); }); ``` ### Advanced Configuration ```json { "protections": { "ClockTampering": { "enabled": true, "action": "close", "intervalMs": 300000, "config": { "maxAllowedSkew": 60, "useNTP": false, "ntpServers": ["pool.ntp.org"], "detectBackwardJumps": true, "detectForwardJumps": true } } } } ``` --- ## Available Actions | Action | Behavior | Recommended For | |--------|----------|----------------| | **Close** | Terminate application | Trial software, time-based licenses | | **Log** | Record tampering and continue | Analytics, monitoring | | **Custom** | Execute custom handler | Grace periods, user warnings | | **None** | Detect only | Testing | --- ## Configuration Parameters ```json { "config": { "maxAllowedSkew": 60, "useNTP": false, "ntpServers": ["pool.ntp.org", "time.google.com"], "detectBackwardJumps": true, "detectForwardJumps": true, "allowTimezoneChanges": true } } ``` | Parameter | Description | Default | Unit | |-----------|-------------|---------|------| | `maxAllowedSkew` | Maximum allowed time deviation | `60` | seconds | | `useNTP` | Validate against NTP servers | `false` | boolean | | `ntpServers` | NTP servers for validation | `[]` | array | | `detectBackwardJumps` | Detect backward time changes | `true` | boolean | | `detectForwardJumps` | Detect forward time changes | `true` | boolean | | `allowTimezoneChanges` | Allow timezone changes | `true` | boolean | > **NTP Requirement** > When `useNTP: true`, the application requires internet connectivity. This may not be suitable for offline applications. --- ## When to Use **Recommended for:** - **Trial/Shareware Software** - Prevent trial period extension - **Time-Based Licenses** - Validate license expiration dates - **Subscription Apps** - Verify subscription validity - **Time-Limited Features** - Enforce feature expiration - **Gaming** - Prevent time-based exploit farming - **Financial Apps** - Ensure accurate timestamps **Not recommended for:** - Applications without time-based restrictions - Apps that need to run with incorrect system time - Embedded systems with unreliable clocks --- ## Code Examples ### Trial Period Protection ```csharp config.RegisterCustomAction("trial-tampering-handler", async (threat) => { var tamperingType = threat.Metadata["tamperingType"]?.ToString(); await File.AppendAllTextAsync("security.log", $"[{DateTime.UtcNow}] Clock tampering detected: {tamperingType}\n"); await ShowMessageAsync( "Security Violation", "System clock manipulation detected. The trial period cannot be extended by changing system time." ); await Task.Delay(5000); Environment.Exit(-1); }); config.AddProtection(ProtectionModuleType.ClockTampering, "trial-tampering-handler"); ``` ### License Validation with Grace Period ```csharp config.RegisterCustomAction("license-tampering-handler", async (threat) => { var skewSeconds = (int)(threat.Metadata["timeSkew"] ?? 0); // Allow small clock adjustments (DST, manual correction) if (Math.Abs(skewSeconds) < 300) // 5 minutes { await LogSecurityEventAsync("clock_skew_minor", skewSeconds); return; } // Show warning for moderate tampering if (Math.Abs(skewSeconds) < 3600) // 1 hour { await ShowWarningAsync( "Time Sync Issue", "System clock appears incorrect. Please verify your system time settings." ); return; } // Critical tampering - enforce license var license = await ValidateLicenseAsync(); if (!license.IsValid || license.IsExpired) { await ShowLicenseExpiredDialog(); Environment.Exit(-1); } }); ``` ### NTP Validation for Critical Apps ```csharp // Configure with NTP validation await Payload.ConfigureAsync(config => { config.RegisterCustomAction("ntp-validation", async (threat) => { var localTime = DateTime.Now; var ntpTime = await GetNtpTimeAsync("pool.ntp.org"); var diff = Math.Abs((ntpTime - localTime).TotalSeconds); if (diff > 120) // 2 minutes skew { await ShowMessageAsync( "Time Sync Required", $"Your system clock is {diff:F0} seconds off. " + "Please sync with internet time before using this application." ); Environment.Exit(-1); } }); config.AddProtection(ProtectionModuleType.ClockTampering, "ntp-validation"); }); ``` ### Gaming Time-Based Rewards ```csharp config.RegisterCustomAction("gaming-time-check", async (threat) => { var tamperingType = threat.Metadata["tamperingType"]?.ToString(); // Log to anti-cheat system await AntiCheatService.ReportTimeManipulation( CurrentPlayer.Id, tamperingType, threat.Metadata ); // Reset time-based rewards await PlayerProgressService.ResetDailyRewards(CurrentPlayer.Id); // Show warning await ShowInGameMessage( "Time manipulation detected. Daily rewards have been reset." ); }); ``` --- ## Detection Scenarios ### Backward Time Jump ```csharp // User sets clock from 2025-12-28 to 2025-12-20 // Threat metadata: { "tamperingType": "backward-jump", "timeSkew": -691200, // seconds backward "previousTime": "2025-12-28T10:00:00Z", "currentTime": "2025-12-20T10:00:00Z" } ``` ### Forward Time Jump ```csharp // User sets clock from 2025-12-28 to 2026-01-15 // Threat metadata: { "tamperingType": "forward-jump", "timeSkew": 1555200, // seconds forward "previousTime": "2025-12-28T10:00:00Z", "currentTime": "2026-01-15T10:00:00Z" } ``` ### Timezone Change (Allowed) ```csharp // User changes timezone from UTC-5 to UTC+2 // If allowTimezoneChanges: true, this is not flagged ``` --- ## Performance Impact **Detection Time:** <5ms per check **CPU Usage:** Negligible **Memory:** <100 KB **Network:** Only if `useNTP: true` **Recommended Interval:** 300000ms (5 minutes) --- ## Platform Compatibility | Platform | Support | Notes | |----------|---------|-------| | Windows | ✔ | Full support with WinAPI | | Linux | ✔ | Uses CLOCK_MONOTONIC | | macOS | ✔ | Uses mach_absolute_time | | Android | ✔ | SystemClock.elapsedRealtime() | | iOS | ✔ | CACurrentMediaTime() | | .NET 6+ | ✔ | Full support | | .NET Framework 4.6.2+ | ✔ | Full support | --- ## Threat Detection Details ```json { "threatId": "CLK-2025-12-28-2345", "description": "System clock tampering detected", "moduleType": "ClockTampering", "detectedAt": "2025-12-28T18:20:00Z", "confidence": 0.98, "metadata": { "tamperingType": "backward-jump", "timeSkew": -259200, "previousTime": "2025-12-28T10:00:00Z", "currentTime": "2025-12-25T10:00:00Z", "monotonicTime": 1234567890, "bootTime": "2025-12-27T08:00:00Z" } } ``` --- ## Best Practices 1. **Store Last Verification Time Securely** ```csharp // Don't store in plain text files // Use encrypted storage or server-side validation await SecureStorage.SetAsync("last_time_check", DateTime.UtcNow.ToString()); ``` 2. **Combine with Server Validation** ```csharp // For critical apps, validate with backend var serverTime = await ApiClient.GetServerTimeAsync(); ValidateAgainstServerTime(serverTime); ``` 3. **Allow Grace Period for Legitimate Adjustments** ```csharp // Small time adjustments are normal (NTP sync, DST) if (Math.Abs(timeSkew) < 300) // 5 minutes { // Allow it return; } ``` --- ## Related Protections - [Tampering Detection](/platforms/dotnet/products/monitor/protections/tampering-detection) - Code modifications - [Debugger Detection](/platforms/dotnet/products/monitor/protections/debugger-detection) - Debug prevention - [License Binding](/platforms/dotnet/products/monitor/protections/license-binding) - Hardware binding --- ## Next Steps --- # Cloud Metadata Detection **Protection Module:** `CloudMetadata` Detects if the application is running in a cloud environment (AWS, Azure, GCP, etc.). **Available for:** - Server Applications - Desktop Applications - Cloud Services --- ## How It Works Cloud Metadata Detection identifies cloud environments by querying cloud provider metadata services and analyzing system characteristics. **Detection Methods:** - **Metadata Service Queries** - Checks cloud provider metadata endpoints - **DMI/BIOS Analysis** - Examines system manufacturer information - **Environment Variables** - Detects cloud-specific variables - **DNS Resolution** - Validates cloud DNS patterns - **MAC Address Prefixes** - Identifies cloud provider network interfaces **Detected Cloud Providers:** - Amazon Web Services (AWS/EC2) - Microsoft Azure - Google Cloud Platform (GCP) - Oracle Cloud Infrastructure (OCI) - Alibaba Cloud - IBM Cloud - DigitalOcean - Linode - Vultr --- ## Configuration ```json { "protections": { "CloudMetadata": { "enabled": true, "action": "log" } } } ``` ### Code-Based Configuration ```csharp await Payload.ConfigureAsync(config => { config.AddProtection(ProtectionModuleType.CloudMetadata, ActionType.Log); }); ``` > **Single Execution** > This protection runs once at application startup, not periodically, as cloud environment doesn't change during runtime. --- ## Available Actions | Action | Behavior | Recommended For | |--------|----------|-----------------| | **Log** | Record cloud environment | Analytics, telemetry | | **Custom** | Execute cloud-specific logic | Configuration, features | | **None** | Detect only | Passive monitoring | --- ## When to Use **Recommended for:** - **License Differentiation** - Different pricing for cloud vs on-premise - **Configuration Optimization** - Cloud-specific settings - **Feature Enablement** - Enable cloud integrations - **Analytics** - Track deployment environments - **Security Monitoring** - Detect unexpected cloud deployments - **Compliance** - Track data residency --- ## Code Examples ### Cloud Environment Analytics ```csharp config.RegisterCustomAction("cloud-analytics", async (threat) => { var cloudProvider = threat.Metadata["cloudProvider"]?.ToString(); var region = threat.Metadata["region"]?.ToString(); var instanceType = threat.Metadata["instanceType"]?.ToString(); await TelemetryClient.TrackEventAsync("CloudEnvironmentDetected", new { Provider = cloudProvider, Region = region, InstanceType = instanceType, Timestamp = DateTime.UtcNow }); await LogInfoAsync($"Running on {cloudProvider} in {region}"); }); ``` ### Cloud-Specific Configuration ```csharp config.RegisterCustomAction("cloud-config-optimization", async (threat) => { var cloudProvider = threat.Metadata["cloudProvider"]?.ToString(); var isCloud = !string.IsNullOrEmpty(cloudProvider); if (isCloud) { switch (cloudProvider) { case "AWS": AppConfig.UseAwsParameterStore = true; AppConfig.UseAwsSecretsManager = true; AppConfig.EnableXRayTracing = true; await LogInfoAsync("Enabled AWS integrations"); break; case "Azure": AppConfig.UseAzureKeyVault = true; AppConfig.UseAzureAppInsights = true; AppConfig.UseManagedIdentity = true; await LogInfoAsync("Enabled Azure integrations"); break; case "GCP": AppConfig.UseGcpSecretManager = true; AppConfig.UseCloudTrace = true; AppConfig.UseWorkloadIdentity = true; await LogInfoAsync("Enabled GCP integrations"); break; } } }); ``` ### License-Based Cloud Detection ```csharp config.RegisterCustomAction("cloud-license-check", async (threat) => { var cloudProvider = threat.Metadata["cloudProvider"]?.ToString(); var isCloud = !string.IsNullOrEmpty(cloudProvider); if (isCloud) { var license = await GetLicenseAsync(); if (!license.AllowsCloudDeployment) { await ShowMessageAsync( "License Restriction", $"Your license does not permit cloud deployments. " + $"Detected: {cloudProvider}. " + "Please upgrade to a Cloud license." ); Environment.Exit(-1); } // Track cloud usage for billing await BillingService.RecordCloudUsageAsync(cloudProvider, license.Key); } }); ``` ### Regional Compliance ```csharp config.RegisterCustomAction("compliance-check", async (threat) => { var cloudProvider = threat.Metadata["cloudProvider"]?.ToString(); var region = threat.Metadata["region"]?.ToString(); if (cloudProvider == "AWS" || cloudProvider == "Azure" || cloudProvider == "GCP") { var allowedRegions = new[] { "us-east-1", "eu-west-1", "eu-central-1" }; if (!allowedRegions.Contains(region)) { await LogSecurityEventAsync("compliance_violation", new { Provider = cloudProvider, Region = region, Reason = "Deployment in non-compliant region" }); await ShowMessageAsync( "Compliance Violation", $"Application deployed in non-compliant region: {region}. " + $"Allowed regions: {string.Join(", ", allowedRegions)}" ); } } }); ``` --- ## Detection Metadata ### AWS EC2 ```json { "cloudProvider": "AWS", "region": "us-east-1", "availabilityZone": "us-east-1a", "instanceId": "i-0123456789abcdef0", "instanceType": "t3.medium", "imageId": "ami-0abcdef1234567890", "accountId": "123456789012" } ``` ### Azure Virtual Machine ```json { "cloudProvider": "Azure", "region": "eastus", "resourceGroup": "myapp-rg", "subscriptionId": "12345678-1234-1234-1234-123456789012", "vmId": "abcd1234-5678-90ab-cdef-1234567890ab", "vmSize": "Standard_D2s_v3", "osType": "Linux" } ``` ### Google Cloud Platform ```json { "cloudProvider": "GCP", "region": "us-central1", "zone": "us-central1-a", "projectId": "my-project-123456", "instanceId": "1234567890123456789", "machineType": "n1-standard-2", "preemptible": false } ``` --- ## Cloud Provider Detection Details ### AWS Detection Methods 1. **Metadata Service** - `http://169.254.169.254/latest/meta-data/` 2. **DMI Product Name** - Contains "Amazon EC2" 3. **Hypervisor UUID** - Starts with "ec2" or "EC2" 4. **MAC Address** - AWS-specific prefixes ### Azure Detection Methods 1. **Metadata Service** - `http://169.254.169.254/metadata/instance` 2. **DMI System Manufacturer** - "Microsoft Corporation" 3. **DMI Product Name** - "Virtual Machine" 4. **Azure Agent** - Presence of waagent ### GCP Detection Methods 1. **Metadata Service** - `http://metadata.google.internal/` 2. **DMI Product Name** - "Google Compute Engine" 3. **DMI BIOS Vendor** - "Google" --- ## Platform Compatibility | Cloud Provider | Support | Detection Methods | |----------------|---------|-------------------| | AWS | ✔ | Metadata API, DMI, MAC | | Azure | ✔ | Metadata API, DMI, agent | | GCP | ✔ | Metadata API, DMI | | Oracle Cloud | ✔ | Metadata API, DMI | | Alibaba Cloud | ✔ | Metadata API | | IBM Cloud | ✔ | Metadata API | | DigitalOcean | ✔ | Metadata API, DMI | --- ## Performance Impact **Detection Time:** <100ms (single query at startup) **CPU Usage:** Negligible **Memory:** <50 KB **Network:** Single HTTP request to metadata service (timeout: 2s) --- ## Best Practices 1. **Use for Telemetry and Configuration** ```csharp // Track cloud deployments for analytics action: ActionType.Log ``` 2. **Enable Cloud-Native Features** ```csharp if (cloudProvider == "AWS") { EnableAwsIntegrations(); } ``` 3. **License Tier by Environment** ```csharp // Different pricing for cloud vs on-premise if (isCloud && !license.IsCloudTier) { await ShowUpgradePromptAsync(); } ``` 4. **Regional Compliance** ```csharp // Ensure deployments in allowed regions ValidateRegionCompliance(region); ``` --- ## Threat Detection Details ```json { "threatId": "CLD-2025-12-28-9012", "description": "Cloud environment detected", "moduleType": "CloudMetadata", "detectedAt": "2025-12-28T22:00:00Z", "confidence": 1.0, "metadata": { "cloudProvider": "AWS", "region": "us-east-1", "availabilityZone": "us-east-1a", "instanceId": "i-0abcdef1234567890", "instanceType": "t3.large", "imageId": "ami-0123456789abcdef0", "accountId": "123456789012", "vpcId": "vpc-0abc123def456", "subnetId": "subnet-0xyz789abc" } } ``` --- ## Security Considerations > **Metadata Service Security** > Cloud metadata services can expose sensitive information. Ensure your application doesn't leak metadata to untrusted parties. ```csharp // Don't expose cloud metadata in API responses app.MapGet("/health", () => new { status = "healthy" }); // Good app.MapGet("/info", (CloudMetadata meta) => meta); // BAD - leaks cloud info ``` --- ## Related Protections - [Container Detection](/platforms/dotnet/products/monitor/protections/container-detection) - [Virtual Machine Detection](/platforms/dotnet/products/monitor/protections/virtual-machine-detection) - [Remote Desktop](/platforms/dotnet/products/monitor/protections/remote-desktop) --- # Command Injection Protection **Protection Module:** `CommandInjection` Prevents OS command injection attacks through input validation and process execution monitoring. **Available for:** - ASP.NET Core - ASP.NET Framework - Azure Functions - Desktop Applications --- ## How It Works Command Injection Protection monitors process execution and validates input used in shell commands. **Detection Methods:** - **Command Separator Detection** - Identifies `;`, `|`, `&`, `&&`, `||` - **Shell Metacharacter Analysis** - Detects `$()`, `` ` ``, `>`, `<` - **Process Execution Monitoring** - Tracks `Process.Start()` calls - **PowerShell Detection** - Identifies PowerShell execution attempts - **Encoded Command Detection** - Detects Base64 and hex-encoded commands **Common Attack Patterns:** - Command chaining (`; whoami`) - Pipe attacks (`| cat /etc/passwd`) - Subshell execution (`` `whoami` ``) - PowerShell encoded commands - Newline injection (`%0a` attacks) --- ## Configuration ```json { "protections": { "CommandInjection": { "enabled": true, "action": "block" } } } ``` ### ASP.NET Core ```csharp builder.Services.AddBytehideMonitor(monitor => monitor .WithProtection(ProtectionModuleType.CommandInjection, ActionType.Block) ); ``` --- ## Attack Examples ### Command Chaining ```bash # Input: "file.txt; rm -rf /" # Status: BLOCKED ``` ### Pipe Injection ```bash # Input: "file.txt | cat /etc/passwd" # Status: BLOCKED ``` ### Subshell Execution ```bash # Input: "file.txt; $(whoami)" # Status: BLOCKED ``` ### PowerShell Injection ```powershell # Input: "file.txt; powershell -enc base64payload" # Status: BLOCKED ``` --- ## Platform Compatibility | Platform | Support | |----------|---------| | ASP.NET Core | ✔ | | ASP.NET Framework | ✔ | | Azure Functions | ✔ | | Desktop Apps | ✔ | --- ## Related Protections - [Path Traversal](/platforms/dotnet/products/monitor/protections/path-traversal) - [SQL Injection](/platforms/dotnet/products/monitor/protections/sql-injection) --- # Container Detection **Protection Module:** `ContainerDetection` Detects if the application is running inside a container or orchestration environment. **Available for:** - Server Applications - Desktop Applications - Cloud Services --- ## How It Works Container Detection identifies containerized environments through system artifacts and environment characteristics. **Detection Methods:** - **Cgroup Analysis** - Examines `/proc/self/cgroup` for container indicators - **Environment Variables** - Detects container-specific variables - **Filesystem Markers** - Identifies `.dockerenv`, container overlays - **Init Process Detection** - Checks if PID 1 is a container runtime - **Namespace Analysis** - Detects Linux namespaces isolation - **Orchestrator Metadata** - Identifies Kubernetes, Docker Swarm **Detected Environments:** - Docker - Kubernetes (K8s) - Docker Compose - Docker Swarm - LXC/LXD - Podman - containerd - CRI-O --- ## Configuration ```json { "protections": { "ContainerDetection": { "enabled": true, "action": "log", "intervalMs": 120000 } } } ``` ### Code-Based Configuration ```csharp await Payload.ConfigureAsync(config => { config.AddProtection(ProtectionModuleType.ContainerDetection, ActionType.Log); }); ``` --- ## Available Actions | Action | Behavior | Recommended For | |--------|----------|-----------------| | **Log** | Record container environment | Analytics, monitoring | | **Custom** | Execute container-specific logic | Configuration adjustment | | **None** | Detect only (for telemetry) | Cloud deployments | > **Container Environments** > Most modern cloud deployments use containers. Use `log` or `custom` actions for analytics rather than blocking execution. --- ## When to Use **Recommended for:** - **License Enforcement** - Different pricing for containerized deployments - **Configuration Adjustment** - Optimize settings for container environments - **Analytics** - Track deployment methods - **Security Monitoring** - Detect unexpected containerization - **Feature Enablement** - Enable/disable features based on environment **Not for blocking unless:** - License terms prohibit containerized deployments - Application incompatible with containers - Security policy requires bare-metal only --- ## Code Examples ### License-Based Detection ```csharp config.RegisterCustomAction("container-license-check", async (threat) => { var containerType = threat.Metadata["containerType"]?.ToString(); var orchestrator = threat.Metadata["orchestrator"]?.ToString(); await LogDeploymentInfoAsync(new { ContainerType = containerType, Orchestrator = orchestrator, Timestamp = DateTime.UtcNow }); // Check if license allows containerized deployment var license = await GetLicenseAsync(); if (!license.AllowsContainers && containerType != null) { await ShowMessageAsync( "License Restriction", "Your license does not permit containerized deployments. " + "Please upgrade to an Enterprise license for Docker/Kubernetes support." ); Environment.Exit(-1); } }); ``` ### Configuration Optimization ```csharp config.RegisterCustomAction("container-optimization", async (threat) => { var isContainer = threat.Metadata["isContainer"] as bool? ?? false; var containerType = threat.Metadata["containerType"]?.ToString(); if (isContainer) { // Optimize for container environment AppConfig.EnableStatelessMode = true; AppConfig.UseDistributedCache = true; AppConfig.LogToStdout = true; await LogInfoAsync($"Detected {containerType} - enabling container optimizations"); // Adjust resource limits if (containerType == "Kubernetes") { AppConfig.MaxWorkerThreads = Environment.ProcessorCount * 2; AppConfig.EnableHealthChecks = true; } } }); ``` ### Analytics and Monitoring ```csharp config.RegisterCustomAction("container-analytics", async (threat) => { var metadata = threat.Metadata; await TelemetryClient.TrackEventAsync("ContainerDetected", new { ContainerType = metadata["containerType"], Orchestrator = metadata["orchestrator"], ContainerRuntime = metadata["runtime"], NamespaceId = metadata["namespaceId"], KubernetesPodName = metadata["kubernetesPodName"], KubernetesNamespace = metadata["kubernetesNamespace"] }); }); ``` --- ## Detection Metadata ```json { "isContainer": true, "containerType": "Docker", "orchestrator": "Kubernetes", "runtime": "containerd", "cgroupPath": "/kubepods/besteffort/pod123/container456", "namespaceId": "4026532456", "kubernetesPodName": "myapp-7d8f9c6b5-xk9m2", "kubernetesNamespace": "production", "kubernetesServiceAccount": "myapp-sa" } ``` --- ## Platform Compatibility | Platform | Support | Detection Methods | |----------|---------|-------------------| | Linux | ✔ | cgroup, /proc analysis, env vars | | Windows | ✔ | Process isolation, HCS detection | | macOS | ⚠️ | Limited (Docker Desktop detection) | | Docker | ✔ | Full support | | Kubernetes | ✔ | Pod metadata, service account | | LXC/LXD | ✔ | Container-specific markers | --- ## Environment-Specific Features ### Kubernetes Detection ```csharp if (threat.Metadata["orchestrator"]?.ToString() == "Kubernetes") { var podName = threat.Metadata["kubernetesPodName"]?.ToString(); var namespace = threat.Metadata["kubernetesNamespace"]?.ToString(); // Enable Kubernetes-specific features AppConfig.EnableK8sHealthProbes = true; AppConfig.EnableK8sServiceDiscovery = true; await LogInfoAsync($"Running in Kubernetes: {namespace}/{podName}"); } ``` ### Docker Compose Detection ```csharp if (Environment.GetEnvironmentVariable("COMPOSE_PROJECT_NAME") != null) { var projectName = Environment.GetEnvironmentVariable("COMPOSE_PROJECT_NAME"); await LogInfoAsync($"Running in Docker Compose project: {projectName}"); } ``` --- ## Best Practices 1. **Use for Telemetry, Not Blocking** ```csharp // Most apps should just log container info action: ActionType.Log ``` 2. **Optimize Configuration for Containers** ```csharp if (isContainer) { // Enable stateless mode for horizontal scaling AppConfig.EnableStatelessMode = true; } ``` 3. **License Tier Differentiation** ```csharp // Charge different pricing for container deployments if (isKubernetes && !license.IsEnterprise) { await ShowUpgradePromptAsync(); } ``` 4. **Feature Gating** ```csharp // Enable advanced features for containerized deployments if (isContainer) { Features.Enable("distributed-tracing"); Features.Enable("auto-scaling-hints"); } ``` --- ## Threat Detection Details ```json { "threatId": "CNT-2025-12-28-1234", "description": "Container environment detected", "moduleType": "ContainerDetection", "detectedAt": "2025-12-28T20:00:00Z", "confidence": 0.99, "metadata": { "isContainer": true, "containerType": "Docker", "orchestrator": "Kubernetes", "runtime": "containerd", "cgroupPath": "/kubepods/besteffort/pod-abc123/container-def456", "namespaceId": "4026532789", "kubernetesPodName": "myapp-deployment-7d8f9c6b5-xk9m2", "kubernetesNamespace": "production", "kubernetesServiceAccount": "myapp-service-account" } } ``` --- ## Related Protections - [Virtual Machine Detection](/platforms/dotnet/products/monitor/protections/virtual-machine-detection) - [Cloud Metadata](/platforms/dotnet/products/monitor/protections/cloud-metadata) - [Remote Desktop](/platforms/dotnet/products/monitor/protections/remote-desktop) --- # Cross-Site Scripting Protection **Protection Module:** `CrossSiteScripting` Prevents Cross-Site Scripting (XSS) attacks through input validation and output encoding. **Available for:** - ASP.NET Core - ASP.NET Framework - Blazor Server --- ## How It Works XSS Protection validates user input and ensures proper output encoding to prevent malicious script injection. **Detection Methods:** - **Script Tag Detection** - Identifies `