Hoşgeldin Misafir

Açık Portları Otomatik Kapatma ve Saldırı Engelleme Uygulaması

masterkey

Türkiye
6 Nis 2023
290 Mesaj
TIM Görevleri
1

Aktiflik

Seviye

Deneyim

TIM / GÖREV:
Arkadaşlar bilgisayarınızda bulunan açık portları otomatik olarak kapatan ve sizden habersiz arka planda bilgilerinizi çalan veya bilgi yollayan ip adreslerini otomatik bulup o portları kapatan uygulamadır.

  1. Özellikler:
  • Açık portları otomatik tarar
  • Şüpheli bağlantıları tespit eder
  • Brute force saldırılarını engeller
  • Port taramalarını algılar
  • Windows Güvenlik Duvarı'na otomatik kural ekler
  • Web arayüzü ile yönetim
  • Detaylı log kaydı
  1. Web Arayüzü Endpoint'leri:
  • GET /stats - İstatistikler
  • GET /blocked-ips - Engellenen IP'ler
  • POST /unblock - IP engelini kaldır
Bu sistem, Windows bilgisayarınızı otomatik olarak koruyacak ve şüpheli aktiviteleri anında engelleyecektir.

Dosya Yapısı Node.js ile Oluşturulmuştur. Kaynak Kodları
bu kodu :port-monitor.js olarak kaydedin

JavaScript:
// port-monitor.js
// Windows Port Monitor ve Intrusion Prevention System

const net = require('net');
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
const EventEmitter = require('events');

// Konfigürasyon
const config = {
    scanInterval: 5000, // Port tarama aralığı (ms)
    maxConnectionsPerMinute: 10, // Dakikada maksimum bağlantı
    blockDuration: 3600000, // Engelleme süresi (1 saat)
    suspiciousPorts: [22, 23, 135, 445, 1433, 3306, 3389, 5900, 8080, 8443], // Şüpheli portlar
    logFile: path.join(__dirname, 'security.log'),
    blockedIPsFile: path.join(__dirname, 'blocked-ips.json'),
    allowedPorts: [80, 443, 53, 3389] // İzin verilen portlar (isteğe bağlı)
};

class PortMonitor extends EventEmitter {
    constructor() {
        super();
        this.activeConnections = new Map();
        this.blockedIPs = new Map();
        this.connectionHistory = new Map();
        this.isMonitoring = false;
        this.monitoringInterval = null;
        
        this.loadBlockedIPs();
        this.setupEventHandlers();
    }

    setupEventHandlers() {
        this.on('suspicious-activity', this.handleSuspiciousActivity.bind(this));
        this.on('port-scan-detected', this.handlePortScan.bind(this));
        this.on('brute-force-detected', this.handleBruteForce.bind(this));
    }

    // Engellenen IP'leri yükle
    loadBlockedIPs() {
        try {
            if (fs.existsSync(config.blockedIPsFile)) {
                const data = fs.readFileSync(config.blockedIPsFile, 'utf8');
                const blocked = JSON.parse(data);
                for (const [ip, expireTime] of Object.entries(blocked)) {
                    if (expireTime > Date.now()) {
                        this.blockedIPs.set(ip, expireTime);
                    }
                }
                this.log(`Yüklenen engellenen IP sayısı: ${this.blockedIPs.size}`);
            }
        } catch (error) {
            console.error('Engellenen IP\'ler yüklenirken hata:', error);
        }
    }

    // Engellenen IP'leri kaydet
    saveBlockedIPs() {
        const blocked = {};
        for (const [ip, expireTime] of this.blockedIPs.entries()) {
            blocked[ip] = expireTime;
        }
        fs.writeFileSync(config.blockedIPsFile, JSON.stringify(blocked, null, 2));
    }

    // Log kaydı oluştur
    log(message, level = 'INFO') {
        const timestamp = new Date().toISOString();
        const logMessage = `[${timestamp}] [${level}] ${message}\n`;
        
        console.log(logMessage.trim());
        
        fs.appendFileSync(config.logFile, logMessage, (err) => {
            if (err) console.error('Log yazma hatası:', err);
        });
    }

