source: sctry.py@ 2058e5c

Last change on this file since 2058e5c was 2058e5c, checked in by istevanoska <ilinastevanoska@…>, 6 months ago

Working / before login

  • Property mode set to 100644
File size: 19.9 KB
RevLine 
[640ed89]1#!/usr/bin/env python3
2"""
3POPRAVEN CLIENT со фикс за Sysmon
4"""
5
6import socket
7import os
8import platform
9import json
10import requests
11from datetime import datetime, timedelta
12import psutil
13import time
14import subprocess
15import re
16from collections import defaultdict
17
18
19class FixedSysmonCollector:
20 """Симплифициран колектор што работи без инсталиран Sysmon"""
21
22 def __init__(self):
23 self.last_collection = None
24
25 def collect_sysmon_events(self, limit=50):
26 """Симулирај Sysmon настани од процеси и мрежа"""
27 events = []
28
29 try:
30 # 1. Процес настани (Event ID 1 = Process Creation)
31 for proc in psutil.process_iter(['pid', 'name', 'create_time', 'username']):
32 try:
33 pinfo = proc.info
34 if pinfo['create_time']:
35 create_time = datetime.fromtimestamp(pinfo['create_time'])
36 # Додади само процеси креирани во последните 5 минути
37 if not self.last_collection or create_time > self.last_collection:
38 events.append({
39 "event_id": 1,
40 "event_type": "Process Creation",
41 "message": f"Process created: {pinfo['name']} (PID: {pinfo['pid']}, User: {pinfo['username']})",
42 "timestamp": create_time.isoformat(),
43 "process_name": pinfo['name'],
44 "pid": pinfo['pid'],
45 "user": pinfo['username']
46 })
47 except (psutil.NoSuchProcess, psutil.AccessDenied):
48 continue
49
50 if len(events) >= limit // 2:
51 break
52
53 # 2. Мрежни конекции (Event ID 3 = Network Connection)
54 for conn in psutil.net_connections(kind='inet'):
55 try:
56 if conn.raddr and conn.status in ['ESTABLISHED', 'LISTEN']:
57 proc = psutil.Process(conn.pid) if conn.pid else None
58 events.append({
59 "event_id": 3,
60 "event_type": "Network Connection",
61 "message": f"Network {conn.status}: {conn.laddr.ip if conn.laddr else 'N/A'}:{conn.laddr.port if conn.laddr else 'N/A'} -> {conn.raddr.ip}:{conn.raddr.port}",
62 "timestamp": datetime.now().isoformat(),
63 "local_address": f"{conn.laddr.ip}:{conn.laddr.port}" if conn.laddr else None,
64 "remote_address": f"{conn.raddr.ip}:{conn.raddr.port}",
65 "status": conn.status,
66 "pid": conn.pid,
67 "process_name": proc.name() if proc else "Unknown"
68 })
69 except (psutil.NoSuchProcess, psutil.AccessDenied):
70 continue
71
72 if len(events) >= limit:
73 break
74
75 # 3. Системски перформанси настани
76 cpu = psutil.cpu_percent(interval=0.1)
77 if cpu > 80:
78 events.append({
79 "event_id": "PERF_HIGH_CPU",
80 "event_type": "High CPU Usage",
81 "message": f"High CPU usage detected: {cpu:.1f}%",
82 "timestamp": datetime.now().isoformat(),
83 "cpu_percent": cpu
84 })
85
86 ram = psutil.virtual_memory()
87 if ram.percent > 85:
88 events.append({
89 "event_id": "PERF_HIGH_RAM",
90 "event_type": "High Memory Usage",
91 "message": f"High RAM usage: {ram.percent:.1f}%",
92 "timestamp": datetime.now().isoformat(),
93 "ram_percent": ram.percent
94 })
95
96 except Exception as e:
97 print(f"FixedSysmon error: {e}")
98
99 self.last_collection = datetime.now()
100 return events
101
102 def collect_network_connections_detailed(self):
103 """Детални мрежни конекции"""
104 connections = []
105 try:
106 for conn in psutil.net_connections(kind='inet'):
107 try:
108 proc = psutil.Process(conn.pid) if conn.pid else None
109
110 conn_info = {
111 "pid": conn.pid,
112 "status": conn.status,
113 "family": str(conn.family),
114 "type": str(conn.type),
115 "timestamp": datetime.now().isoformat()
116 }
117
118 if conn.laddr:
119 conn_info["local_address"] = f"{conn.laddr.ip}:{conn.laddr.port}"
120 conn_info["local_ip"] = conn.laddr.ip
121 conn_info["local_port"] = conn.laddr.port
122
123 if conn.raddr:
124 conn_info["remote_address"] = f"{conn.raddr.ip}:{conn.raddr.port}"
125 conn_info["remote_ip"] = conn.raddr.ip
126 conn_info["remote_port"] = conn.raddr.port
127
128 if proc:
129 conn_info.update({
130 "process_name": proc.name(),
131 "process_cmdline": ' '.join(proc.cmdline()) if proc.cmdline() else None,
132 "process_username": proc.username() if hasattr(proc, 'username') else None
133 })
134
135 connections.append(conn_info)
136
137 except (psutil.NoSuchProcess, psutil.AccessDenied):
138 continue
139
140 if len(connections) >= 30:
141 break
142
143 except Exception as e:
144 print(f"Network connections error: {e}")
145
146 return connections
147
148 def collect_all_security_data(self):
149 """Собери сите безбедносни податоци (очекуваниот метод!)"""
150 return {
151 "sysmon_events": self.collect_sysmon_events(limit=50),
152 "network_connections": self.collect_network_connections_detailed(),
153 "file_changes": [], # Празен лист, можеш да го имплементираш подоцна
154 "collection_time": datetime.now().isoformat()
155 }
156
157
158class EnhancedFixedClient:
[2058e5c]159 def __init__(self, server_ip="192.168.1.13", port=5555, env_token=None):
[640ed89]160 self.server_ip = server_ip
161 self.port = port
162 self.computer_name = socket.gethostname()
163 self.user = os.getlogin()
[2058e5c]164 self.sysmon_collector = FixedSysmonCollector()
165 self.env_token = env_token
166 # Користи поправената верзија
[640ed89]167
168 def get_detailed_info(self):
169 """Собирај подробни податоци"""
170 info = {
171 "computer_name": self.computer_name,
172 "user": self.user,
173 "ip_address": socket.gethostbyname(self.computer_name),
174 "os": f"{platform.system()} {platform.release()} {platform.version()}",
175 "architecture": platform.architecture()[0],
176 "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
177 "is_sysmon_available": self._check_sysmon_installed()
178 }
179
180 info.update(self.get_performance_metrics())
181 info.update(self.get_hardware_info())
182
183 return info
184
185 def _check_sysmon_installed(self):
186 """Провери дали Sysmon е инсталиран"""
187 try:
188 if platform.system() == "Windows":
189 result = subprocess.run(
190 ["powershell", "-Command", "Get-Process -Name 'sysmon' -ErrorAction SilentlyContinue"],
191 capture_output=True, text=True
192 )
193 return result.returncode == 0
194 except:
195 pass
196 return False
197
198 def get_performance_metrics(self):
199 """Метрики за перформанси - ПОПРАВЕНО БЕЗ DEPRECATION WARNING"""
200 try:
201 cpu_percent = psutil.cpu_percent(interval=1)
202 cpu_freq = psutil.cpu_freq()
203
204 ram = psutil.virtual_memory()
205 swap = psutil.swap_memory()
206
207 disk = psutil.disk_usage("C:/" if platform.system() == "Windows" else "/")
208
209 # ДОБАВИ TRY-EXCEPT за disk_io_counters
210 disk_read_mb = 0
211 disk_write_mb = 0
212 try:
213 disk_io = psutil.disk_io_counters()
214 if disk_io:
215 disk_read_mb = round(disk_io.read_bytes / (1024 ** 2), 2)
216 disk_write_mb = round(disk_io.write_bytes / (1024 ** 2), 2)
217 except:
218 pass
219
220 net_io = psutil.net_io_counters()
221
222 return {
223 "cpu_usage": cpu_percent,
224 "cpu_cores": psutil.cpu_count(logical=True),
225 "cpu_freq_current": cpu_freq.current if cpu_freq else 0,
226 "ram_usage": ram.percent,
227 "ram_total_gb": round(ram.total / (1024 ** 3), 2),
228 "ram_used_gb": round(ram.used / (1024 ** 3), 2),
229 "swap_usage": swap.percent if swap else 0,
230 "disk_usage": disk.percent,
231 "disk_total_gb": round(disk.total / (1024 ** 3), 2),
232 "disk_used_gb": round(disk.used / (1024 ** 3), 2),
233 "disk_read_mb": disk_read_mb,
234 "disk_write_mb": disk_write_mb,
235 "network_sent_mb": round(net_io.bytes_sent / (1024 ** 2), 2),
236 "network_recv_mb": round(net_io.bytes_recv / (1024 ** 2), 2),
237 "network_packets_sent": net_io.packets_sent,
238 "network_packets_recv": net_io.packets_recv,
239 "boot_time": datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"),
240 "uptime_hours": round((datetime.now() - datetime.fromtimestamp(psutil.boot_time())).seconds / 3600, 2)
241 }
242 except Exception as e:
243 print(f"Performance metrics error: {e}")
244 return {}
245
246 def get_hardware_info(self):
247 """Хардвер информации"""
248 try:
249 partitions = []
250 for partition in psutil.disk_partitions():
251 try:
252 usage = psutil.disk_usage(partition.mountpoint)
253 partitions.append({
254 "device": partition.device,
255 "mountpoint": partition.mountpoint,
256 "fstype": partition.fstype,
257 "total_gb": round(usage.total / (1024 ** 3), 2),
258 "used_gb": round(usage.used / (1024 ** 3), 2),
259 "free_gb": round(usage.free / (1024 ** 3), 2),
260 "percent_used": usage.percent
261 })
262 except:
263 continue
264
265 # Мрежни интерфејси
266 net_if_addrs = psutil.net_if_addrs()
267 interfaces = {}
268 for interface, addrs in net_if_addrs.items():
269 interfaces[interface] = [
270 {
271 "family": str(addr.family),
272 "address": addr.address,
273 "netmask": addr.netmask if hasattr(addr, 'netmask') else None
274 }
275 for addr in addrs if addr.address
276 ]
277
278 return {
279 "cpu_physical_cores": psutil.cpu_count(logical=False),
280 "cpu_logical_cores": psutil.cpu_count(logical=True),
281 "disks": partitions,
282 "network_interfaces": interfaces,
283 "battery_percent": psutil.sensors_battery().percent if hasattr(psutil.sensors_battery(),
284 'percent') else None,
285 "temperatures": self._get_temperatures()
286 }
287 except Exception as e:
288 print(f"Hardware info error: {e}")
289 return {}
290
291 def _get_temperatures(self):
292 """Добиј температури на системот"""
293 try:
294 temps = {}
295 if hasattr(psutil, 'sensors_temperatures'):
296 sensors = psutil.sensors_temperatures()
297 for name, entries in sensors.items():
298 if entries:
299 temps[name] = entries[0].current
300 return temps
301 except:
302 return {}
303
304 def get_detailed_processes(self):
305 """Детални информации за процесите - ПОПРАВЕНО БЕЗ DEPRECATION WARNING"""
306 processes = []
307 try:
308 for proc in psutil.process_iter(['pid', 'name', 'username', 'cpu_percent',
309 'memory_percent', 'create_time', 'status']):
310 try:
311 pinfo = proc.info
312
313 # КОРИСТИ psutil.Process() за да добиеш дополнителни информации
314 with proc.oneshot():
315 processes.append({
316 "pid": pinfo['pid'],
317 "name": pinfo['name'],
318 "user": pinfo['username'],
319 "cpu_percent": pinfo['cpu_percent'],
320 "memory_mb": round(proc.memory_info().rss / (1024 ** 2), 2),
321 "memory_percent": pinfo['memory_percent'],
322 "create_time": datetime.fromtimestamp(pinfo['create_time']).strftime("%Y-%m-%d %H:%M:%S") if
323 pinfo['create_time'] else None,
324 "status": pinfo['status'],
325 "exe": proc.exe() if hasattr(proc, 'exe') else None,
326 "cmdline": ' '.join(proc.cmdline()) if hasattr(proc, 'cmdline') else None,
327 "num_threads": proc.num_threads() if hasattr(proc, 'num_threads') else None,
328 # НЕ КОРИСТИ proc.connections() - тоа е deprecated!
329 "connections_count": 0 # Стави 0 или избриши го ова поле
330 })
331 except (psutil.NoSuchProcess, psutil.AccessDenied):
332 continue
333
334 if len(processes) >= 100:
335 break
336
337 except Exception as e:
338 print(f"Process error: {e}")
339
340 return processes
341
342 def collect_and_send(self):
343 """Собери и испрати сите податоци"""
344 print(f"\n[{datetime.now().strftime('%H:%M:%S')}] 🔍 Собирање податоци...")
345
346 # Собери сите податоци
347 data = {
348 "info": self.get_detailed_info(),
349 "processes": self.get_detailed_processes(),
350 "security_data": self.sysmon_collector.collect_all_security_data(), # ОВА СЕГА РАБОТИ!
351 "collection_time": datetime.now().isoformat(),
352 "client_version": "2.1_fixed"
353 }
354
355 # Прикажи основни информации
356 info = data["info"]
357 sec_data = data["security_data"]
358
359 print(f" 💻 Компјутер: {info['computer_name']}")
360 print(f" 👤 Корисник: {info['user']}")
361 print(
362 f" 📊 CPU: {info.get('cpu_usage', 0)}% | RAM: {info.get('ram_usage', 0)}% | Disk: {info.get('disk_usage', 0)}%")
363 print(f" 🔄 Процеси: {len(data['processes'])}")
364 print(f" 🛡️ Sysmon настани: {len(sec_data.get('sysmon_events', []))}")
365 print(f" 🌐 Мрежни конекции: {len(sec_data.get('network_connections', []))}")
366
367 # Испрати ги податоците
368 try:
[2058e5c]369 headers = {"X-Env-Token": self.env_token} if self.env_token else {}
370
[640ed89]371 response = requests.post(
372 f"http://{self.server_ip}:{self.port}/receive",
373 json=data,
[2058e5c]374 headers=headers,
[640ed89]375 timeout=30
376 )
377
378 if response.status_code == 200:
379 result = response.json()
380 print(f" ✅ Податоците се успешно испратени!")
381 if 'event_count' in result:
382 print(f" 📝 Зачувани {result['event_count']} Sysmon настани")
383 return True
384 else:
[2058e5c]385 if response.status_code == 401:
386 try:
387 msg = response.json()
388 except:
389 msg = {}
390 print(" 🔒 Token invalid/expired. Побарај нов token од Admin панел.")
391 print(f" Server says: {msg}")
392 else:
393 print(f" ❌ Грешка: {response.status_code}")
394 try:
395 print(" ", response.text[:300])
396 except:
397 pass
[640ed89]398 return False
399
400 except Exception as e:
401 print(f" ❌ Проблем со серверот: {e}")
402 return False
403
404
405def main():
406 """Главна програма"""
407 print("=" * 70)
408 print("🖥️ FIXED LAN LOG COLLECTOR v2.1")
409 print("=" * 70)
410 print(f"Компјутер: {socket.gethostname()}")
411 print(f"Корисник: {os.getlogin()}")
412 print(f"IP: {socket.gethostbyname(socket.gethostname())}")
413 print("=" * 70)
414 print("Податоците ќе се собираат и испраќаат на секои 30 секунди.")
415 print("Притисни Ctrl+C за да го прекинеш.")
416 print("=" * 70)
417
418 # Провери дали серверот е достапен
419 server_ip = input("Внеси сервер IP (default 192.168.1.13): ").strip() or "192.168.1.13"
420
[2058e5c]421 env_token = input("Внеси ENV TOKEN (од Admin панел): ").strip()
422 if not env_token:
423 print("❌ Мора ENV TOKEN за да се регистрира уредот.")
424 return
[640ed89]425
[2058e5c]426 client = EnhancedFixedClient(server_ip, 5555, env_token=env_token)
[640ed89]427 # Тест конекција
428 print(f"\n🔌 Тестирање на врска со серверот {server_ip}...")
429 try:
430 response = requests.get(f"http://{server_ip}:5555/ping", timeout=5)
431 if response.status_code == 200:
432 print(" ✅ Серверот е достапен!")
433 else:
434 print(f" ⚠️ Серверот одговори со: {response.status_code}")
435 confirm = input(" Сакаш ли да продолжиш? (y/n): ").lower()
436 if confirm != 'y':
437 return
438 except Exception as e:
439 print(f" ❌ Не можам да се поврзам со серверот {server_ip}: {e}")
440 confirm = input(" Сакаш ли да продолжиш? (y/n): ").lower()
441 if confirm != 'y':
442 return
443
444 try:
445 count = 1
446 while True:
447 print(f"\n📤 Трансмисија #{count}")
448
449 success = client.collect_and_send()
450
451 count += 1
452 print(f"\n⏳ Чекам 30 секунди до следната трансмисија...")
453
454 # Countdown
455 for i in range(30, 0, -1):
456 if i % 10 == 0 or i <= 5:
457 print(f"\r {i} секунди остануваат...", end="")
458 time.sleep(1)
459 print("\r" + " " * 40 + "\r", end="")
460
461 except KeyboardInterrupt:
462 print("\n\n🛑 Програмата е зајчана.")
463 print(f"📊 Dashboard: http://{server_ip}:5555/")
464
465
466if __name__ == "__main__":
467 try:
468 import psutil
469 import requests
470 except ImportError:
471 print("Инсталирај ги модулите:")
472 print("pip install psutil requests")
473 input("Притисни ENTER за излез...")
474 exit(1)
475
476 main()
Note: See TracBrowser for help on using the repository browser.