-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmonitor.py
More file actions
553 lines (439 loc) · 19.4 KB
/
monitor.py
File metadata and controls
553 lines (439 loc) · 19.4 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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
"""
monitor.py - ProjectSentry File Encryption Monitor
Integrated setup wizard and file monitoring system
"""
# Imports
import os
import sys
import configparser
import getpass
import hashlib
import json
import logging
import time
from pathlib import Path
from datetime import datetime, timedelta
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# Import our modules
from security import encrypt_file, decrypt_file
from hardware import is_dongle_present
# ========== SETUP FUNCTIONS (Merged from setup.py) ==========
def print_header():
"""Print setup wizard header"""
print("=" * 60)
print("[INFO] PROJECT SENTRY - INITIAL SETUP WIZARD")
print("=" * 60)
print("Welcome to ProjectSentry! Let's set up your secure file vault.")
print("This setup will only run once to configure your system.\n")
def get_master_password():
"""Get and verify master password from user"""
print("[INFO] STEP 1: SET YOUR MASTER PASSWORD")
print("-" * 40)
print("Your master password will be used to encrypt all files.")
print("[WARNING] IMPORTANT: If you lose this password, your files cannot be recovered!")
print("[INFO] Recommendation: Use a strong password with at least 12 characters\n")
while True:
password1 = getpass.getpass("Enter your master password: ").strip()
if len(password1) == 0:
print("[ERROR] Password cannot be empty. Please try again.\n")
continue
if len(password1) < 8:
print("[WARNING] Warning: Password is shorter than 8 characters.")
confirm = input("Continue anyway? (y/n): ").lower()
if confirm != 'y':
continue
password2 = getpass.getpass("Confirm your master password: ").strip()
if password1 != password2:
print("[ERROR] Passwords don't match. Please try again.\n")
continue
# Create password hash for verification (not storage - we don't store passwords)
password_strength = analyze_password_strength(password1)
print(f"[SUCCESS] Password set successfully!")
print(f"[INFO] Password strength: {password_strength}")
return password1
def analyze_password_strength(password):
"""Analyze password strength"""
score = 0
if len(password) >= 8:
score += 1
if len(password) >= 12:
score += 1
if any(c.islower() for c in password):
score += 1
if any(c.isupper() for c in password):
score += 1
if any(c.isdigit() for c in password):
score += 1
if any(c in "!@#$%^&*()_+-=[]{}|;:,.<>?" for c in password):
score += 1
if score <= 2:
return "Weak"
elif score <= 4:
return "Medium"
else:
return "Strong"
def setup_vault_directory():
"""Setup the vault directory for monitoring"""
print("\n[INFO] STEP 2: CONFIGURE YOUR VAULT DIRECTORY")
print("-" * 40)
print("Choose a directory that ProjectSentry will monitor for new files.")
print("Any file placed in this directory will be automatically encrypted.\n")
while True:
print("Options:")
print("1. Use default vault directory (recommended)")
print("2. Choose custom directory")
print("3. Create new directory")
choice = input("\nEnter your choice (1-3): ").strip()
if choice == '1':
# Default directory
home_dir = Path.home()
vault_dir = home_dir / "ProjectSentry_Vault"
break
elif choice == '2':
# Custom directory
custom_path = input("Enter full path to your vault directory: ").strip()
vault_dir = Path(custom_path)
if not vault_dir.exists():
print(f"[ERROR] Directory doesn't exist: {vault_dir}")
create = input("Create this directory? (y/n): ").lower()
if create != 'y':
continue
break
elif choice == '3':
# Create new directory
dir_name = input("Enter directory name: ").strip()
if not dir_name:
print("[ERROR] Directory name cannot be empty.")
continue
location = input("Enter parent directory path (or press Enter for Desktop): ").strip()
if not location:
location = Path.home() / "Desktop"
else:
location = Path(location)
vault_dir = location / dir_name
break
else:
print("[ERROR] Invalid choice. Please enter 1, 2, or 3.")
# Create the directory if it doesn't exist
try:
vault_dir.mkdir(parents=True, exist_ok=True)
print(f"[SUCCESS] Vault directory ready: {vault_dir}")
return str(vault_dir.absolute())
except Exception as e:
print(f"[ERROR] Error creating directory: {e}")
return None
def create_config_file(vault_directory):
"""Create the config.ini file from template"""
print("\n[INFO] STEP 3: CREATING CONFIGURATION FILE")
print("-" * 40)
config = configparser.ConfigParser()
# Settings section
config['Settings'] = {
'watch_directory': vault_directory,
'delete_original_after_encryption': 'false',
'encrypted_file_extension': '.enc',
'encrypt_all_files': 'true'
}
# Hardware section
config['Hardware'] = {
'dongle_id': 'ProjectSentryKey_Alpha_9182',
'hardware_required': 'true'
}
# System section
config['System'] = {
'setup_completed': 'true',
'version': '1.0'
}
try:
with open('config.ini', 'w') as f:
config.write(f)
print("[SUCCESS] Configuration file created successfully!")
return True
except Exception as e:
print(f"[ERROR] Error creating config file: {e}")
return False
def print_setup_complete(vault_directory):
"""Print setup completion message"""
print("\n" + "=" * 60)
print("[SUCCESS] SETUP COMPLETED SUCCESSFULLY!")
print("=" * 60)
print("Your ProjectSentry system is now configured and ready to use.\n")
print("[INFO] SETUP SUMMARY:")
print(f" [INFO] Master password: Set and verified")
print(f" [INFO] Vault directory: {vault_directory}")
print(f" [INFO] Configuration: Saved to config.ini")
print(f" [INFO] Hardware: Mock dongle (for testing)")
print("\n[INFO] NEXT STEPS:")
print("1. The system will now start monitoring automatically")
print("2. Add files to your vault directory to test encryption")
print("3. The system will automatically encrypt new files")
print("\n[WARNING] IMPORTANT REMINDERS:")
print("• Remember your master password - it cannot be recovered!")
print("• Keep your ProjectSentry dongle connected when using the system")
print("• Encrypted files will have '.enc' extension")
print("\n" + "=" * 60)
def run_first_time_setup():
"""Run the complete first-time setup process"""
print_header()
try:
# Step 1: Master Password
master_password = get_master_password()
# Step 2: Vault Directory
vault_directory = setup_vault_directory()
if not vault_directory:
print("[ERROR] Setup failed: Could not configure vault directory")
return None, None
# Step 3: Create Configuration
if not create_config_file(vault_directory):
print("[ERROR] Setup failed: Could not create configuration file")
return None, None
# Show completion message
print_setup_complete(vault_directory)
return master_password, vault_directory
except KeyboardInterrupt:
print("\n\n[WARNING] Setup cancelled by user.")
print("Run the program again to complete setup.")
return None, None
except Exception as e:
print(f"\n[ERROR] Setup failed with error: {e}")
print("Please try running setup again.")
return None, None
# ========== MONITORING FUNCTIONS ==========
def load_config():
"""Load configuration from config.ini file"""
config = configparser.ConfigParser()
try:
config.read('config.ini')
# Check if setup was completed
if not config.has_option('System', 'setup_completed') or not config.getboolean('System', 'setup_completed'):
print("[ERROR] System setup not completed!")
return None, None, None, None
watch_directory = config.get('Settings', 'watch_directory')
dongle_id = config.get('Hardware', 'dongle_id', fallback='DEVELOPMENT_MODE')
encrypt_all = config.getboolean('Settings', 'encrypt_all_files', fallback=False)
allowed_extensions = []
if not encrypt_all and config.has_section('FileTypes'):
ext_string = config.get('FileTypes', 'allowed_extensions', fallback='')
if ext_string:
allowed_extensions = [ext.strip() for ext in ext_string.split(',')]
if not os.path.exists(watch_directory):
print(f"[ERROR] Watch directory '{watch_directory}' does not exist!")
return None, None, None, None
return watch_directory, dongle_id, encrypt_all, allowed_extensions
except (configparser.NoSectionError, configparser.NoOptionError) as e:
print(f"[ERROR] Error reading config.ini: {e}")
return None, None, None, None
class EncryptionEventHandler(FileSystemEventHandler):
"""Enhanced event handler for file system events with improved debouncing"""
def __init__(self, master_password, dongle_id, encrypt_all=True, allowed_extensions=None):
super().__init__()
self.master_password = master_password
self.dongle_id = dongle_id
self.encrypt_all = encrypt_all
self.allowed_extensions = allowed_extensions or []
# Enhanced debouncing system - simplified as per requirements
self.recent_events = {} # file_path -> timestamp
self.debounce_seconds = 2 # Ignore events within 2 seconds
logging.info(f"Event handler initialized with password length: {len(master_password)}")
if encrypt_all:
logging.info("File filter: ALL file types will be encrypted")
else:
logging.info(
f"File filter: Only {len(self.allowed_extensions)} file types: {', '.join(self.allowed_extensions)}")
def should_process_event(self, file_path):
"""Simplified debouncing - ignore events for same file within 2 seconds"""
current_time = datetime.now()
# Check if this file had a recent event
if file_path in self.recent_events:
time_diff = current_time - self.recent_events[file_path]
if time_diff < timedelta(seconds=self.debounce_seconds):
return False
# Update timestamp and clean old entries
self.recent_events[file_path] = current_time
# Clean up old entries (older than 5 minutes)
cutoff_time = current_time - timedelta(minutes=5)
self.recent_events = {k: v for k, v in self.recent_events.items() if v > cutoff_time}
return True
def should_encrypt_file(self, file_path):
"""Check if file should be encrypted based on configuration"""
# Skip if file is already encrypted
if file_path.endswith('.enc'):
return False, "Already encrypted"
# Skip system files and hidden files
filename = os.path.basename(file_path)
if filename.startswith('.') or filename.startswith('~'):
return False, "System/hidden file"
# Skip empty files
try:
if os.path.getsize(file_path) == 0:
return False, "Empty file"
except OSError:
return False, "File access error"
# If encrypt_all is True, encrypt everything (except already filtered above)
if self.encrypt_all:
return True, "All files mode"
# Check file extension
file_extension = os.path.splitext(file_path)[1].lower()
if file_extension in self.allowed_extensions:
return True, f"Allowed extension: {file_extension}"
else:
return False, f"Extension not allowed: {file_extension}"
def on_created(self, event):
"""Handle file creation events"""
if not event.is_directory:
if self.should_process_event(event.src_path):
filename = os.path.basename(event.src_path)
logging.info(f"FILE CREATED: {filename}")
self.process_file(event.src_path, "CREATED")
def on_moved(self, event):
"""Handle file move/rename events"""
if not event.is_directory:
if self.should_process_event(event.dest_path):
old_name = os.path.basename(event.src_path)
new_name = os.path.basename(event.dest_path)
if os.path.dirname(event.src_path) == os.path.dirname(event.dest_path):
logging.info(f"FILE RENAMED: '{old_name}' -> '{new_name}'")
self.process_file(event.dest_path, "RENAMED")
else:
logging.info(f"FILE MOVED: '{old_name}' to '{new_name}'")
self.process_file(event.dest_path, "MOVED")
def on_modified(self, event):
"""Handle file modification events"""
if not event.is_directory:
if self.should_process_event(event.src_path):
filename = os.path.basename(event.src_path)
logging.info(f"FILE MODIFIED: {filename}")
self.process_file(event.src_path, "MODIFIED")
def process_file(self, file_path, operation_type):
"""Process detected file using integrated modules"""
filename = os.path.basename(file_path)
# Check if file should be encrypted
should_encrypt, reason = self.should_encrypt_file(file_path)
if not should_encrypt:
logging.info(f"SKIPPED: {filename} - {reason}")
return
logging.info(f"CHECKING HARDWARE DONGLE...")
# Use the actual hardware check function from hardware.py
if not is_dongle_present():
logging.warning("Hardware dongle not detected! File encryption aborted.")
logging.warning("Please ensure the ProjectSentry dongle is connected.")
return
logging.info(f"Hardware dongle verified!")
logging.info(f"Processing {operation_type} operation on: {filename} - {reason}")
try:
# Use the actual encrypt_file function from security.py with permission handling
encrypted_path = encrypt_file(file_path, self.master_password)
logging.info(f"Successfully encrypted: {filename}")
logging.info(f"Encrypted file created: {os.path.basename(encrypted_path)}")
except PermissionError:
logging.error("Permission denied. Cannot write to the target folder. Please check your folder permissions.")
except Exception as e:
logging.error(f"Encryption failed for {filename}: {e}")
def setup_logging():
"""Configure logging to both console and file"""
# Create formatter
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# Setup file handler
file_handler = logging.FileHandler('activity.log')
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)
# Setup console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(logging.Formatter('%(levelname)s - %(message)s'))
# Setup root logger
logging.basicConfig(
level=logging.INFO,
handlers=[file_handler, console_handler]
)
def main():
"""Main function to run the encryption monitor"""
# Setup logging first
setup_logging()
print("[INFO] PROJECTSENTRY FILE ENCRYPTION SYSTEM")
print("=" * 50)
# Check if config.ini exists - if not, run first-time setup
if not os.path.exists('config.ini'):
logging.info("Configuration file not found. Starting first-time setup...")
master_password, vault_directory = run_first_time_setup()
if master_password is None:
logging.error("Setup failed or was cancelled. Exiting.")
sys.exit(1)
logging.info("Setup completed successfully! Starting monitoring...")
else:
# Load existing configuration
try:
watch_directory, dongle_id, encrypt_all, allowed_extensions = load_config()
if watch_directory is None:
logging.error("Failed to load configuration. Please check config.ini")
sys.exit(1)
except Exception as e:
logging.error(f"Configuration error: {e}")
sys.exit(1)
# Get master password
print("\n" + "=" * 50)
print("[INFO] ENTER YOUR MASTER PASSWORD")
print("=" * 50)
print("Enter the master password you set during initial setup.")
try:
master_password = getpass.getpass("Master Password: ")
if not master_password:
logging.error("Password cannot be empty!")
sys.exit(1)
logging.info(f"Password received! (Length: {len(master_password)})")
# NEW: Always analyze password strength on each run
strength = analyze_password_strength(master_password)
logging.info(f"Password strength: {strength}")
except KeyboardInterrupt:
print("\nOperation cancelled by user.")
sys.exit(0)
vault_directory = watch_directory
logging.info("System configured and ready!")
logging.info("Using integrated security.py and hardware.py modules")
# Initial hardware check
logging.info("PERFORMING INITIAL HARDWARE VERIFICATION...")
if not is_dongle_present():
logging.error("Hardware dongle not detected!")
logging.warning("Please connect the ProjectSentry dongle and try again.")
return
logging.info("Initial hardware verification successful!")
# Set up monitoring
logging.info("Setting up intelligent file monitor...")
event_handler = EncryptionEventHandler(master_password, "ProjectSentryKey_Alpha_9182", True, [])
observer = Observer()
observer.schedule(event_handler, vault_directory, recursive=True)
try:
observer.start()
print("\n" + "=" * 60)
print("[SUCCESS] PROJECTSENTRY ENCRYPTION MONITOR STARTED!")
print("=" * 60)
print(f"[INFO] Monitoring: {vault_directory}")
print("[INFO] Modules integrated:")
print(" [INFO] security.py - Real AES-GCM encryption")
print(" [INFO] hardware.py - Dongle verification (mock)")
print("[INFO] Features enabled:")
print(" [INFO] Enhanced event debouncing (2-second window)")
print(" [INFO] Professional logging to activity.log")
print(" [INFO] Permission error handling")
print(" [INFO] File filter: ALL file types")
print("[INFO] Press Ctrl+C to stop")
print("=" * 60)
print("\n[INFO] Ready! Perform file operations in the watch directory...\n")
logging.info("Monitor started successfully")
logging.info(f"Monitoring directory: {vault_directory}")
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\n" + "=" * 40)
print("[INFO] STOPPING MONITOR...")
print("=" * 40)
observer.stop()
logging.info("Monitor stopped successfully!")
except Exception as e:
logging.error(f"Monitor error: {e}")
observer.stop()
finally:
observer.join()
if __name__ == '__main__':
main()