    // Windows Güvenlik Duvarı'na kural ekle
    async addFirewallRule(ip, port = null) {
        return new Promise((resolve, reject) => {
            let command;
            if (port) {
                command = `netsh advfirewall firewall add rule name="Block_${ip}_Port_${port}" dir=in action=block remoteip=${ip} protocol=tcp localport=${port}`;
            } else {
                command = `netsh advfirewall firewall add rule name="Block_${ip}" dir=in action=block remoteip=${ip}`;
            }
            
            exec(command, (error, stdout, stderr) => {
                if (error) {
                    this.log(`Güvenlik duvarı kuralı eklenirken hata: ${error}`, 'ERROR');
                    reject(error);
                } else {
                    this.log(`IP engellendi: ${ip}${port ? ` (Port: ${port})` : ''}`, 'SECURITY');
                    resolve(stdout);
                }
            });
        });
    }

    // Windows Güvenlik Duvarı'ndan kural kaldır
    async removeFirewallRule(ip, port = null) {
        return new Promise((resolve, reject) => {
            let ruleName;
            if (port) {
                ruleName = `Block_${ip}_Port_${port}`;
            } else {
                ruleName = `Block_${ip}`;
            }
            
            const command = `netsh advfirewall firewall delete rule name="${ruleName}"`;
            
            exec(command, (error, stdout, stderr) => {
                if (error) {
                    this.log(`Güvenlik duvarı kuralı kaldırılırken hata: ${error}`, 'ERROR');
                    reject(error);
                } else {
                    this.log(`IP engeli kaldırıldı: ${ip}${port ? ` (Port: ${port})` : ''}`, 'INFO');
                    resolve(stdout);
                }
            });
        });
    }

    // IP'yi engelle
    async blockIP(ip, reason, port = null) {
        if (this.blockedIPs.has(ip)) {
            return;
        }
        
        const expireTime = Date.now() + config.blockDuration;
        this.blockedIPs.set(ip, expireTime);
        this.saveBlockedIPs();
        
        try {
            await this.addFirewallRule(ip, port);
            this.log(`IP engellendi: ${ip} - Sebep: ${reason}`, 'SECURITY');
            this.emit('ip-blocked', { ip, reason, expireTime });
        } catch (error) {
            this.log(`IP engellenirken hata: ${ip} - ${error}`, 'ERROR');
        }
    }

    // Süresi dolan engelleri temizle
    cleanupExpiredBlocks() {
        const now = Date.now();
        const toRemove = [];
        
        for (const [ip, expireTime] of this.blockedIPs.entries()) {
            if (expireTime <= now) {
                toRemove.push(ip);
            }
        }
        
        for (const ip of toRemove) {
            this.blockedIPs.delete(ip);
            this.removeFirewallRule(ip).catch(console.error);
            this.log(`IP engeli süresi doldu: ${ip}`, 'INFO');
        }
        
        if (toRemove.length > 0) {
            this.saveBlockedIPs();
        }
    }

    // Bağlantı geçmişini temizle
    cleanupConnectionHistory() {
        const now = Date.now();
        for (const [ip, connections] of this.connectionHistory.entries()) {
            const filtered = connections.filter(time => now - time < 60000); // Son 1 dakika
            if (filtered.length === 0) {
                this.connectionHistory.delete(ip);
            } else {
                this.connectionHistory.set(ip, filtered);
            }
        }
    }

