-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcsmt.py
More file actions
533 lines (439 loc) · 20.6 KB
/
Copy pathcsmt.py
File metadata and controls
533 lines (439 loc) · 20.6 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
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
#!/usr/bin/env python3
"""
Clipboard Security Monitor Tool
Monitors clipboard content for malicious patterns and provides protection against ClickFix attacks
"""
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import pyperclip
import threading
import time
import re
import json
import os
from datetime import datetime
from typing import List, Dict, Tuple
import sys
# Try to import pystray for system tray functionality
try:
import pystray
from pystray import MenuItem as item
from PIL import Image, ImageDraw
TRAY_AVAILABLE = True
except ImportError:
TRAY_AVAILABLE = False
print("Note: Install 'pystray' and 'Pillow' for system tray support: pip install pystray Pillow")
class ClipboardSecurityMonitor:
def __init__(self):
self.root = tk.Tk()
self.root.title("Clipboard Security Monitor")
self.root.geometry("800x600")
# Configuration
self.config_file = "clipboard_signatures.json"
self.log_file = "clipboard_monitor.log"
# State variables
self.monitoring = False
self.last_clipboard_content = ""
self.monitor_thread = None
self.tray_icon = None
self.is_hidden = False
# Load malicious signatures
self.signatures = self.load_signatures()
# Initialize GUI
self.setup_gui()
# Setup system tray if available
if TRAY_AVAILABLE:
self.setup_system_tray()
# Configure window close behavior
self.root.protocol("WM_DELETE_WINDOW", self.on_window_close)
# Start monitoring
self.start_monitoring()
def load_signatures(self) -> Dict:
"""Load malicious signature patterns from config file"""
default_signatures = {
"powershell_commands": [
r"powershell\.exe.*-encodedcommand",
r"powershell.*-exec.*bypass",
r"IEX\s*\(",
r"Invoke-Expression",
r"downloadstring",
r"net\.webclient",
r"system\.net\.webclient"
],
"cmd_commands": [
r"cmd\.exe.*\/c",
r"certutil.*-urlcache",
r"bitsadmin.*\/transfer",
r"regsvr32.*\/s.*\/n.*\/u.*\/i:",
r"mshta.*http"
],
"script_patterns": [
r"<script.*>.*eval\(",
r"javascript:.*eval\(",
r"vbscript:.*execute",
r"data:text\/html.*base64"
],
"suspicious_urls": [
r"http[s]?:\/\/(?:[a-z0-9\-]+\.)*[a-z0-9\-]+\.[a-z]{2,}\/[a-zA-Z0-9\-\._~:\/?#\[\]@!\$&'\(\)\*\+,;=%]*\.(?:exe|scr|bat|cmd|ps1|vbs|js)",
r"bit\.ly\/[a-zA-Z0-9]+",
r"tinyurl\.com\/[a-zA-Z0-9]+",
r"t\.co\/[a-zA-Z0-9]+"
],
"encoding_patterns": [
r"base64.*decode",
r"frombase64string",
r"[A-Za-z0-9+/]{50,}={0,2}", # Base64 pattern
r"\\x[0-9a-fA-F]{2}", # Hex encoding
]
}
try:
if os.path.exists(self.config_file):
with open(self.config_file, 'r') as f:
return json.load(f)
else:
self.save_signatures(default_signatures)
return default_signatures
except Exception as e:
self.log_message(f"Error loading signatures: {e}")
return default_signatures
def save_signatures(self, signatures: Dict):
"""Save signatures to config file"""
try:
with open(self.config_file, 'w') as f:
json.dump(signatures, f, indent=2)
except Exception as e:
self.log_message(f"Error saving signatures: {e}")
def setup_gui(self):
"""Initialize the GUI components"""
# Create main frame
main_frame = ttk.Frame(self.root, padding="10")
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Configure grid weights
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
main_frame.columnconfigure(1, weight=1)
main_frame.rowconfigure(2, weight=1)
# Status frame
status_frame = ttk.LabelFrame(main_frame, text="Monitor Status", padding="5")
status_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=(0, 10))
self.status_label = ttk.Label(status_frame, text="Status: Monitoring", foreground="green")
self.status_label.grid(row=0, column=0, padx=(0, 20))
self.toggle_button = ttk.Button(status_frame, text="Stop Monitoring", command=self.toggle_monitoring)
self.toggle_button.grid(row=0, column=1)
self.clear_button = ttk.Button(status_frame, text="Clear Clipboard", command=self.clear_clipboard)
self.clear_button.grid(row=0, column=2, padx=(10, 0))
# Clipboard content frame
content_frame = ttk.LabelFrame(main_frame, text="Current Clipboard Content", padding="5")
content_frame.grid(row=1, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
content_frame.columnconfigure(0, weight=1)
content_frame.rowconfigure(0, weight=1)
self.clipboard_text = scrolledtext.ScrolledText(content_frame, height=10, wrap=tk.WORD)
self.clipboard_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Threat analysis frame
analysis_frame = ttk.LabelFrame(main_frame, text="Threat Analysis", padding="5")
analysis_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=(0, 10))
analysis_frame.columnconfigure(0, weight=1)
analysis_frame.rowconfigure(0, weight=1)
self.analysis_text = scrolledtext.ScrolledText(analysis_frame, height=8, wrap=tk.WORD)
self.analysis_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Control buttons frame
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=3, column=0, columnspan=2, pady=(10, 0))
ttk.Button(button_frame, text="Scan Current Clipboard", command=self.scan_current_clipboard).grid(row=0,
column=0,
padx=(0, 10))
ttk.Button(button_frame, text="Edit Signatures", command=self.edit_signatures).grid(row=0, column=1,
padx=(0, 10))
ttk.Button(button_frame, text="View Log", command=self.view_log).grid(row=0, column=2, padx=(0, 10))
# Add tray control button if tray is available
if TRAY_AVAILABLE:
ttk.Button(button_frame, text="Minimize to Tray", command=self.hide_to_tray).grid(row=0, column=3,
padx=(10, 0))
def toggle_monitoring(self):
"""Toggle clipboard monitoring on/off"""
if self.monitoring:
self.stop_monitoring()
else:
self.start_monitoring()
def start_monitoring(self):
"""Start clipboard monitoring"""
self.monitoring = True
self.status_label.config(text="Status: Monitoring", foreground="green")
self.toggle_button.config(text="Stop Monitoring")
if not self.monitor_thread or not self.monitor_thread.is_alive():
self.monitor_thread = threading.Thread(target=self.monitor_clipboard, daemon=True)
self.monitor_thread.start()
def stop_monitoring(self):
"""Stop clipboard monitoring"""
self.monitoring = False
self.status_label.config(text="Status: Stopped", foreground="red")
self.toggle_button.config(text="Start Monitoring")
def monitor_clipboard(self):
"""Monitor clipboard content for changes"""
while self.monitoring:
try:
current_content = pyperclip.paste()
if current_content != self.last_clipboard_content:
self.last_clipboard_content = current_content
self.root.after(0, self.update_display, current_content)
except Exception as e:
self.log_message(f"Clipboard monitoring error: {e}")
time.sleep(0.5) # Check every 500ms
def update_display(self, content: str):
"""Update the GUI with current clipboard content and analysis"""
# Update clipboard content display
self.clipboard_text.delete(1.0, tk.END)
self.clipboard_text.insert(1.0, content)
# Analyze content for threats
threats = self.analyze_content(content)
# Update analysis display
self.analysis_text.delete(1.0, tk.END)
if threats:
self.analysis_text.insert(tk.END, "⚠️ MALICIOUS CONTENT DETECTED!\n\n", "threat")
self.analysis_text.tag_config("threat", foreground="red", font=("TkDefaultFont", 10, "bold"))
for threat in threats:
self.analysis_text.insert(tk.END, f"• {threat}\n")
self.analysis_text.insert(tk.END, "\n🛡️ RECOMMENDATION: Clear clipboard immediately!\n", "warning")
self.analysis_text.tag_config("warning", foreground="orange", font=("TkDefaultFont", 9, "bold"))
# Log the threat
self.log_threat(content, threats)
# Show warning dialog
self.show_threat_warning(threats)
# Show tray notification if hidden
if TRAY_AVAILABLE and self.is_hidden and hasattr(self, 'tray_icon') and self.tray_icon:
threat_count = len(threats)
self.tray_icon.notify(f"⚠️ {threat_count} threat(s) detected in clipboard!")
else:
self.analysis_text.insert(tk.END, "✅ No malicious patterns detected.\n", "safe")
self.analysis_text.tag_config("safe", foreground="green")
self.analysis_text.insert(tk.END, "Clipboard content appears to be safe.")
def analyze_content(self, content: str) -> List[str]:
"""Analyze clipboard content for malicious patterns"""
threats = []
content_lower = content.lower()
for category, patterns in self.signatures.items():
for pattern in patterns:
if re.search(pattern, content, re.IGNORECASE | re.MULTILINE):
threat_desc = f"Detected {category.replace('_', ' ').title()}: {pattern}"
threats.append(threat_desc)
return threats
def show_threat_warning(self, threats: List[str]):
"""Show warning dialog when malicious content is detected"""
threat_list = "\n".join([f"• {threat}" for threat in threats[:3]]) # Show first 3 threats
result = messagebox.askyesno(
"Malicious Content Detected!",
f"The clipboard contains potentially malicious content:\n\n{threat_list}\n\n"
f"Do you want to clear the clipboard for safety?",
icon="warning"
)
if result:
self.clear_clipboard()
def clear_clipboard(self):
"""Clear the clipboard content"""
try:
pyperclip.copy("")
self.log_message("Clipboard cleared by user")
messagebox.showinfo("Success", "Clipboard has been cleared.")
except Exception as e:
messagebox.showerror("Error", f"Failed to clear clipboard: {e}")
def scan_current_clipboard(self):
"""Manually scan current clipboard content"""
try:
content = pyperclip.paste()
self.update_display(content)
except Exception as e:
messagebox.showerror("Error", f"Failed to read clipboard: {e}")
def edit_signatures(self):
"""Open signature editor window"""
editor_window = tk.Toplevel(self.root)
editor_window.title("Edit Malicious Signatures")
editor_window.geometry("600x500")
# Create text editor for signatures
editor_frame = ttk.Frame(editor_window, padding="10")
editor_frame.pack(fill=tk.BOTH, expand=True)
ttk.Label(editor_frame, text="Edit signatures (JSON format):").pack(anchor=tk.W)
signature_editor = scrolledtext.ScrolledText(editor_frame, height=20, wrap=tk.WORD)
signature_editor.pack(fill=tk.BOTH, expand=True, pady=(5, 10))
# Load current signatures
signature_editor.insert(1.0, json.dumps(self.signatures, indent=2))
def save_signatures():
try:
new_signatures = json.loads(signature_editor.get(1.0, tk.END))
self.signatures = new_signatures
self.save_signatures(new_signatures)
messagebox.showinfo("Success", "Signatures updated successfully!")
editor_window.destroy()
except json.JSONDecodeError as e:
messagebox.showerror("Error", f"Invalid JSON format: {e}")
ttk.Button(editor_frame, text="Save", command=save_signatures).pack(pady=(0, 5))
def view_log(self):
"""Show log viewer window"""
log_window = tk.Toplevel(self.root)
log_window.title("Activity Log")
log_window.geometry("700x400")
log_frame = ttk.Frame(log_window, padding="10")
log_frame.pack(fill=tk.BOTH, expand=True)
log_text = scrolledtext.ScrolledText(log_frame, wrap=tk.WORD)
log_text.pack(fill=tk.BOTH, expand=True)
# Load and display log content
try:
if os.path.exists(self.log_file):
with open(self.log_file, 'r') as f:
log_content = f.read()
log_text.insert(1.0, log_content)
else:
log_text.insert(1.0, "No log entries found.")
except Exception as e:
log_text.insert(1.0, f"Error loading log: {e}")
def log_message(self, message: str):
"""Log a message to the log file"""
try:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(self.log_file, 'a') as f:
f.write(f"[{timestamp}] {message}\n")
except Exception:
pass
def create_tray_icon(self):
"""Create an icon for the system tray"""
# Create a simple shield icon
image = Image.new('RGB', (64, 64), color='white')
draw = ImageDraw.Draw(image)
# Draw a shield shape
shield_points = [
(32, 8), # Top center
(48, 16), # Top right
(48, 40), # Right
(32, 56), # Bottom center
(16, 40), # Left
(16, 16), # Top left
(32, 8) # Back to top
]
draw.polygon(shield_points, fill='#2E7D32', outline='#1B5E20')
# Add a checkmark or security symbol
draw.line([(24, 32), (30, 38), (40, 24)], fill='white', width=3)
return image
def setup_system_tray(self):
"""Setup system tray icon and menu"""
if not TRAY_AVAILABLE:
return
# Create tray icon
icon_image = self.create_tray_icon()
# Create menu items
menu_items = (
item('Show Window', self.show_window, default=True),
item('Hide Window', self.hide_window),
item('Toggle Monitoring', self.toggle_monitoring_tray),
item('Clear Clipboard', self.clear_clipboard_tray),
pystray.Menu.SEPARATOR,
item('Scan Clipboard', self.scan_current_clipboard_tray),
item('View Log', self.view_log_tray),
pystray.Menu.SEPARATOR,
item('Exit', self.quit_application)
)
# Create the tray icon
self.tray_icon = pystray.Icon(
"clipboard_monitor",
icon_image,
"Clipboard Security Monitor",
menu=pystray.Menu(*menu_items)
)
def show_window(self, icon=None, item=None):
"""Show the main window"""
self.root.deiconify()
self.root.lift()
self.root.focus_force()
self.is_hidden = False
def hide_window(self, icon=None, item=None):
"""Hide the main window"""
self.root.withdraw()
self.is_hidden = True
def hide_to_tray(self):
"""Hide window to system tray"""
if TRAY_AVAILABLE:
self.hide_window()
# Show tray notification
if hasattr(self, 'tray_icon') and self.tray_icon:
self.tray_icon.notify("Clipboard Security Monitor is running in the background")
else:
messagebox.showinfo("Info", "System tray not available. Install 'pystray' and 'Pillow' packages.")
def toggle_monitoring_tray(self, icon=None, item=None):
"""Toggle monitoring from tray menu"""
self.toggle_monitoring()
status = "enabled" if self.monitoring else "disabled"
if hasattr(self, 'tray_icon') and self.tray_icon:
self.tray_icon.notify(f"Clipboard monitoring {status}")
def clear_clipboard_tray(self, icon=None, item=None):
"""Clear clipboard from tray menu"""
self.clear_clipboard()
def scan_current_clipboard_tray(self, icon=None, item=None):
"""Scan clipboard from tray menu"""
try:
content = pyperclip.paste()
threats = self.analyze_content(content)
if threats:
threat_count = len(threats)
if hasattr(self, 'tray_icon') and self.tray_icon:
self.tray_icon.notify(f"⚠️ {threat_count} threat(s) detected in clipboard!")
self.show_window() # Show window to display details
else:
if hasattr(self, 'tray_icon') and self.tray_icon:
self.tray_icon.notify("✅ Clipboard content is safe")
except Exception as e:
if hasattr(self, 'tray_icon') and self.tray_icon:
self.tray_icon.notify(f"Error scanning clipboard: {str(e)[:50]}")
def view_log_tray(self, icon=None, item=None):
"""View log from tray menu"""
self.show_window()
self.view_log()
def on_window_close(self):
"""Handle window close event"""
if TRAY_AVAILABLE:
# Minimize to tray instead of closing
self.hide_to_tray()
else:
self.quit_application()
def quit_application(self, icon=None, item=None):
"""Completely quit the application"""
self.stop_monitoring()
if TRAY_AVAILABLE and self.tray_icon:
self.tray_icon.stop()
self.root.quit()
self.root.destroy()
sys.exit(0) # Silently fail if logging fails
def log_threat(self, content: str, threats: List[str]):
"""Log detected threat information"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
threat_summary = "; ".join(threats[:3]) # Log first 3 threats
content_preview = content[:100] + "..." if len(content) > 100 else content
log_entry = (f"[{timestamp}] THREAT DETECTED: {threat_summary}\n"
f"Content preview: {content_preview}\n"
f"{'=' * 80}\n")
try:
with open(self.log_file, 'a') as f:
f.write(log_entry)
except Exception:
pass
def run(self):
"""Run the application"""
# Start tray icon in a separate thread if available
if TRAY_AVAILABLE and self.tray_icon:
tray_thread = threading.Thread(target=self.tray_icon.run, daemon=True)
tray_thread.start()
self.root.mainloop()
def on_closing(self):
"""Handle application closing - deprecated, use quit_application instead"""
self.quit_application()
def main():
"""Main function to run the clipboard security monitor"""
try:
app = ClipboardSecurityMonitor()
app.run()
except ImportError as e:
if "pyperclip" in str(e):
print("Error: pyperclip module is required. Install it with: pip install pyperclip")
else:
print(f"Import error: {e}")
except Exception as e:
print(f"Application error: {e}")
if __name__ == "__main__":
main()