-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsecurity.py
More file actions
375 lines (295 loc) · 12.9 KB
/
security.py
File metadata and controls
375 lines (295 loc) · 12.9 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
import os
import hashlib
from Crypto.Cipher import AES
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from Crypto.Hash import SHA256
import getpass
# NEW: imports for optional GUI browse and config-based watch dir check
import tkinter as tk # NEW
from tkinter import filedialog # NEW
import configparser # NEW
def encrypt_file(file_path, password):
"""
Encrypts a file using AES-GCM with PBKDF2 key derivation.
Args:
file_path (str): Path to the file to encrypt
password (str): Password for encryption
Returns:
str: Path to the encrypted file (.enc extension)
Raises:
FileNotFoundError: If the input file doesn't exist
Exception: For other encryption errors
"""
try:
# Check if file exists
if not os.path.exists(file_path):
raise FileNotFoundError(f"File not found: {file_path}")
# Read the original file in binary mode
with open(file_path, 'rb') as f:
plaintext = f.read()
# Generate a random salt (16 bytes)
salt = get_random_bytes(16)
# Derive key using PBKDF2
# Using 100,000 iterations for strong security
key = PBKDF2(password, salt, dkLen=32, count=100000, hmac_hash_module=SHA256)
# Create AES-GCM cipher
cipher = AES.new(key, AES.MODE_GCM)
nonce = cipher.nonce # GCM automatically generates a nonce
# Encrypt the data and get authentication tag
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
# Create encrypted file path
encrypted_file_path = file_path + '.enc'
# Write encrypted data to file
# Format: salt (16 bytes) + nonce (16 bytes) + tag (16 bytes) + ciphertext
with open(encrypted_file_path, 'wb') as f:
f.write(salt)
f.write(nonce)
f.write(tag)
f.write(ciphertext)
os.remove(file_path)
print(f"File encrypted successfully: {encrypted_file_path}")
return encrypted_file_path
except FileNotFoundError:
raise
except Exception as e:
raise Exception(f"Encryption failed: {str(e)}")
def decrypt_file(encrypted_file_path, password, delete_encrypted=True):
"""
Decrypts a file that was encrypted using encrypt_file function.
Args:
encrypted_file_path (str): Path to the encrypted file (.enc)
password (str): Password for decryption
delete_encrypted (bool): Whether to delete the encrypted file after decryption
Returns:
str: Path to the decrypted file
Raises:
FileNotFoundError: If the encrypted file doesn't exist
ValueError: If password is incorrect or file is corrupted
Exception: For other decryption errors
"""
try:
# Check if encrypted file exists
if not os.path.exists(encrypted_file_path):
raise FileNotFoundError(f"Encrypted file not found: {encrypted_file_path}")
# Read the encrypted file
with open(encrypted_file_path, 'rb') as f:
encrypted_data = f.read()
# Verify minimum file size (salt + nonce + tag = 48 bytes minimum)
if len(encrypted_data) < 48:
raise ValueError("Invalid encrypted file format")
# Extract components in the correct order
salt = encrypted_data[:16] # First 16 bytes: salt
nonce = encrypted_data[16:32] # Next 16 bytes: nonce
tag = encrypted_data[32:48] # Next 16 bytes: authentication tag
ciphertext = encrypted_data[48:] # Remaining bytes: encrypted data
# Re-derive the key using the same parameters
from Crypto.Hash import SHA256
key = PBKDF2(password, salt, dkLen=32, count=100000, hmac_hash_module=SHA256)
# Create AES-GCM cipher for decryption
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
# Attempt to decrypt and verify authenticity
try:
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
except ValueError as e:
raise ValueError("Decryption failed: Wrong password or corrupted file")
# Verify decryption result
if plaintext is None:
raise ValueError("Decryption returned None")
if len(plaintext) == 0:
raise ValueError("Decryption returned empty data")
# Determine output file path (remove .enc extension)
if encrypted_file_path.endswith('.enc'):
decrypted_file_path = encrypted_file_path[:-4] # Remove .enc
else:
decrypted_file_path = encrypted_file_path + '.decrypted'
# Ensure target directory exists and is writable
target_dir = os.path.dirname(os.path.abspath(decrypted_file_path))
if not os.access(target_dir, os.W_OK):
raise Exception(f"No write permission to directory: {target_dir}")
# Write decrypted data to file with verification
try:
with open(decrypted_file_path, 'wb') as f:
bytes_written = f.write(plaintext)
f.flush() # Force buffer to disk
os.fsync(f.fileno()) # Force OS to write to disk
# Immediate verification
if not os.path.exists(decrypted_file_path):
raise Exception("File creation failed - file does not exist after write")
file_size = os.path.getsize(decrypted_file_path)
if file_size != len(plaintext):
raise Exception(f"File size mismatch: expected {len(plaintext)}, got {file_size}")
if file_size == 0:
raise Exception("Created file is empty")
except Exception as write_err:
raise Exception(f"File write operation failed: {write_err}")
# Only delete encrypted file after successful verification
if delete_encrypted:
try:
os.remove(encrypted_file_path)
except Exception as del_err:
print(f"Warning: Could not delete encrypted file: {del_err}")
print(f"File decrypted successfully: {decrypted_file_path}")
return decrypted_file_path
except FileNotFoundError:
raise
except ValueError:
raise
except Exception as e:
raise Exception(f"Decryption failed: {str(e)}")
# NEW: helper to get watch directory from config.ini (if present)
def _get_watch_directory():
cfg = configparser.ConfigParser()
if not os.path.exists("config.ini"):
return None
try:
cfg.read("config.ini")
if cfg.has_option("Settings", "watch_directory"):
return cfg.get("Settings", "watch_directory")
except Exception:
return None
return None
# NEW: helper to check if candidate path is inside base path
def _is_inside(base_dir, candidate_path):
if not base_dir:
return False
base = os.path.abspath(base_dir)
cand = os.path.abspath(candidate_path)
try:
return os.path.commonpath([base, cand]) == base
except Exception:
return False
# NEW: quoted-path cleaner for pasted paths (handles Windows “Copy as path”)
import os
import re
import unicodedata
def _clean_path(p: str) -> str:
"""
Cleans a Windows path pasted from 'Copy as Path' or manual input.
Removes surrounding quotes (", ', “, ”, etc.), trims whitespace,
expands environment variables (~, %USERPROFILE%), and normalizes the path.
"""
if not p:
return p
# Normalize Unicode (handles smart quotes and special spaces)
p = unicodedata.normalize("NFKC", p)
# Strip leading/trailing spaces and hidden chars (zero-width, BOM)
p = p.strip().replace("\u200b", "").replace("\ufeff", "")
# Remove wrapping quotes of any type
p = re.sub(r'^[\'\"“”‘’]+|[\'\"“”‘’]+$', '', p)
# Expand user (~) and environment (%VAR%)
p = os.path.expanduser(os.path.expandvars(p))
# Normalize to absolute Windows path
return os.path.normpath(p)
# NEW: decrypt directly to a chosen output path (avoids writing inside watched dir)
def decrypt_file_to(encrypted_file_path, password, output_path, delete_encrypted=True):
"""
Decrypts encrypted_file_path and writes plaintext directly to output_path.
"""
try:
if not os.path.exists(encrypted_file_path):
raise FileNotFoundError(f"Encrypted file not found: {encrypted_file_path}")
with open(encrypted_file_path, 'rb') as f:
encrypted_data = f.read()
if len(encrypted_data) < 48:
raise ValueError("Invalid encrypted file format")
salt = encrypted_data[:16]
nonce = encrypted_data[16:32]
tag = encrypted_data[32:48]
ciphertext = encrypted_data[48:]
key = PBKDF2(password, salt, dkLen=32, count=100000, hmac_hash_module=SHA256)
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
try:
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
except ValueError:
raise ValueError("Decryption failed: Wrong password or corrupted file")
if plaintext is None or len(plaintext) == 0:
raise ValueError("Decryption produced no data")
# Ensure destination directory exists and writable
target_dir = os.path.dirname(os.path.abspath(output_path)) or "."
os.makedirs(target_dir, exist_ok=True)
if not os.access(target_dir, os.W_OK):
raise Exception(f"No write permission to directory: {target_dir}")
with open(output_path, 'wb') as f:
f.write(plaintext)
f.flush()
os.fsync(f.fileno())
if not os.path.exists(output_path):
raise Exception("Output write failed")
if delete_encrypted:
try:
os.remove(encrypted_file_path)
except Exception as del_err:
print(f"Warning: Could not delete encrypted file: {del_err}")
print(f"File decrypted successfully: {output_path}")
return output_path
except Exception as e:
raise Exception(f"Decryption failed: {str(e)}")
# NEW: small UI helpers for browsing
def _pick_restore_file(default_name):
root = tk.Tk()
root.withdraw()
path = filedialog.asksaveasfilename(
title="Save restored file as",
initialfile=default_name,
defaultextension="",
filetypes=[("All Files", "*.*")]
)
root.destroy()
return path or ""
def main():
"""
Simple command-line interface for testing the encryption/decryption functions.
"""
print("=== File Encryption/Decryption Tool ===")
# Loop until user chooses Exit
while True:
print("1. Encrypt a file")
print("2. Decrypt a file")
print("3. Exit")
choice = input("Enter your choice (1, 2, or 3): ").strip()
if choice == '1':
file_path = _clean_path(input("Enter path to file to encrypt:"))
password = getpass.getpass("Enter password: ")
try:
encrypted_path = encrypt_file(file_path, password)
print(f"Success! Encrypted file created: {encrypted_path}")
except Exception as e:
print(f"Error: {e}")
elif choice == '2':
encrypted_path = _clean_path(input("Enter path to encrypted file (.enc):"))
password = getpass.getpass("Enter password: ")
# NEW: offer to browse a safe output location outside the watch dir
try:
# Derive default restored name
if encrypted_path.lower().endswith(".enc"):
default_name = os.path.basename(encrypted_path)[:-4]
else:
default_name = os.path.basename(encrypted_path) + ".restored"
use_browse = input("Browse output location? (y/N): ").strip().lower() == "y"
if use_browse:
out_path = _pick_restore_file(default_name)
if not out_path:
print("No output selected. Decryption cancelled.")
continue
watch_dir = _get_watch_directory()
if _is_inside(watch_dir, out_path):
print("Selected path is inside the watched folder; pick a different location.")
continue
# Decrypt directly to chosen path
decrypted_path = decrypt_file_to(encrypted_path, password, out_path)
print(f"Success! Decrypted file created: {decrypted_path}")
else:
# Fall back to original behavior (writes next to .enc file)
decrypted_path = decrypt_file(encrypted_path, password)
print(f"Success! Decrypted file created: {decrypted_path}")
except Exception as e:
print(f"Error: {e}")
elif choice == '3':
print("Exiting. Goodbye.")
break
else:
print("Invalid choice!")
if __name__ == "__main__":
main()