-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwiper.py
More file actions
345 lines (283 loc) · 9.65 KB
/
wiper.py
File metadata and controls
345 lines (283 loc) · 9.65 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
#!/usr/bin/env python3
# Motor de borrado síncrono — DoD 5220.22-M
# jaimefg1888
#
# Tres pases:
# 1. Ceros (\x00)
# 2. Unos (\xFF)
# 3. Aleatorio (os.urandom)
#
# Antes de eliminar: renombra el fichero y resetea timestamps para que las
# herramientas de carving no encuentren el inodo original.
import os
import random
import stat
import string
import sys
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Optional
CHUNK_SIZE = 256 * 1024 # 256 KB — reduces syscall overhead on large files
DOD_PASSES = 3
@dataclass
class WipeResult:
filepath: str
success: bool
file_size: int = 0
bytes_written: int = 0
error: str = ""
duration: float = 0.0
@dataclass
class WipeSummary:
total_files: int = 0
files_wiped: int = 0
files_failed: int = 0
total_bytes_overwritten: int = 0
total_duration: float = 0.0
errors: list[str] = field(default_factory=list)
results: list[WipeResult] = field(default_factory=list)
@dataclass
class WipeTelemetry:
"""Real-time snapshot consumed by the Rich dashboard in ``madara.py``.
All fields are updated in-place so the dashboard can read the latest
state without any shared-memory primitives.
"""
start_time: float = 0.0
current_pass: int = 0
total_passes: int = DOD_PASSES
bytes_written_total: int = 0
bytes_written_current_pass: int = 0
file_size: int = 0
current_file: str = ""
finished: bool = False
@property
def total_target_bytes(self) -> int:
return self.file_size * self.total_passes
@property
def global_progress(self) -> float:
target = self.total_target_bytes
if target <= 0:
return 1.0
return min(self.bytes_written_total / target, 1.0)
ProgressCallback = Optional[Callable[[str, int, int, int], None]]
def _overwrite_pass(
fd: int,
file_size: int,
pass_number: int,
filepath: str,
progress_callback: ProgressCallback = None,
) -> int:
"""Write one overwrite pass to an already-open file descriptor.
Seeks to the beginning of the file, then writes *file_size* bytes in
chunks of :data:`CHUNK_SIZE`, calling ``os.fsync`` at the end to force
the data to physical media.
Args:
fd: Open file descriptor with write access.
file_size: Number of bytes to overwrite.
pass_number: 1 = zeros, 2 = ones, 3 = random.
filepath: Path string passed verbatim to *progress_callback*.
progress_callback: Optional four-argument callable
``(filepath, pass_number, bytes_written, file_size)``.
Returns:
Total bytes written in this pass.
"""
os.lseek(fd, 0, os.SEEK_SET)
bytes_written = 0
remaining = file_size
while remaining > 0:
chunk_len = min(CHUNK_SIZE, remaining)
if pass_number == 1:
data = b"\x00" * chunk_len
elif pass_number == 2:
data = b"\xFF" * chunk_len
else:
data = os.urandom(chunk_len)
os.write(fd, data)
bytes_written += chunk_len
remaining -= chunk_len
if progress_callback:
progress_callback(filepath, pass_number, bytes_written, file_size)
os.fsync(fd)
return bytes_written
def _scrub_metadata(filepath: str) -> str:
"""Overwrite the file's timestamps and rename it to obstruct forensic recovery.
Sets ``atime`` and ``mtime`` to Unix epoch 0 so that tools such as
Autopsy / Sleuth Kit cannot use timestamps to reconstruct the file's
history. Then renames the file to a random 12-character name to
overwrite the directory entry.
Args:
filepath: Absolute path to the file to scrub.
Returns:
The new path after renaming (may equal *filepath* if the rename
failed).
"""
try:
os.utime(filepath, (0, 0))
except OSError:
pass
directory = os.path.dirname(filepath) or "."
random_name = (
"".join(random.choices(string.ascii_lowercase + string.digits, k=12)) + ".tmp"
)
new_path = os.path.join(directory, random_name)
try:
os.rename(filepath, new_path)
return new_path
except OSError:
return filepath
def _ensure_writable(filepath: str) -> None:
"""Remove the read-only flag from *filepath* if it is set.
A no-op if the file is already writable or if ``chmod`` fails (e.g.
due to an immutable flag set by ``chattr +i``).
Args:
filepath: Path to the file to make writable.
"""
try:
mode = os.stat(filepath).st_mode
if not (mode & stat.S_IWRITE):
os.chmod(filepath, mode | stat.S_IWRITE)
except OSError:
pass
def wipe_file(
filepath: str,
progress_callback: ProgressCallback = None,
) -> WipeResult:
"""Securely overwrite and delete a single file using DoD 5220.22-M.
The file is overwritten in three passes (zeros → ones → random),
fsynced after each pass, then renamed and deleted. The file descriptor
is always closed in a ``finally`` block, even when I/O errors occur
mid-pass.
Args:
filepath: Path to the file to wipe.
progress_callback: Optional progress callback; see
:data:`ProgressCallback`.
Returns:
A :class:`WipeResult` describing the outcome.
"""
start_time = time.time()
filepath = os.path.abspath(filepath)
if not os.path.isfile(filepath):
return WipeResult(
filepath=filepath,
success=False,
error=f"Archivo no encontrado: {filepath}",
)
_ensure_writable(filepath)
try:
file_size = os.path.getsize(filepath)
total_bytes_written = 0
if file_size == 0:
final_path = _scrub_metadata(filepath)
os.remove(final_path)
return WipeResult(
filepath=filepath,
success=True,
file_size=0,
duration=time.time() - start_time,
)
flags = os.O_WRONLY | (os.O_BINARY if sys.platform == "win32" else 0)
fd = os.open(filepath, flags)
try:
for pass_num in range(1, DOD_PASSES + 1):
total_bytes_written += _overwrite_pass(
fd, file_size, pass_num, filepath, progress_callback
)
finally:
os.close(fd)
final_path = _scrub_metadata(filepath)
os.remove(final_path)
return WipeResult(
filepath=filepath,
success=True,
file_size=file_size,
bytes_written=total_bytes_written,
duration=time.time() - start_time,
)
except PermissionError as exc:
return WipeResult(
filepath=filepath,
success=False,
error=f"Permiso denegado: {exc}",
duration=time.time() - start_time,
)
except OSError as exc:
return WipeResult(
filepath=filepath,
success=False,
error=f"Error del sistema: {exc}",
duration=time.time() - start_time,
)
except Exception as exc:
return WipeResult(
filepath=filepath,
success=False,
error=f"Error inesperado: {exc}",
duration=time.time() - start_time,
)
def wipe_directory(
dirpath: str,
progress_callback: ProgressCallback = None,
) -> WipeSummary:
"""Recursively wipe every file inside *dirpath* and then remove the tree.
Files are wiped bottom-up so that each file's parent directory still
exists when the wipe call is made. Empty directories are pruned after
all files have been processed; any directory that cannot be removed (e.g.
due to remaining locked files) is silently skipped.
Args:
dirpath: Root directory to wipe.
progress_callback: Optional progress callback forwarded to each
:func:`wipe_file` call.
Returns:
A :class:`WipeSummary` aggregating results for all processed files.
"""
summary = WipeSummary()
start_time = time.time()
dirpath = os.path.abspath(dirpath)
if not os.path.isdir(dirpath):
summary.errors.append(f"Directorio no encontrado: {dirpath}")
return summary
all_files = [
os.path.join(root, filename)
for root, _, files in os.walk(dirpath, topdown=False)
for filename in files
]
summary.total_files = len(all_files)
for filepath in all_files:
result = wipe_file(filepath, progress_callback)
summary.results.append(result)
if result.success:
summary.files_wiped += 1
summary.total_bytes_overwritten += result.bytes_written
else:
summary.files_failed += 1
summary.errors.append(f"{result.filepath}: {result.error}")
for root, dirs, _ in os.walk(dirpath, topdown=False):
for dirname in dirs:
try:
os.rmdir(os.path.join(root, dirname))
except OSError:
pass
try:
os.rmdir(dirpath)
except OSError:
pass
summary.total_duration = time.time() - start_time
return summary
def collect_files(target: str) -> list[str]:
"""Return a flat list of all files reachable from *target*.
Args:
target: A path to a single file or a directory root.
Returns:
A list of absolute file paths. Empty if *target* does not exist.
"""
target = os.path.abspath(target)
if os.path.isfile(target):
return [target]
if os.path.isdir(target):
return [
os.path.join(root, filename)
for root, _, filenames in os.walk(target, topdown=False)
for filename in filenames
]
return []