Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
274 lines (229 loc) · 10.8 KB
/
Copy pathserver.ts
File metadata and controls
274 lines (229 loc) · 10.8 KB
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
import express from 'express';
import { createServer as createViteServer } from 'vite';
import dotenv from 'dotenv';
import { GoogleGenAI } from '@google/genai';
dotenv.config();
const app = express();
const PORT = 3000;
app.use(express.json({ limit: '10mb' }));
// Initialize GoogleGenAI client (telemetry header included as per skill guidelines)
const apiKey = process.env.GEMINI_API_KEY || '';
let ai: GoogleGenAI | null = null;
if (apiKey) {
ai = new GoogleGenAI({
apiKey,
httpOptions: {
headers: {
'User-Agent': 'aistudio-build',
},
},
});
}
// Check AI status
app.get('/api/ai/status', (_req, res) => {
res.json({
available: !!ai,
model: 'gemini-3.8-flash',
});
});
// AI SIEM Incident Report Endpoint
app.post('/api/ai/incident-report', async (req, res) => {
try {
const { summaryData, sampleLogs } = req.body;
if (!ai) {
return res.status(200).json({
report: generateHeuristicReport(summaryData),
fallback: true,
});
}
const prompt = `Sen kıdemli bir SOC (Security Operations Center) Analisti ve SIEM Uzmanısın.
Aşağıda Linux auth.log / Snort / Suricata loglarından elde edilmiş güvenlik özeti ve log satırları bulunmaktadır:
Özet Veriler:
- Toplam Olay Sayısı: ${summaryData.totalEvents}
- Başarısız Giriş / Brute-Force Denemeleri: ${summaryData.failedAttempts}
- Şüpheli / Tehdit IP Sayısı: ${summaryData.threatIpCount}
- Hedef Alınan Kullanıcılar: ${summaryData.targetedUsers?.slice(0, 10).join(', ')}
- En Tehlikeli IP'ler: ${JSON.stringify(summaryData.topAttackingIps?.slice(0, 5))}
- Tespit Edilen Saldırı Türleri: ${summaryData.attackTypes?.join(', ')}
Örnek Log Satırları:
${sampleLogs?.slice(0, 15).join('\n')}
Lütfen Türkçe dilinde profesyonel bir "SIEM Güvenlik Olayı ve Adli Analiz Raporu" oluştur. Rapor şunları içermelidir:
1. **Yönetici Özeti**: Saldırının boyutu, niteliği ve etki derecesi.
2. **Tehdit Vektörü ve MITRE ATT&CK Eşlemesi**: (Örn: T1110 Brute Force, T1078 Valid Accounts vb.)
3. **Şüpheli IP Aktiviteleri**: Saldırgan IP'lerin davranış analizi ve hedeflenen hesaplar.
4. **iptables & Savunma Önerileri**: Alınması gereken acil firewall kuralları, fail2ban konfigürasyonu ve SSH sıkılaştırma (hardening) tavsiyeleri.
Yanıtı temiz, yapılandırılmış markdown formatında yaz.`;
const response = await ai.models.generateContent({
model: 'gemini-3.8-flash',
contents: prompt,
});
const report = response.text || 'Rapor oluşturulamadı.';
return res.json({ report, fallback: false });
} catch (error: any) {
console.error('AI Report Generation Error:', error);
return res.status(200).json({
report: generateHeuristicReport(req.body.summaryData || {}),
fallback: true,
error: error.message,
});
}
});
// AI IP Investigation Endpoint
app.post('/api/ai/investigate-ip', async (req, res) => {
try {
const { ipData } = req.body;
if (!ai) {
return res.status(200).json({
analysis: generateHeuristicIpAnalysis(ipData),
fallback: true,
});
}
const prompt = `Sen bir Siber Tehdit İstihbaratı ve SOC Analistisin.
Aşağıdaki IP adresi hakkında SIEM sistemimiz anormal aktivite ve brute-force saldırısı tespit etti:
IP Bilgileri:
- IP Adresi: ${ipData.ip}
- Konum / Ülke: ${ipData.country || 'Bilinmiyor'} (${ipData.city || 'Bilinmiyor'})
- ISP / ASN: ${ipData.isp || 'Bilinmiyor'}
- Başarısız Giriş Denemesi: ${ipData.failedAttempts}
- Başarılı Giriş: ${ipData.successfulAttempts || 0}
- Hedeflenen Kullanıcı Adları: ${ipData.usernames?.join(', ') || 'root, admin'}
- Hedef Portlar: ${ipData.ports?.join(', ') || '22 (SSH)'}
- Risk Skoru: ${ipData.riskScore} / 100
- Algılanan Anomali: ${ipData.anomalyTypes?.join(', ')}
Lütfen bu IP için Türkçe olarak:
1. Saldırı profili ve niyeti (Brute-force, dictionary attack, botnet nodu, credential stuffing vb.)
2. Tehlike seviyesi değerlendirmesi
3. Bu IP için önerilen iptables / firewall eylemi (örneğin DROP kuralı ve süresi)
4. Sunucu yöneticisine kritik uyarılar
hazırla.`;
const response = await ai.models.generateContent({
model: 'gemini-3.8-flash',
contents: prompt,
});
return res.json({
analysis: response.text || 'Analiz oluşturulamadı.',
fallback: false,
});
} catch (error: any) {
console.error('AI IP Investigation Error:', error);
return res.status(200).json({
analysis: generateHeuristicIpAnalysis(req.body.ipData || {}),
fallback: true,
error: error.message,
});
}
});
// AI SOC Assistant Chatbot Endpoint
app.post('/api/ai/chat', async (req, res) => {
try {
const { message, context } = req.body;
if (!ai) {
return res.json({
reply: generateHeuristicChatReply(message, context),
fallback: true,
});
}
const prompt = `Sen AegisLog SIEM ve Linux Güvenlik Duvarı Asistanısın.
Sistem Context:
- Analiz Edilen Log Türü: ${context?.logType || 'Linux auth.log / Snort / Suricata'}
- Aktif Engelli IP Sayısı: ${context?.bannedIpCount || 0}
- Tespit Edilen Tehdit Sayısı: ${context?.threatCount || 0}
- Son Tespit Edilen Şüpheli IP'ler: ${context?.topIps?.join(', ') || 'Yok'}
Kullanıcının Sorusu / Komutu:
"${message}"
Siber güvenlik, Linux log analizi (auth.log, Snort, Suricata), brute-force savunması, iptables, fail2ban ve sunucu güvenliği konularında uzman, net, uygulanabilir komut ve adımlar içeren profesyonel bir yanıt ver. Türkçe yanıtla. Kod veya komut varsa bash/iptables formatında göster.`;
const response = await ai.models.generateContent({
model: 'gemini-3.8-flash',
contents: prompt,
});
return res.json({
reply: response.text || 'Yanıt üretilemedi.',
fallback: false,
});
} catch (error: any) {
console.error('AI Chat Error:', error);
return res.json({
reply: generateHeuristicChatReply(req.body.message || '', req.body.context || {}),
fallback: true,
});
}
});
// Fallback heuristic generators if Gemini API is temporarily offline or key not provided
function generateHeuristicReport(data: any) {
const topIps = (data.topAttackingIps || []).slice(0, 3).map((item: any) => `- **${item.ip}**: ${item.count} başarısız deneme (${item.country || 'Unknown'})`).join('\n') || '- Belirtilmedi';
return `### SIEM Güvenlik Olayı ve Adli Tahlil Raporu (Heuristic SOC Engine)
#### 1. Yönetici Özeti
İncelenen sistem loglarında toplam **${data.totalEvents || 0}** adet olay analiz edilmiş ve **${data.failedAttempts || 0}** adet anormal oturum açma / yetkisiz erişim teşebbüsü saptanmıştır. Sistemde **${data.threatIpCount || 0}** adet yüksek riskli tehdit kaynağı IP adresi belirlenmiştir.
#### 2. Tehdit Vektörü ve MITRE ATT&CK Analizi
- **T1110.001 - Brute Force (Password Guessing):** Çok sayıda geçersiz kullanıcı adı ve sözlük saldırısı tespit edildi.
- **T1078.003 - Valid Accounts (Local Accounts):** Özellikle 'root', 'admin' ve 'ubuntu' gibi kritik hesaplara yönelik hedefli denemeler saptandı.
- **T1046 - Network Service Discovery:** Farklı port ve servislerin yoklandığı görüldü.
#### 3. Tespit Edilen Başlıca Saldırgan IP'ler
${topIps}
#### 4. iptables & Acil Önlem Tavsiyeleri
1. **Otomatik Bloklama:** Eşik değeri aşan IP'ler iptables INPUT zincirine DROP kuralı olarak eklendi:
\`\`\`bash
iptables -A INPUT -s <SALDIRGAN_IP> -j DROP
\`\`\`
2. **SSH Güvenliği:** \`/etc/ssh/sshd_config\` dosyasında \`PermitRootLogin no\` ve \`PasswordAuthentication no\` ayarlarını uygulayarak yalnızca SSH Public Key yetkilendirmesi kullanın.
3. **Port Değişimi & Fail2ban:** Standart 22 portunu rastgele bir yüksek porta taşıyın ve fail2ban servisini aktif hale getirin.`;
}
function generateHeuristicIpAnalysis(ipData: any) {
return `### IP Tehdit Değerlendirmesi: ${ipData.ip || 'Bilinmeyen'}
- **Risk Skoru:** ${ipData.riskScore || 85}/100 (Yüksek Risk)
- **Konum / ISP:** ${ipData.city || 'Frankfurt'}, ${ipData.country || 'DE'} - ${ipData.isp || 'Hosting Datacenter / Proxy'}
- **Saldırı Tipi:** SSH Dağıtık Brute-Force & Kullanıcı Numaralandırma (User Enumeration)
- **Hedeflenen Hesaplar:** ${ipData.usernames?.join(', ') || 'root, admin, test, ubuntu'}
**Eylem Planı:**
Bu IP adresinin tüm gelen bağlantıları derhal iptables üzerinden filtrelenmelidir:
\`\`\`bash
sudo iptables -I INPUT -s ${ipData.ip} -j DROP
\`\`\`
Eğer devam eden bir alt ağ saldırısı varsa ilgili CIDR bloğunu (/24) kısıtlayabilirsiniz.`;
}
function generateHeuristicChatReply(msg: string, ctx: any) {
const lower = msg.toLowerCase();
if (lower.includes('iptables') || lower.includes('engel') || lower.includes('block')) {
return `**iptables ile IP Engelleme Rehberi:**
Şüpheli bir IP'yi sunucu seviyesinde tamamen engellemek için:
\`\`\`bash
# Tek bir IP adresini engelle
sudo iptables -A INPUT -s 198.51.100.44 -j DROP
# Belirli bir porta (örn: SSH 22) gelen bağlantıyı engelle
sudo iptables -A INPUT -p tcp -s 198.51.100.44 --dport 22 -j DROP
# Mevcut kuralları satır numaralarıyla listele
sudo iptables -L INPUT -v -n --line-numbers
# Engeli kaldırmak için
sudo iptables -D INPUT <SATIR_NUMARASI>
\`\`\`
AegisLog arayüzündeki **iptables Güvenlik Duvarı** sekmesinden veya dahili CLI terminalinden bu işlemi tek tıkla uygulayabilirsiniz.`;
}
if (lower.includes('brute') || lower.includes('ssh') || lower.includes('auth.log')) {
return `**Linux auth.log Brute-Force Tespiti:**
Linux Debian/Ubuntu sistemlerde kimlik doğrulama logları \`/var/log/auth.log\`, RHEL/CentOS sistemlerde ise \`/var/log/secure\` altındadır.
Tipik bir brute-force saldırısı şu kalıplarla kendini gösterir:
1. \`Failed password for invalid user <user> from <ip>\`
2. \`Failed password for root from <ip>\`
3. \`Received disconnect from <ip>: 11: Bye Bye [preauth]\`
AegisLog, bu satırları otomatik regex ile parse ederek saniyedeki başarısız girişim sıklığına göre anında alarm üretir ve iptables DROP kuralını tetikler.`;
}
return `AegisLog SIEM Asistanı hazır. Sistemde şu anda **${ctx?.threatCount || 0}** adet tehdit ve **${ctx?.bannedIpCount || 0}** adet engellenmiş kural bulunmaktadır.
Logları analiz etmek, iptables kuralları üretmek veya şüpheli bir IP adresini incelemek için komut verebilirsiniz.
Örnek: "198.51.100.44 IP adresini engelle", "Brute-force saldırılarını özetle", "Fail2ban yapılandırması nasıl olmalı?"`;
}
// Start Express server and mount Vite middleware
async function startServer() {
if (process.env.NODE_ENV !== 'production') {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
} else {
app.use(express.static('dist'));
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`[AegisLog SIEM] Server running on http://0.0.0.0:${PORT}`);
});
}
startServer();