    // Şüpheli aktivite kontrolü
    checkSuspiciousActivity(ip, port) {
        const now = Date.now();
        
        // Bağlantı geçmişini güncelle
        if (!this.connectionHistory.has(ip)) {
            this.connectionHistory.set(ip, []);
        }
        
        const history = this.connectionHistory.get(ip);
        history.push(now);
        this.connectionHistory.set(ip, history.filter(time => now - time < 60000));
        
        // Dakikadaki bağlantı sayısını kontrol et
        const connectionCount = this.connectionHistory.get(ip).length;
        
        if (connectionCount > config.maxConnectionsPerMinute) {
            this.emit('suspicious-activity', { ip, port, type: 'brute-force', count: connectionCount });
        }
        
        // Şüpheli portlara bağlantı kontrolü
        if (config.suspiciousPorts.includes(port)) {
            this.emit('suspicious-activity', { ip, port, type: 'suspicious-port', count: connectionCount });
        }
        
        return connectionCount;
    }

    // Şüpheli aktivite işleyici
    async handleSuspiciousActivity(data) {
        const { ip, port, type, count } = data;
        
        if (type === 'brute-force') {
            this.log(`Brute force tespit edildi - IP: ${ip}, Port: ${port}, Bağlantı sayısı: ${count}`, 'WARNING');
            await this.blockIP(ip, `Brute force attack on port ${port}`, port);
        } else if (type === 'suspicious-port') {
            this.log(`Şüpheli port bağlantısı - IP: ${ip}, Port: ${port}`, 'WARNING');
            await this.blockIP(ip, `Suspicious port access: ${port}`, port);
        }
    }

    // Port tarama tespiti
    async handlePortScan(data) {
        const { ip, ports } = data;
        this.log(`Port tarama tespit edildi - IP: ${ip}, Taranan portlar: ${ports.join(', ')}`, 'WARNING');
        await this.blockIP(ip, 'Port scanning detected');
    }

    // Brute force tespiti
    async handleBruteForce(data) {
        const { ip, port, attempts } = data;
        this.log(`Brute force saldırısı - IP: ${ip}, Port: ${port}, Deneme sayısı: ${attempts}`, 'CRITICAL');
        await this.blockIP(ip, `Brute force attack on ${port}`, port);
    }

    // Açık portları tara
    scanOpenPorts() {
        const commonPorts = [21, 22, 23, 25, 53, 80, 110, 135, 139, 143, 443, 445, 993, 995, 1433, 3306, 3389, 5432, 5900, 8080, 8443];
        const openPorts = [];
        
        commonPorts.forEach(port => {
            const socket = new net.Socket();
            socket.setTimeout(1000);
            
            socket.on('connect', () => {
                openPorts.push(port);
                socket.destroy();
                this.log(`Açık port bulundu: ${port}`, 'INFO');
                this.emit('open-port-detected', { port });
            });
            
            socket.on('error', () => {
                socket.destroy();
            });
            
            socket.on('timeout', () => {
                socket.destroy();
            });
            
            socket.connect(port, '127.0.0.1');
        });
        
        return openPorts;
    }

    // Aktif bağlantıları izle
    monitorActiveConnections() {
        return new Promise((resolve, reject) => {
            exec('netstat -an', (error, stdout, stderr) => {
                if (error) {
                    reject(error);
                    return;
                }
                
                const lines = stdout.split('\n');
                const connections = [];
                
                lines.forEach(line => {
                    // ESTABLISHED bağlantıları bul
                    if (line.includes('ESTABLISHED')) {
                        const parts = line.trim().split(/\s+/);
                        if (parts.length >= 3) {
                            const localAddr = parts[1];
                            const remoteAddr = parts[2];
                            
                            // Yerel ve uzak adresleri parse et
                            const localMatch = localAddr.match(/(\d+\.\d+\.\d+\.\d+):(\d+)/);
                            const remoteMatch = remoteAddr.match(/(\d+\.\d+\.\d+\.\d+):(\d+)/);
                            
                            if (localMatch && remoteMatch && remoteMatch[1] !== '0.0.0.0' && remoteMatch[1] !== '127.0.0.1') {
                                const connection = {
                                    localIP: localMatch[1],
                                    localPort: parseInt(localMatch[2]),
                                    remoteIP: remoteMatch[1],
                                    remotePort: parseInt(remoteMatch[2]),
                                    status: 'ESTABLISHED'
                                };
                                
                                connections.push(connection);
                                
                                // Şüpheli aktivite kontrolü
                                if (!this.blockedIPs.has(connection.remoteIP)) {
                                    const count = this.checkSuspiciousActivity(connection.remoteIP, connection.localPort);
                                    if (count > config.maxConnectionsPerMinute) {
                                        this.emit('suspicious-activity', {
                                            ip: connection.remoteIP,
                                            port: connection.localPort,
                                            type: 'brute-force',
                                            count: count
                                        });
                                    }
                                }
                            }
                        }
                    }
                });
                
                resolve(connections);
            });
        });
    }

