UNPKG

ssh-bridge-ai

Version:

One Command Magic SSH with Invisible Analytics - Connect to any server instantly with 'sshbridge user@server'. Zero setup, zero friction, pure magic. Industry-standard security with behind-the-scenes business intelligence.

451 lines (383 loc) 10.9 kB
const crypto = require('crypto'); const fs = require('fs-extra'); const path = require('path'); /** * Integrity Checker for SSHBridge * * Implements multiple layers of protection: * - Code integrity verification * - Anti-debugging techniques * - Runtime tampering detection * - Performance monitoring for analysis attempts */ class IntegrityChecker { constructor() { this.checksums = new Map(); this.lastCheck = Date.now(); this.checkInterval = 5000; // Check every 5 seconds this.maxChecksPerMinute = 10; this.checkCount = 0; this.checkResetTime = Date.now(); // Initialize protection this.initializeProtection(); // Start periodic checks this.startPeriodicChecks(); } /** * Initialize all protection mechanisms */ initializeProtection() { try { // Anti-debugging this.setupAntiDebugging(); // Code integrity this.calculateChecksums(); // Runtime protection this.setupRuntimeProtection(); // Performance monitoring this.setupPerformanceMonitoring(); } catch (error) { // Silently fail to avoid revealing protection mechanisms console.error('Integrity check initialization failed'); } } /** * Setup anti-debugging techniques */ setupAntiDebugging() { // Detect debugger presence const startTime = performance.now(); debugger; const endTime = performance.now(); if (endTime - startTime > 100) { this.handleDebuggerDetected(); } // Monitor console methods for debugging const originalLog = console.log; const originalDebug = console.debug; console.log = (...args) => { this.detectDebugging('console.log', args); return originalLog.apply(console, args); }; console.debug = (...args) => { this.detectDebugging('console.debug', args); return originalDebug.apply(console, args); }; // Detect Node.js inspector if (process.env.NODE_OPTIONS && process.env.NODE_OPTIONS.includes('--inspect')) { this.handleDebuggerDetected(); } // Detect common debugging tools this.detectDebuggingTools(); } /** * Calculate checksums for critical files */ calculateChecksums() { try { const criticalFiles = [ 'src/cli.js', 'src/api.js', 'src/config.js', 'src/security/secure-executor.js' ]; for (const file of criticalFiles) { if (fs.existsSync(file)) { const content = fs.readFileSync(file, 'utf8'); const checksum = crypto.createHash('sha256').update(content).digest('hex'); this.checksums.set(file, checksum); } } } catch (error) { // Silently fail } } /** * Setup runtime protection */ setupRuntimeProtection() { // Monitor process modifications const originalProcess = process; // Detect process manipulation Object.defineProperty(process, 'mainModule', { get: () => { this.detectTampering('process.mainModule access'); return originalProcess.mainModule; } }); // Monitor require cache const originalRequire = require; const requireCache = require.cache; Object.defineProperty(require, 'cache', { get: () => { this.detectTampering('require.cache access'); return requireCache; } }); // Monitor global object this.monitorGlobalObject(); } /** * Setup performance monitoring */ setupPerformanceMonitoring() { // Monitor for performance analysis attempts const originalPerformance = performance; if (global.performance) { Object.defineProperty(global, 'performance', { get: () => { this.detectPerformanceAnalysis(); return originalPerformance; } }); } } /** * Start periodic integrity checks */ startPeriodicChecks() { setInterval(() => { this.performIntegrityCheck(); }, this.checkInterval); } /** * Perform comprehensive integrity check */ performIntegrityCheck() { try { // Rate limiting if (this.shouldSkipCheck()) { return; } // Verify checksums this.verifyChecksums(); // Check for runtime tampering this.checkRuntimeIntegrity(); // Update check count this.checkCount++; } catch (error) { // Silently fail to avoid revealing protection } } /** * Check if we should skip this check due to rate limiting */ shouldSkipCheck() { const now = Date.now(); // Reset counter every minute if (now - this.checkResetTime > 60000) { this.checkCount = 0; this.checkResetTime = now; } return this.checkCount >= this.maxChecksPerMinute; } /** * Verify file checksums */ verifyChecksums() { for (const [file, expectedChecksum] of this.checksums) { try { if (fs.existsSync(file)) { const content = fs.readFileSync(file, 'utf8'); const currentChecksum = crypto.createHash('sha256').update(content).digest('hex'); if (currentChecksum !== expectedChecksum) { this.handleTamperingDetected(`File checksum mismatch: ${file}`); } } } catch (error) { // Silently fail } } } /** * Check runtime integrity */ checkRuntimeIntegrity() { // Check for suspicious global variables const suspiciousGlobals = ['__REACT_DEVTOOLS_GLOBAL_HOOK__', '__REDUX_DEVTOOLS_EXTENSION__']; for (const globalName of suspiciousGlobals) { if (global[globalName]) { this.detectTampering(`Suspicious global detected: ${globalName}`); } } // Check for debugging flags if (process.env.NODE_ENV === 'development' && !this.isExpectedDevelopment()) { this.detectTampering('Unexpected development environment'); } } /** * Monitor global object for modifications */ monitorGlobalObject() { const originalGlobals = new Set(Object.keys(global)); // Monitor for new global variables setInterval(() => { const currentGlobals = new Set(Object.keys(global)); for (const globalName of currentGlobals) { if (!originalGlobals.has(globalName)) { this.detectTampering(`New global variable detected: ${globalName}`); } } }, 10000); } /** * Detect debugging attempts */ detectDebugging(method, args) { const suspiciousPatterns = [ /debug/i, /breakpoint/i, /inspect/i, /trace/i, /profile/i ]; const argsString = JSON.stringify(args); for (const pattern of suspiciousPatterns) { if (pattern.test(argsString)) { this.handleDebuggingDetected(`${method} with suspicious content: ${argsString}`); } } } /** * Detect debugging tools */ detectDebuggingTools() { // Check for common debugging environment variables const debugVars = [ 'NODE_OPTIONS', 'DEBUG', 'NODE_DEBUG', 'NODE_DEBUG_NATIVE' ]; for (const varName of debugVars) { if (process.env[varName]) { const value = process.env[varName]; if (value.includes('--inspect') || value.includes('--debug') || value.includes('--trace')) { this.handleDebuggerDetected(); } } } } /** * Detect performance analysis */ detectPerformanceAnalysis() { this.detectTampering('Performance analysis attempt detected'); } /** * Detect tampering attempts */ detectTampering(reason) { console.error(`🔒 Security: Tampering detected - ${reason}`); this.handleTamperingDetected(reason); } /** * Handle debugger detection */ handleDebuggerDetected() { console.error('🔒 Security: Debugger detected'); // Implement progressive degradation this.degradeFunctionality('debugger_detected'); // Could also implement: // - Exit process // - Corrupt data // - Send alert to monitoring service } /** * Handle debugging detection */ handleDebuggingDetected(reason) { console.error(`🔒 Security: Debugging detected - ${reason}`); // Implement progressive degradation this.degradeFunctionality('debugging_detected'); } /** * Handle tampering detection */ handleTamperingDetected(reason) { console.error(`🔒 Security: Tampering detected - ${reason}`); // Implement progressive degradation this.degradeFunctionality('tampering_detected'); } /** * Implement progressive functionality degradation */ degradeFunctionality(reason) { // Log the incident this.logSecurityIncident(reason); // Implement progressive degradation based on severity switch (reason) { case 'debugger_detected': // Most severe - exit process process.exit(1); break; case 'debugging_detected': // Moderate - disable sensitive features this.disableSensitiveFeatures(); break; case 'tampering_detected': // Mild - log and continue with warnings this.enableWarningMode(); break; } } /** * Disable sensitive features */ disableSensitiveFeatures() { // Disable advanced security features if (global.sshbridge) { global.sshbridge.securityLevel = 'degraded'; } } /** * Enable warning mode */ enableWarningMode() { // Enable additional logging and warnings if (global.sshbridge) { global.sshbridge.warningMode = true; } } /** * Log security incidents */ logSecurityIncident(reason) { try { const logEntry = { timestamp: new Date().toISOString(), reason, processId: process.pid, nodeVersion: process.version, platform: process.platform, arch: process.arch, userAgent: process.env.USER_AGENT || 'unknown' }; // Could send to monitoring service console.error('🔒 Security incident logged:', logEntry); } catch (error) { // Silently fail to avoid revealing logging mechanism } } /** * Check if development environment is expected */ isExpectedDevelopment() { // Only allow development in specific conditions return process.env.SSHBRIDGE_DEV_MODE === 'true' && process.env.NODE_ENV === 'development' && process.env.USER === process.env.SSHBRIDGE_DEV_USER; } /** * Get security status */ getSecurityStatus() { return { integrityChecks: this.checkCount, lastCheck: this.lastCheck, protectionActive: true, checksumsVerified: this.checksums.size > 0 }; } } module.exports = { IntegrityChecker };