File size: 10,928 Bytes
857cdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/**
 * Security Logger - ระบบบันทึกเหตุการณ์ความปลอดภัย
 * Chahua Development Thailand
 * CEO: Saharath C.
 * 
 * Purpose: บันทึกและตรวจสอบเหตุการณ์ด้านความปลอดภัย
 */

const fs = require('fs');
const path = require('path');

class SecurityLogger {
    constructor(options = {}) {
        this.config = {
            logPath: options.logPath || './logs/security',
            maxLogSize: options.maxLogSize || 10 * 1024 * 1024, // 10MB
            maxLogFiles: options.maxLogFiles || 5,
            alertThreshold: options.alertThreshold || 10, // Alert after 10 events
            enableRealTimeAlerts: options.enableRealTimeAlerts || true,
            sensitiveFields: options.sensitiveFields || ['password', 'token', 'secret', 'key']
        };
        
        this.securityEvents = [];
        this.alertCount = 0;
        this.blockedIPs = new Set();
        this.suspiciousActivities = new Map();
        
        this.ensureLogDirectory();
        console.log('Security Logger initialized');
    }

    ensureLogDirectory() {
        try {
            if (!fs.existsSync(this.config.logPath)) {
                fs.mkdirSync(this.config.logPath, { recursive: true });
            }
        } catch (error) {
            console.warn('Warning: Could not create security log directory:', error.message);
        }
    }

    async logSecurityEvent(eventData) {
        const timestamp = new Date().toISOString();
        const eventId = this.generateEventId();
        
        const securityEvent = {
            id: eventId,
            timestamp,
            type: eventData.type || 'UNKNOWN',
            severity: eventData.severity || 'medium',
            details: this.sanitizeDetails(eventData),
            ip: eventData.ip || 'unknown',
            userAgent: eventData.userAgent || 'unknown',
            source: eventData.source || 'system'
        };
        
        // Add to memory
        this.securityEvents.push(securityEvent);
        
        // Maintain max events in memory
        if (this.securityEvents.length > 1000) {
            this.securityEvents.shift();
        }
        
        // Write to file
        this.writeToLogFile(securityEvent);
        
        // Check for alerts
        this.checkForAlerts(securityEvent);
        
        // Update suspicious activity tracking
        this.updateSuspiciousActivity(securityEvent);
        
        console.log(`Security Event [${securityEvent.severity.toUpperCase()}]: ${securityEvent.type} - ${eventId}`);
        
        return eventId;
    }

    logAuthFailure(ip, username, details = {}) {
        return this.logSecurityEvent({
            type: 'AUTH_FAILURE',
            ip,
            username,
            severity: 'high',
            ...details
        });
    }

    logAuthSuccess(ip, username, details = {}) {
        return this.logSecurityEvent({
            type: 'AUTH_SUCCESS',
            ip,
            username,
            severity: 'low',
            ...details
        });
    }

    logSuspiciousAccess(ip, endpoint, details = {}) {
        return this.logSecurityEvent({
            type: 'SUSPICIOUS_ACCESS',
            ip,
            endpoint,
            severity: 'high',
            ...details
        });
    }

    logRateLimitExceeded(ip, endpoint, details = {}) {
        return this.logSecurityEvent({
            type: 'RATE_LIMIT_EXCEEDED',
            ip,
            endpoint,
            severity: 'medium',
            ...details
        });
    }

    logDataBreach(source, details = {}) {
        return this.logSecurityEvent({
            type: 'DATA_BREACH',
            source,
            severity: 'critical',
            ...details
        });
    }

    logUnauthorizedAccess(ip, resource, details = {}) {
        return this.logSecurityEvent({
            type: 'UNAUTHORIZED_ACCESS',
            ip,
            resource,
            severity: 'high',
            ...details
        });
    }

    logSystemAnomaly(anomalyType, details = {}) {
        return this.logSecurityEvent({
            type: 'SYSTEM_ANOMALY',
            anomalyType,
            severity: 'medium',
            ...details
        });
    }

    sanitizeDetails(details) {
        const sanitized = { ...details };
        
        // Remove sensitive fields
        for (const field of this.config.sensitiveFields) {
            if (sanitized[field]) {
                sanitized[field] = '***REDACTED***';
            }
        }
        
        return sanitized;
    }

    writeToLogFile(event) {
        try {
            const logFileName = `security-${new Date().toISOString().split('T')[0]}.log`;
            const logFilePath = path.join(this.config.logPath, logFileName);
            
            const logEntry = JSON.stringify(event) + '\n';
            
            // Check file size and rotate if needed
            if (fs.existsSync(logFilePath)) {
                const stats = fs.statSync(logFilePath);
                if (stats.size > this.config.maxLogSize) {
                    this.rotateLogFile(logFilePath);
                }
            }
            
            fs.appendFileSync(logFilePath, logEntry);
            
        } catch (error) {
            console.error('Error writing security log:', error.message);
        }
    }