    // İzleme döngüsü
    async startMonitoring() {
        if (this.isMonitoring) {
            this.log('İzleme zaten aktif', 'WARNING');
            return;
        }
        
        this.isMonitoring = true;
        this.log('Port izleme başlatıldı', 'INFO');
        
        // Periyodik temizlik
        setInterval(() => {
            this.cleanupExpiredBlocks();
            this.cleanupConnectionHistory();
        }, 60000); // Her dakika
        
        // Ana izleme döngüsü
        this.monitoringInterval = setInterval(async () => {
            try {
                // Açık portları tara
                const openPorts = this.scanOpenPorts();
                
                // Aktif bağlantıları izle
                const connections = await this.monitorActiveConnections();
                
                if (connections.length > 0) {
                    this.log(`Aktif bağlantılar: ${connections.length}`, 'DEBUG');
                }
                
            } catch (error) {
                this.log(`İzleme hatası: ${error}`, 'ERROR');
            }
        }, config.scanInterval);
        
        this.log('Port izleme sistemi aktif', 'INFO');
    }

    // İzlemeyi durdur
    stopMonitoring() {
        if (this.monitoringInterval) {
            clearInterval(this.monitoringInterval);
            this.monitoringInterval = null;
        }
        
        this.isMonitoring = false;
        this.log('Port izleme durduruldu', 'INFO');
    }

    // Engellenen IP'leri listele
    getBlockedIPs() {
        return Array.from(this.blockedIPs.entries()).map(([ip, expireTime]) => ({
            ip,
            expireTime,
            remainingTime: Math.max(0, expireTime - Date.now())
        }));
    }

    // Belirli bir IP'nin engelini kaldır
    async unblockIP(ip) {
        if (this.blockedIPs.has(ip)) {
            this.blockedIPs.delete(ip);
            this.saveBlockedIPs();
            await this.removeFirewallRule(ip);
            this.log(`IP engeli kaldırıldı: ${ip}`, 'INFO');
            return true;
        }
        return false;
    }

    // İstatistikleri getir
    getStatistics() {
        const totalBlocked = this.blockedIPs.size;
        const activeConnections = this.activeConnections.size;
        
        return {
            totalBlocked,
            activeConnections,
            blockedIPs: this.getBlockedIPs(),
            config: {
                scanInterval: config.scanInterval,
                maxConnectionsPerMinute: config.maxConnectionsPerMinute,
                blockDuration: config.blockDuration
            }
        };
    }
}

// Web arayüzü için basit HTTP sunucusu (opsiyonel)
class WebInterface {
    constructor(monitor, port = 3000) {
        this.monitor = monitor;
        this.port = port;
    }
    
    start() {
        const http = require('http');
        
        const server = http.createServer((req, res) => {
            res.setHeader('Content-Type', 'application/json');
            
            if (req.url === '/stats') {
                const stats = this.monitor.getStatistics();
                res.end(JSON.stringify(stats, null, 2));
            } else if (req.url === '/blocked-ips') {
                const blocked = this.monitor.getBlockedIPs();
                res.end(JSON.stringify(blocked, null, 2));
            } else if (req.url === '/unblock' && req.method === 'POST') {
                let body = '';
                req.on('data', chunk => body += chunk);
                req.on('end', async () => {
                    try {
                        const { ip } = JSON.parse(body);
                        const result = await this.monitor.unblockIP(ip);
                        res.end(JSON.stringify({ success: result, ip }));
                    } catch (error) {
                        res.end(JSON.stringify({ error: error.message }));
                    }
                });
            } else {
                res.end(JSON.stringify({ message: 'Port Monitor API', endpoints: ['/stats', '/blocked-ips', '/unblock'] }));
            }
        });
        
        server.listen(this.port, () => {
            console.log(`Web arayüzü http://localhost:${this.port} adresinde başlatıldı`);
        });
    }
}

