Debian Codegraph @

tests/TestWipePath.py

raw
1 # vim: ts=4:sw=4:expandtab
2
3 # BleachBit
4 # Copyright (C) 2008-2025 Andrew Ziem
5 # https://www.bleachbit.org
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 """
21 Test FileUtilities.wipe_path
22
23 Example invocations:
24
25 # Run unit test that wipes a disk image. This is safe.
26 sudo python3 -m unittest -v tests.TestWipePath
27
28 # Equivalent to above
29 sudo python3 -m tests.TestWipePath
30
31 # Run unit test with specific filesystem
32 sudo BB_FS=ext3 python3 -m unittest -v tests.TestWipePath
33
34 # Wipe a real device---dangerous with all file system types
35 sudo python3 -m tests.TestWipePath --destroy /dev/sdb4
36
37 # Wipe a real device---dangerous with ext3
38 sudo python3 -m tests.TestWipePath --destroy /dev/sdb4 --format ext3
39
40
41 """
42
43 import argparse
44 import logging
45 import os
46 import shutil
47 import stat
48 import sys
49 import tempfile
50 import time
51 import unittest
52
53 from bleachbit.FileUtilities import delete, exe_exists, free_space, listdir
54 from bleachbit.General import run_external
55 from bleachbit.Wipe import wipe_path
56 from tests import common
57
58 logger = logging.getLogger('bleachbit')
59
60 IMAGE_SIZE_BYTES = 2097152
61 MAX_WIPES = 3
62 FS_FORMAT_COMMANDS = {
63 'ext3': ('/sbin/mkfs.ext3', '-q', '-F'),
64 'ext4': ('/sbin/mkfs.ext4', '-q', '-F'),
65 # 'xfs': ('/sbin/mkfs.xfs', '-q', '-f'),
66 'ntfs': ('/sbin/mkntfs', '-F'),
67 'vfat': ('/sbin/mkfs.fat', '-F', '32'),
68 }
69 FS_TYPES = tuple(FS_FORMAT_COMMANDS.keys())
70
71
72 def _format_tool_available(fs_type):
73 return _resolve_executable(FS_FORMAT_COMMANDS[fs_type][0]) is not None
74
75
76 def create_disk_image(n_bytes, fs_type):
77 """Make blank file and return filename
78
79 The filename prefix includes the mkfs program basename to aid debugging.
80 """
81 (fd, filename) = tempfile.mkstemp(
82 suffix='disk-image', prefix=f'bleachbit-wipe-test-{fs_type}-')
83 try:
84 os.ftruncate(fd, n_bytes)
85 finally:
86 os.close(fd)
87 return filename
88
89
90 def run_or_die(args):
91 """Run command and die if it fails
92
93 In case of success, return stdout.
94 """
95 (rc, stdout, stderr) = run_external(args)
96 assert (rc == 0), f"Command failed with return code {rc}, stderr: {stderr}"
97 return stdout
98
99
100 def _resolve_executable(path):
101 """Return executable path if available, else None."""
102 candidates = []
103 if os.path.isabs(path):
104 candidates.append(path)
105 candidates.append(shutil.which(os.path.basename(path)))
106 else:
107 candidates.append(shutil.which(path))
108 for candidate in candidates:
109 if candidate and os.path.exists(candidate) and os.access(candidate, os.X_OK):
110 return candidate
111 return None
112
113
114 def format_filesystem(filename, fs_type):
115 """Format filesystem
116
117 FIXME: some file systems require larger image size than default.
118 * btrfs requires 114,294,784 bytes
119 * xfs requires 300MB
120
121 Potential improvement later: add option to partially fill a block device.
122 mkfs.fat accepts argument as block size (1024B)
123 mkfs.ntfs accepts argument as sector size (512B)
124 mkfs.ext4 accepts argument as 1024B blocks or with optional suffix like 5G
125 """
126 base_cmd = FS_FORMAT_COMMANDS[fs_type]
127 exe_path = _resolve_executable(base_cmd[0])
128 if not exe_path:
129 raise FileNotFoundError(base_cmd[0])
130 cmd = (exe_path, *base_cmd[1:], filename)
131 run_or_die(cmd)
132
133
134 def make_dirty(mountpoint):
135 """Make filesystem dirty by writing
136
137 Files have "secret" in their name and "sssshhhh" in their contents.
138 """
139 create_counter = 0
140 write_counter = 0
141 contents = 'sssshhhh' * 512
142 while True:
143 try:
144 fn = os.path.join(mountpoint, 'secret' + str(create_counter))
145 with open(fn, 'w', encoding='utf-8') as f:
146 create_counter += 1
147 f.write(contents)
148 f.flush()
149 write_counter += 1
150 except IOError:
151 logger.error(
152 'error while creating or writing to temporary file #%d', create_counter)
153 break
154 create_counter_str = f"{create_counter:,}"
155 write_counter_str = f"{write_counter:,}"
156 logger.debug('created %s files and wrote to %s files',
157 create_counter_str, write_counter_str)
158
159
160 def mount_filesystem(device_or_image, mountpoint):
161 """Mount filesystem from either a real device or disk image"""
162 if _is_block_device(device_or_image):
163 option = 'rw,nosuid,nodev,noexec'
164 else:
165 option = 'loop'
166 args = ['mount', '-o', option, device_or_image, mountpoint]
167 run_or_die(args)
168 logger.debug('mounted %s at %s', device_or_image, mountpoint)
169
170
171 def unmount_filesystem(mountpoint):
172 """Unmount filesystem
173
174 In case of error, retry up to 5 times.
175 """
176 time.sleep(0.5) # avoid "in use" error
177 args = ['umount', mountpoint]
178 attempts = 0
179 while True:
180 (rc, _, stderr) = run_external(args)
181 if stderr:
182 logger.error(stderr)
183 if 0 == rc:
184 break
185 attempts += 1
186 time.sleep(attempts * 2)
187 if attempts > 5:
188 raise RuntimeError('cannot umount')
189
190
191 def assert_clean(filename, fs_type, expect_clean):
192 """Assert cleanliness or dirtiness of a disk image.
193
194 Semantics:
195 - If expect_clean is True: assert no contents markers remain.
196 - If expect_clean is False: assert contents markers remain (dirty).
197 - If expect_clean is None: skip assertion.
198
199 Filename remnants are logged but not asserted because detectability varies by filesystem.
200
201 Returns count of file contents markers.
202 """
203 # ASCII strings for covers ext*, FAT, and file contents
204 (rc_ascii, out_ascii, _err_ascii) = run_external(['strings', filename])
205 if rc_ascii != 0:
206 out_ascii = ''
207
208 # UTF-16LE strings for covers NTFS filename storage
209 out_le = ''
210 if 'ntfs' == fs_type:
211 (rc_le, out_le, _err_le) = run_external(['strings', '-el', filename])
212 if rc_le != 0:
213 out_le = ''
214
215 # Filenames may be stored as ASCII or UTF-16LE depending on filesystem
216 filename_count = max(out_ascii.count('secret'), out_le.count('secret'))
217
218 # File contents were written as ASCII text
219 contents_count = out_ascii.count('sssshhhh')
220 contents_count_str = f"{contents_count:,}"
221 filename_count_str = f"{filename_count:,}"
222
223 logger.debug('found %s markers in image contents and %s markers in filenames',
224 contents_count_str, filename_count_str)
225
226 if expect_clean is None:
227 pass
228 elif expect_clean:
229 assert contents_count == 0, (
230 f'Contents not wiped: found {contents_count_str} markers; '
231 f'filename markers: {filename_count_str}; '
232 f'fs: {fs_type}')
233 else:
234 assert contents_count > 0, (
235 'No contents marker found; filesystem not dirty '
236 f'(filename markers: {filename_count_str}); '
237 f'fs: {fs_type}')
238 return contents_count
239
240
241 @common.skipIfWindows
242 def wipe_helper(fs_type, n_bytes=None, device_path=None, passes=MAX_WIPES, sleep_seconds=5):
243 """Test FileUtilities.wipe_path on image or block device
244
245 For device image, pass device_path and set n_bytes to None.
246 For image, pass n_bytes and set device_path to None.
247 """
248
249 assert isinstance(fs_type, str)
250 assert fs_type in FS_TYPES
251
252 is_device = False
253 if device_path:
254 if _is_block_device(device_path):
255 filename = device_path
256 else:
257 raise ValueError(f'Not a block device: {device_path}')
258 _real_device_warning(device_path, sleep_seconds)
259 is_device = True
260 assert n_bytes is None, 'n_bytes must be None when using a block device'
261 else:
262 assert isinstance(n_bytes, int)
263 assert n_bytes > 0
264 filename = create_disk_image(n_bytes, fs_type)
265 logger.debug('created disk image %s', filename)
266
267 for exe in ('strings', 'df'):
268 if not exe_exists(exe):
269 raise RuntimeError(f'{exe} not found')
270
271 # format filesystem
272 mountpoint = None
273 try:
274 format_filesystem(filename, fs_type)
275
276 # mount
277 mountpoint = tempfile.mkdtemp(prefix='bleachbit-wipe-mountpoint')
278 mount_filesystem(filename, mountpoint)
279 except Exception:
280 # The exception is normal for non-root.
281 if mountpoint and os.path.exists(mountpoint):
282 delete(mountpoint)
283 if not is_device:
284 delete(filename)
285 raise
286
287 # baseline free disk space
288 logger.debug('df for clean filesystem %s', mountpoint)
289 logger.debug(run_external(['df', mountpoint])[1])
290
291 # make dirty
292 make_dirty(mountpoint)
293
294 # verify dirtiness (require contents marker; filenames may not be detectable on all FS)
295 unmount_filesystem(mountpoint)
296 content_markers_dirty = assert_clean(filename, fs_type, expect_clean=False)
297 mount_filesystem(filename, mountpoint)
298
299 # standard delete
300 logger.info('standard delete')
301 delete_counter = 0
302 for secretfile in listdir(mountpoint):
303 if 'secret' not in secretfile:
304 # skip lost+found
305 continue
306 delete(secretfile, shred=False)
307 delete_counter += 1
308 logger.debug('deleted %s files', f"{delete_counter:,}")
309
310 # check
311 logger.debug('df for empty, dirty filesystem %s', mountpoint)
312 logger.debug(run_external(['df', mountpoint])[1])
313
314 # verify dirtiness again (require contents marker; filenames may not be detectable)
315 unmount_filesystem(mountpoint)
316 assert_clean(filename, fs_type, expect_clean=False)
317 mount_filesystem(filename, mountpoint)
318 expected_free_space = free_space(mountpoint)
319
320 content_markers_list = []
321 # measure effectiveness of multiple wipes
322 for i in range(1, passes + 1):
323 print('*' * 30)
324 print(f'* pass {i} for {fs_type} *')
325 print('*' * 30)
326
327 # remount
328 if i > 1:
329 mount_filesystem(filename, mountpoint)
330
331 # really wipe
332 logger.info('wiping %s', mountpoint)
333
334 old_level = logging.getLogger('bleachbit.FileUtilities').level
335 logging.getLogger('bleachbit.FileUtilities').setLevel(logging.INFO)
336 try:
337 for _w in wipe_path(mountpoint):
338 pass
339 finally:
340 logging.getLogger('bleachbit.FileUtilities').setLevel(old_level)
341
342 # verify cleaning process freed all space it allocated
343 actual_free_space = free_space(mountpoint)
344 if not expected_free_space == actual_free_space:
345 logger.error('expecting %d free space but got %d',
346 expected_free_space, actual_free_space)
347
348 # unmount
349 unmount_filesystem(mountpoint)
350
351 # Require contents to be wiped. Wiping filenames is not supported.
352 content_markers = assert_clean(filename, fs_type, None)
353 content_markers_list.append(content_markers)
354 effectiveness = 100 * (content_markers_dirty -
355 content_markers) / content_markers_dirty
356 print(
357 f"Pass {i}: Content markers: {content_markers:,}, Effectiveness: {effectiveness:.1f}%")
358 if content_markers == 0:
359 break
360
361 # show content marker counts to help user understand wiping effectiveness
362 if content_markers_list == [0]:
363 print('100% effective on first pass!')
364 else:
365 print(f"\nContent marker counts by pass: {content_markers_list}")
366 if len(content_markers_list) > 1:
367 if content_markers_list[0] > min(content_markers_list):
368 print('Wiping had incremental improvement after first pass')
369 else:
370 print('Wiping did not improve after first pass')
371
372 if not is_device:
373 delete(filename)
374 delete(mountpoint)
375 if content_markers > 0:
376 raise AssertionError(f'Contents not wiped for {fs_type}')
377
378
379 class WipeTestCase(common.BleachbitTestCase):
380 """Test case for file wiping operations"""
381
382 @common.skipIfWindows
383 @common.also_with_sudo
384 def test_wipe(self):
385 """Test wiping on several kinds of file systems"""
386 if not exe_exists('strings'):
387 raise RuntimeError(
388 'strings not found: run `sudo apt install binutils` or equivalent')
389 requested_fs = FS_TYPES
390 # Optional filter example: sudo BB_FS=ext3 python3 -m unittest tests.TestWipePath
391 env_fs = os.environ.get('BB_FS') or os.environ.get('bb_fs')
392 if env_fs:
393 if env_fs not in FS_TYPES:
394 raise ValueError(
395 f'BB_FS={env_fs} did not match valid file system type')
396 requested_fs = (env_fs,)
397
398 available_fs = tuple(
399 fs for fs in requested_fs if _format_tool_available(fs))
400 missing_fs = tuple(fs for fs in requested_fs if fs not in available_fs)
401
402 if missing_fs:
403 logger.warning('Skipping wipe tests for filesystems lacking mkfs utilities: %s',
404 ', '.join(missing_fs))
405 if not available_fs:
406 missing_list = ', '.join(missing_fs) or 'unknown'
407 self.skipTest(
408 f'Missing mkfs utilities for requested filesystems: {missing_list}')
409
410 for fs_type in available_fs:
411 if common.have_root():
412 wipe_helper(fs_type=fs_type,
413 n_bytes=IMAGE_SIZE_BYTES)
414 else:
415 # Mount will fail
416 with self.assertRaises(AssertionError):
417 wipe_helper(fs_type=fs_type,
418 n_bytes=IMAGE_SIZE_BYTES)
419
420
421 def suite():
422 """Return a test suite"""
423 return unittest.TestLoader().loadTestsFromTestCase(WipeTestCase)
424
425
426 def _real_device_warning(target_desc, sleep_seconds):
427 border = '=' * 78
428 msg = (
429 f"\n{border}\n"
430 f"DANGEROUS OPERATION REQUESTED\n\n"
431 f"You requested wiping all data on: {target_desc}\n"
432 f"This is DESTRUCTIVE and will lead to DATA LOSS.\n"
433 f"Proceeding in {sleep_seconds} seconds. Press Ctrl+C to abort.\n"
434 f"{border}\n"
435 )
436 print(msg)
437 for i in range(sleep_seconds, 0, -1):
438 print(f"Starting in {i}...", end='\r', flush=True)
439 time.sleep(1)
440 print(' ' * 40, end='\r', flush=True)
441
442
443 def _is_block_device(path):
444 """Return True if path is a block device."""
445 try:
446 st = os.stat(path)
447 return stat.S_ISBLK(st.st_mode)
448 except Exception:
449 return False
450
451
452 def _ensure_not_mounted(device_path):
453 """Exit if the given device is mounted anywhere.
454
455 Uses 'findmnt' to query mount targets for the source device (and its
456 realpath). If mounted anywhere, exit safely.
457 """
458 if not device_path:
459 return
460 if not exe_exists('findmnt'):
461 raise RuntimeError('findmnt not found')
462 # Check real path in case of link such as /dev/disk/by-uuid/..
463 candidates = [device_path]
464 real = os.path.realpath(device_path)
465 if real != device_path:
466 candidates.append(real)
467
468 for dev in candidates:
469 rc, out, _err = run_external(['findmnt', dev])
470 if rc == 0 and out.strip():
471 print(
472 f"Refusing to operate on {device_path}: mounted at {out.strip()}")
473 sys.exit(3)
474
475
476 def main():
477 """Main"""
478 if len(sys.argv) == 1:
479 unittest.main()
480 return
481
482 parser = argparse.ArgumentParser(
483 description=(
484 'Run TestWipePath as a destructive tool to wipe free space on a real block device.'
485 'By default, without arguments, this script runs unittests.'
486 'DANGER! Do not delete your data! Carefully check the options!'
487 )
488 )
489 parser.add_argument('--destroy', required=True,
490 help='Block device (e.g., /dev/sdb1) that will be destroyed!')
491 parser.add_argument(
492 '--format', help='Comma-separated filesystems to format before wiping (ext3,ext4,ntfs,vfat)')
493 parser.add_argument('--passes', type=int, default=1,
494 help='Number of wipe passes (default: 1)')
495 parser.add_argument('--sleep', type=int, default=5,
496 help='Seconds to wait before start (default: 5)')
497 parser.add_argument('--verbose', action='store_true',
498 help='Enable verbose logging')
499
500 args = parser.parse_args()
501
502 if not common.have_root():
503 print('Use sudo to run this script')
504 sys.exit(2)
505
506 # Parse formats list if provided
507 formats = FS_TYPES
508 if args.format:
509 raw = [s.strip().lower() for s in args.format.split(',') if s.strip()]
510 invalid = [fs for fs in raw if fs not in FS_TYPES]
511 if invalid:
512 print(f"Error: unsupported filesystem(s): {', '.join(invalid)}")
513 sys.exit(2)
514 formats = raw if raw else None
515
516 _ensure_not_mounted(args.destroy)
517
518 for fs_type in formats:
519 wipe_helper(fs_type=fs_type,
520 device_path=args.destroy,
521 passes=args.passes,
522 sleep_seconds=args.sleep,
523 )
524 sys.exit(0)
525
526
527 if __name__ == '__main__':
528 main()