    rotateLogFile(logFilePath) {
        try {
            const logDir = path.dirname(logFilePath);
            const baseName = path.basename(logFilePath, '.log');
            
            // Rotate existing files
            for (let i = this.config.maxLogFiles - 1; i > 0; i--) {
                const oldFile = path.join(logDir, `${baseName}.${i}.log`);
                const newFile = path.join(logDir, `${baseName}.${i + 1}.log`);
                
                if (fs.existsSync(oldFile)) {
                    if (i === this.config.maxLogFiles - 1) {
                        fs.unlinkSync(oldFile); // Delete oldest
                    } else {
                        fs.renameSync(oldFile, newFile);
                    }
                }
            }
            
            // Move current file to .1
            const rotatedFile = path.join(logDir, `${baseName}.1.log`);
            fs.renameSync(logFilePath, rotatedFile);
            
            console.log(`Security log rotated: ${logFilePath}`);
            
        } catch (error) {
            console.error('Error rotating security log:', error.message);
        }
    }

    checkForAlerts(event) {
        if (!this.config.enableRealTimeAlerts) return;
        
        // Count events from same IP in last hour
        const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
        const recentEvents = this.securityEvents.filter(e => 
            e.ip === event.ip && 
            new Date(e.timestamp) > oneHourAgo
        );
        
        if (recentEvents.length >= this.config.alertThreshold) {
            this.triggerAlert(event.ip, recentEvents);
        }
        
        // Immediate alert for critical events
        if (event.severity === 'critical') {
            this.triggerCriticalAlert(event);
        }
    }

    triggerAlert(ip, events) {
        this.alertCount++;
        console.warn(`SECURITY ALERT: Multiple events from IP ${ip} (${events.length} events)`);
        
        // Block IP after multiple alerts
        if (events.length >= this.config.alertThreshold * 2) {
            this.blockedIPs.add(ip);
            console.warn(`IP ${ip} has been blocked due to suspicious activity`);
        }
        
        // In a real system, you might send email/SMS alerts here
    }

    triggerCriticalAlert(event) {
        console.error(`CRITICAL SECURITY ALERT: ${event.type} - ${event.id}`);
        // In a real system, you might trigger immediate notifications
    }

    updateSuspiciousActivity(event) {
        const key = `${event.ip}_${event.type}`;
        const count = this.suspiciousActivities.get(key) || 0;
        this.suspiciousActivities.set(key, count + 1);
    }

    isIPBlocked(ip) {
        return this.blockedIPs.has(ip);
    }

    unblockIP(ip) {
        if (this.blockedIPs.delete(ip)) {
            console.log(`IP ${ip} has been unblocked`);
            return true;
        }
        return false;
    }

    getSecurityReport(timeRange = '24h') {
        const hours = timeRange === '24h' ? 24 : parseInt(timeRange);
        const startTime = new Date(Date.now() - hours * 60 * 60 * 1000);
        
        const relevantEvents = this.securityEvents.filter(e => 
            new Date(e.timestamp) > startTime
        );
        
        const report = {
            timeRange: `${hours} hours`,
            totalEvents: relevantEvents.length,
            eventTypes: {},
            severityBreakdown: {},
            topIPs: {},
            blockedIPs: Array.from(this.blockedIPs),
            alertsTriggered: this.alertCount
        };
        
        // Analyze events
        relevantEvents.forEach(event => {
            // Event types
            report.eventTypes[event.type] = (report.eventTypes[event.type] || 0) + 1;
            
            // Severity breakdown
            report.severityBreakdown[event.severity] = (report.severityBreakdown[event.severity] || 0) + 1;
            
            // Top IPs
            report.topIPs[event.ip] = (report.topIPs[event.ip] || 0) + 1;
        });
        
        // Sort top IPs
        report.topIPs = Object.entries(report.topIPs)
            .sort(([,a], [,b]) => b - a)
            .slice(0, 10)
            .reduce((obj, [ip, count]) => {
                obj[ip] = count;
                return obj;
            }, {});
        
        return report;
    }

    exportSecurityLogs(startDate, endDate) {
        try {
            const events = this.securityEvents.filter(e => {
                const eventDate = new Date(e.timestamp);
                return eventDate >= startDate && eventDate <= endDate;
            });
            
            const exportData = {
                exportDate: new Date().toISOString(),
                dateRange: { start: startDate, end: endDate },
                totalEvents: events.length,
                events: events
            };
            
            return exportData;
            
        } catch (error) {
            console.error('Error exporting security logs:', error.message);
            return null;
        }
    }

    generateEventId() {
        return `sec_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
    }

    getStats() {
        return {
            totalEvents: this.securityEvents.length,
            alertsTriggered: this.alertCount,
            blockedIPs: this.blockedIPs.size,
            suspiciousActivities: this.suspiciousActivities.size
        };
    }
}

module.exports = SecurityLogger;