// Ana uygulama
async function main() {
    console.log('Windows Port Monitor ve Intrusion Prevention System');
    console.log('==================================================');
    
    const monitor = new PortMonitor();
    
    // Olay dinleyicileri
    monitor.on('ip-blocked', (data) => {
        console.log(`⚠️  IP engellendi: ${data.ip} - ${data.reason}`);
    });
    
    monitor.on('open-port-detected', (data) => {
        console.log(`🔓 Açık port tespit edildi: ${data.port}`);
        if (data.port === 3389) {
            console.log('   ⚠️  RDP portu açık! Güvenli parola kullandığınızdan emin olun.');
        }
    });
    
    // İzlemeyi başlat
    await monitor.startMonitoring();
    
    // Web arayüzünü başlat (opsiyonel)
    const webInterface = new WebInterface(monitor, 3000);
    webInterface.start();
    
    console.log('\n✅ Sistem aktif ve izleme yapılıyor...');
    console.log('📊 Web arayüzü: http://localhost:3000');
    console.log('📝 Log dosyası: security.log');
    console.log('🚫 Engellenen IP\'ler: blocked-ips.json');
    console.log('\nPress Ctrl+C to stop\n');
    
    // Graceful shutdown
    process.on('SIGINT', async () => {
        console.log('\n\n🛑 Kapatılıyor...');
        monitor.stopMonitoring();
        console.log('✅ Güvenli bir şekilde kapatıldı');
        process.exit(0);
    });
}

// Uygulamayı başlat
if (require.main === module) {
    main().catch(console.error);
}

module.exports = { PortMonitor, WebInterface };


bu kodu : service.js olarak kaydedin

JavaScript:
// service.js
// Windows servisi olarak çalıştırmak için

const { PortMonitor } = require('./port-monitor');
const { Service } = require('node-windows');

// Servis tanımı
const svc = new Service({
    name: 'PortMonitor',
    description: 'Windows Port Monitor ve Intrusion Prevention System',
    script: require('path').join(__dirname, 'port-monitor.js'),
    nodeOptions: [
        '--harmony',
        '--max_old_space_size=4096'
    ]
});

// Servis olayları
svc.on('install', () => {
    console.log('Servis yüklendi');
    svc.start();
});

svc.on('start', () => {
    console.log('Servis başlatıldı');
});

svc.on('stop', () => {
    console.log('Servis durduruldu');
});

svc.on('uninstall', () => {
    console.log('Servis kaldırıldı');
});

// Komut satırı argümanlarını kontrol et
if (process.argv[2] === 'install') {
    svc.install();
} else if (process.argv[2] === 'uninstall') {
    svc.uninstall();
} else {
    console.log('Kullanım: node service.js [install|uninstall]');
}


Son Olarak : package.json olarak kaydedin..


JSON:
{
  "name": "windows-port-monitor",
  "version": "1.0.0",
  "description": "Windows port monitor and intrusion prevention system",
  "main": "port-monitor.js",
  "scripts": {
    "start": "node port-monitor.js",
    "service:install": "node service.js install",
    "service:uninstall": "node service.js uninstall",
    "test": "node test.js"
  },
  "dependencies": {
    "node-windows": "^1.0.0-beta.8"
  },
  "author": "Security System",
  "license": "MIT"
}






Kullanım Talimatları:​

  1. Kurulum:
bash
npm install
node port-monitor.js
  1. Windows Servisi Olarak Kurulum:
bash
npm run service:install



umarım herkezin işine yarar son olarak direkt dosyalar için Tıklayın