| 1 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
# Copyright (c) 2008-2026 Andrew Ziem. |
| 3 |
# |
| 4 |
# This work is licensed under the terms of the GNU GPL, version 3 or |
| 5 |
# later. See the COPYING file in the top-level directory. |
| 6 |
|
| 7 |
|
| 8 |
""" |
| 9 |
Test case for module WindowsWipe |
| 10 |
""" |
| 11 |
|
| 12 |
# standard library |
| 13 |
import os |
| 14 |
import sys |
| 15 |
import time |
| 16 |
import unittest |
| 17 |
from contextlib import suppress |
| 18 |
|
| 19 |
import bleachbit |
| 20 |
|
| 21 |
# third party |
| 22 |
if bleachbit.IS_WINDOWS: |
| 23 |
import win32file |
| 24 |
import pywintypes |
| 25 |
from win32com.shell import shell |
| 26 |
|
| 27 |
# local |
| 28 |
from tests import common |
| 29 |
from bleachbit.FileUtilities import children_in_directory |
| 30 |
|
| 31 |
if bleachbit.IS_WINDOWS: |
| 32 |
# importing WindowsWipe fails on non-Windows |
| 33 |
from bleachbit.WindowsWipe import ( |
| 34 |
check_os, |
| 35 |
determine_win_version, |
| 36 |
open_file, |
| 37 |
close_file, |
| 38 |
get_file_basic_info, |
| 39 |
truncate_file, |
| 40 |
volume_from_file, |
| 41 |
get_volume_information, |
| 42 |
get_extents, |
| 43 |
write_zero_fill, |
| 44 |
file_wipe, |
| 45 |
wipe_file_direct, |
| 46 |
extents_a_minus_b, |
| 47 |
GENERIC_READ, |
| 48 |
GENERIC_WRITE |
| 49 |
) |
| 50 |
from tests.TestWindows import WindowsLinksMixIn |
| 51 |
else: |
| 52 |
WindowsLinksMixIn = object |
| 53 |
|
| 54 |
|
| 55 |
@common.skipUnlessWindows |
| 56 |
class WindowsWipeTestCase(common.BleachbitTestCase, WindowsLinksMixIn): |
| 57 |
"""Test case for module WindowsWipe""" |
| 58 |
|
| 59 |
def setUp(self): |
| 60 |
"""Set up test environment""" |
| 61 |
super().setUp() |
| 62 |
|
| 63 |
def test_check_os(self): |
| 64 |
"""Unit test for check_os()""" |
| 65 |
# This should not raise an exception on Windows |
| 66 |
check_os() |
| 67 |
|
| 68 |
def test_determine_win_version(self): |
| 69 |
"""Unit test for determine_win_version""" |
| 70 |
version, is_win_home = determine_win_version() |
| 71 |
self.assertIsInstance(version, str) |
| 72 |
self.assertIsInstance(is_win_home, bool) |
| 73 |
|
| 74 |
def test_open_close_file(self): |
| 75 |
"""Unit tests for open_file() and close_file""" |
| 76 |
open_path = os.path.join(self.tempdir, 'open') |
| 77 |
self.write_file(open_path, b'test data') |
| 78 |
file_handle = open_file(open_path) |
| 79 |
self.assertIsNotNone(file_handle) |
| 80 |
close_file(file_handle) |
| 81 |
|
| 82 |
def test_open_file_refuses_symlink(self): |
| 83 |
"""open_file() must not follow a symlink to another file""" |
| 84 |
target = self.write_file('open_file_target', b'keepme') |
| 85 |
link = os.path.join(self.tempdir, 'open_file_link') |
| 86 |
self._create_win_file_symlink(target, link) |
| 87 |
with self.assertRaises(OSError): |
| 88 |
open_file(link) |
| 89 |
|
| 90 |
def test_get_extents_system32(self): |
| 91 |
"""Unit test for get_extents() with system32 files""" |
| 92 |
|
| 93 |
error_count = 0 |
| 94 |
zero_extents_count = 0 |
| 95 |
nonzero_extents_count = 0 |
| 96 |
heuristic_exceptions = [] |
| 97 |
large_files_count = 0 |
| 98 |
large_files_zero_extents = [] |
| 99 |
start_time = time.time() |
| 100 |
|
| 101 |
for path in children_in_directory(os.path.expandvars(r'%windir%\system32')): |
| 102 |
try: |
| 103 |
file_handle = open_file(path) |
| 104 |
except pywintypes.error as e: |
| 105 |
# 5 = ERROR_ACCESS_DENIED |
| 106 |
# 32 = ERROR_SHARING_VIOLATION |
| 107 |
# 1920 = ERROR_FILE_ENCRYPTED (reparse points / AppExecutionAlias |
| 108 |
# stubs under WindowsApps are not openable). |
| 109 |
if e.winerror in (5, 32, 1920): |
| 110 |
error_count += 1 |
| 111 |
continue |
| 112 |
print(f"Error opening {path}: {e}") |
| 113 |
raise e |
| 114 |
except PermissionError: |
| 115 |
# open_file() refuses a symlink (e.g. Docker Desktop's |
| 116 |
# docker.exe in system32), which is expected here. |
| 117 |
error_count += 1 |
| 118 |
continue |
| 119 |
|
| 120 |
ret = get_extents(file_handle, filename=path) |
| 121 |
self.assertIsInstance(ret, list) |
| 122 |
close_file(file_handle) |
| 123 |
|
| 124 |
if len(ret) == 0: |
| 125 |
zero_extents_count += 1 |
| 126 |
else: |
| 127 |
nonzero_extents_count += 1 |
| 128 |
|
| 129 |
# Files with size under ~500 bytes are usually resident in the |
| 130 |
# MFT, so they have zero clusters. There may be a few exceptions. |
| 131 |
fsize = os.path.getsize(path) |
| 132 |
if fsize > 1000: |
| 133 |
large_files_count += 1 |
| 134 |
if len(ret) == 0: |
| 135 |
# WOF-compressed (Compact OS) files report zero extents |
| 136 |
# without setting FILE_ATTRIBUTE_COMPRESSED. |
| 137 |
large_files_zero_extents.append((path, fsize, len(ret))) |
| 138 |
elif fsize < 200 and len(ret) != 0: |
| 139 |
heuristic_exceptions.append( |
| 140 |
(path, fsize, len(ret))) |
| 141 |
total_files = zero_extents_count + nonzero_extents_count + error_count |
| 142 |
elapsed_seconds = time.time() - start_time |
| 143 |
if total_files > 0: |
| 144 |
files_per_second = total_files / elapsed_seconds |
| 145 |
else: |
| 146 |
files_per_second = None |
| 147 |
zero_frac = (len(large_files_zero_extents) / large_files_count |
| 148 |
if large_files_count else 0) |
| 149 |
print(f"\ntest_get_extents() stats: {error_count:,} errors; {zero_extents_count:,} files with zero extents; {nonzero_extents_count:,} files with nonzero extents; {int(elapsed_seconds)} seconds; {int(files_per_second) if files_per_second else None} files per second") |
| 150 |
print( |
| 151 |
f"large files: {large_files_count:,}; large files with zero extents: {len(large_files_zero_extents):,} ({zero_frac:.0%})") |
| 152 |
self.assertGreater(zero_extents_count, 10) |
| 153 |
self.assertGreater(nonzero_extents_count, 100) |
| 154 |
# Print the first few heuristic exceptions for diagnostics. |
| 155 |
for path, fsize, extent_count in heuristic_exceptions[:5]: |
| 156 |
print( |
| 157 |
f" heuristic exception: {path} size={fsize:,} extents={extent_count}") |
| 158 |
self.assertLess( |
| 159 |
len(heuristic_exceptions), 6, |
| 160 |
f"Too many heuristic exceptions ({len(heuristic_exceptions)}): " |
| 161 |
f"{heuristic_exceptions[:5]}") |
| 162 |
# On Compact OS images most of system32 is WOF-compressed and reports |
| 163 |
# zero extents, so only check this when WOF isn't dominating. |
| 164 |
for path, fsize, extent_count in large_files_zero_extents[:5]: |
| 165 |
print(f" large zero-extent file: {path} size={fsize:,}") |
| 166 |
if zero_frac < 0.5: |
| 167 |
self.assertLess( |
| 168 |
len(large_files_zero_extents), 6, |
| 169 |
f"Too many large files with zero extents " |
| 170 |
f"({len(large_files_zero_extents)}): {large_files_zero_extents[:5]}") |
| 171 |
else: |
| 172 |
print( |
| 173 |
"skipping large-file extent check: volume appears WOF-compressed (Compact OS)") |
| 174 |
|
| 175 |
def test_get_file_basic_info(self): |
| 176 |
"""Unit test for get_file_basic_info()""" |
| 177 |
path = self.write_file(filename='test.txt', text='test data') |
| 178 |
|
| 179 |
file_handle = open_file(path) |
| 180 |
file_size, is_special = get_file_basic_info(path, file_handle) |
| 181 |
self.assertEqual(file_size, 9) |
| 182 |
self.assertFalse(is_special) |
| 183 |
close_file(file_handle) |
| 184 |
|
| 185 |
from bleachbit.General import run_external |
| 186 |
compact_cmd = ["compact", "/c", path] |
| 187 |
(rc, _, _) = run_external(compact_cmd) |
| 188 |
self.assertEqual(0, rc) |
| 189 |
|
| 190 |
file_handle = open_file(path) |
| 191 |
_, is_special_after = get_file_basic_info(path, file_handle) |
| 192 |
close_file(file_handle) |
| 193 |
self.assertTrue(is_special_after) |
| 194 |
|
| 195 |
sparse_path = os.path.join(self.tempdir, 'sparse') |
| 196 |
self.write_file(sparse_path, b'test data') |
| 197 |
fsutil_cmd = ["fsutil", "sparse", "setflag", sparse_path] |
| 198 |
(rc, _, _) = run_external(fsutil_cmd) |
| 199 |
self.assertEqual(0, rc) |
| 200 |
|
| 201 |
file_handle = open_file(sparse_path) |
| 202 |
_, is_sparse = get_file_basic_info(sparse_path, file_handle) |
| 203 |
close_file(file_handle) |
| 204 |
self.assertTrue(is_sparse) |
| 205 |
|
| 206 |
def test_truncate_file(self): |
| 207 |
"""Unit test for truncate_file()""" |
| 208 |
truncate_path = os.path.join(self.tempdir, 'truncate') |
| 209 |
self.write_file(truncate_path, b'test data to be truncated') |
| 210 |
|
| 211 |
self.assertGreater(os.path.getsize(truncate_path), 0) |
| 212 |
|
| 213 |
file_handle = open_file(truncate_path, GENERIC_READ | GENERIC_WRITE) |
| 214 |
truncate_file(file_handle) |
| 215 |
close_file(file_handle) |
| 216 |
|
| 217 |
self.assertEqual(os.path.getsize(truncate_path), 0) |
| 218 |
|
| 219 |
def test_get_volume_information(self): |
| 220 |
"""Unit test for get_volume_information""" |
| 221 |
volume = volume_from_file(sys.executable) |
| 222 |
self.assertIsInstance(volume, str) |
| 223 |
self.assertTrue(volume.endswith('\\')) |
| 224 |
self.assertTrue(os.path.exists(volume)) |
| 225 |
self.assertEqual(len(volume), 3) |
| 226 |
|
| 227 |
volume_info = get_volume_information(volume) |
| 228 |
|
| 229 |
self.assertIsNotNone(volume_info) |
| 230 |
self.assertGreater(volume_info.sectors_per_cluster, 0) |
| 231 |
self.assertGreater(volume_info.bytes_per_sector, 0) |
| 232 |
self.assertGreater(volume_info.total_clusters, 0) |
| 233 |
|
| 234 |
def test_write_zero_fill(self): |
| 235 |
"""Unit test for write_zero_fill""" |
| 236 |
tmp_path = os.path.join(self.tempdir, 'write_zero_fill') |
| 237 |
self.write_file(tmp_path, b'test data') |
| 238 |
|
| 239 |
file_handle = open_file(tmp_path, GENERIC_READ | GENERIC_WRITE) |
| 240 |
write_length = 1024 |
| 241 |
write_zero_fill(file_handle, write_length) |
| 242 |
close_file(file_handle) |
| 243 |
|
| 244 |
self.assertEqual(os.path.getsize(tmp_path), write_length) |
| 245 |
|
| 246 |
with open(tmp_path, 'rb') as f: |
| 247 |
data = f.read() |
| 248 |
self.assertEqual(data, b'\x00' * write_length) |
| 249 |
|
| 250 |
def test_file_wipe_basic(self): |
| 251 |
"""Basic unit test for file_wipe""" |
| 252 |
if not shell.IsUserAnAdmin(): |
| 253 |
self.skipTest("Test requires administrator privileges") |
| 254 |
|
| 255 |
cases = [ |
| 256 |
{ |
| 257 |
"name": "file_wipe_basic_small", |
| 258 |
"data": b'This is test data that should be wiped', |
| 259 |
"expect_zero_extents": True, |
| 260 |
}, |
| 261 |
{ |
| 262 |
"name": "file_wipe_basic_large", |
| 263 |
"data": os.urandom(4 * 1024 * 1024), |
| 264 |
"expect_zero_extents": False, |
| 265 |
}, |
| 266 |
] |
| 267 |
|
| 268 |
for case in cases: |
| 269 |
tmp_path = os.path.join(self.tempdir, case["name"]) |
| 270 |
write_data = case["data"] |
| 271 |
self.write_file(tmp_path, write_data) |
| 272 |
|
| 273 |
file_handle = open_file(tmp_path) |
| 274 |
try: |
| 275 |
extents = get_extents(file_handle, filename=tmp_path) |
| 276 |
finally: |
| 277 |
close_file(file_handle) |
| 278 |
|
| 279 |
if case["expect_zero_extents"]: |
| 280 |
self.assertEqual(extents, []) |
| 281 |
else: |
| 282 |
self.assertIsInstance(extents, list) |
| 283 |
self.assertGreater(len(extents), 0) |
| 284 |
|
| 285 |
total_clusters = sum((end - start + 1) for start, end in extents) |
| 286 |
if total_clusters > 0: |
| 287 |
volume = volume_from_file(tmp_path) |
| 288 |
volume_info = get_volume_information(volume) |
| 289 |
cluster_size = (volume_info.sectors_per_cluster * |
| 290 |
volume_info.bytes_per_sector) |
| 291 |
self.assertGreaterEqual( |
| 292 |
total_clusters * cluster_size, len(write_data)) |
| 293 |
|
| 294 |
file_wipe(tmp_path) |
| 295 |
|
| 296 |
with open(tmp_path, 'rb') as f: |
| 297 |
data = f.read() |
| 298 |
self.assertEqual(data, b'\x00' * len(write_data)) |
| 299 |
|
| 300 |
def test_file_wipe_locked(self): |
| 301 |
"""Test file_wipe() with a locked file""" |
| 302 |
if not shell.IsUserAnAdmin(): |
| 303 |
self.skipTest("Test requires administrator privileges") |
| 304 |
|
| 305 |
tmp_path = os.path.join(self.tempdir, 'file_wipe_locked') |
| 306 |
self.write_file(tmp_path, b'This is test data that should be locked') |
| 307 |
|
| 308 |
file_handle = None |
| 309 |
try: |
| 310 |
file_handle = win32file.CreateFileW( |
| 311 |
tmp_path, |
| 312 |
win32file.GENERIC_READ, # Only need read access to lock it |
| 313 |
0, # No sharing to cause "access denied" error |
| 314 |
None, # No security attributes |
| 315 |
win32file.OPEN_EXISTING, |
| 316 |
win32file.FILE_ATTRIBUTE_NORMAL, |
| 317 |
None |
| 318 |
) |
| 319 |
|
| 320 |
with self.assertRaises(pywintypes.error) as context: |
| 321 |
file_wipe(tmp_path) |
| 322 |
|
| 323 |
# error 32: file in use |
| 324 |
# error 5: access denied |
| 325 |
self.assertIn(context.exception.winerror, [5, 32]) |
| 326 |
|
| 327 |
finally: |
| 328 |
# Close the file handle to release the lock |
| 329 |
if file_handle: |
| 330 |
win32file.CloseHandle(file_handle) |
| 331 |
|
| 332 |
def test_file_wipe_swapped_handles(self): |
| 333 |
"""Test file_wipe() with swapped handles and extents""" |
| 334 |
if not shell.IsUserAnAdmin(): |
| 335 |
self.skipTest("Test requires administrator privileges") |
| 336 |
|
| 337 |
volume = volume_from_file(self.tempdir) |
| 338 |
volume_info = get_volume_information(volume) |
| 339 |
cluster_size = (volume_info.sectors_per_cluster * |
| 340 |
volume_info.bytes_per_sector) |
| 341 |
|
| 342 |
file_configs = [ |
| 343 |
{"path": os.path.join(self.tempdir, 'file_wipe_swap_1'), |
| 344 |
"content": b'1', |
| 345 |
"clusters": 1, |
| 346 |
"handle": None}, |
| 347 |
{"path": os.path.join(self.tempdir, 'file_wipe_swap_2'), |
| 348 |
"content": b'2', |
| 349 |
"clusters": 2, |
| 350 |
"handle": None} |
| 351 |
] |
| 352 |
|
| 353 |
try: |
| 354 |
for config in file_configs: |
| 355 |
with open(config["path"], 'wb') as f: |
| 356 |
f.write(config["content"] * |
| 357 |
(cluster_size * config["clusters"])) |
| 358 |
|
| 359 |
with open(config["path"], 'rb') as f: |
| 360 |
content = f.read() |
| 361 |
config["content_before"] = content |
| 362 |
expected_size = cluster_size * config["clusters"] |
| 363 |
self.assertEqual(len(content), expected_size, |
| 364 |
f"File should be exactly {config['clusters']} cluster(s) ({expected_size} bytes)") |
| 365 |
self.assertEqual( |
| 366 |
content, config["content"] * expected_size) |
| 367 |
|
| 368 |
config["handle"] = open_file( |
| 369 |
config["path"], GENERIC_READ | GENERIC_WRITE) |
| 370 |
config["extents"] = get_extents( |
| 371 |
config["handle"], filename=config["path"]) |
| 372 |
|
| 373 |
total_clusters = sum([(end - start + 1) |
| 374 |
for start, end in config["extents"]]) |
| 375 |
self.assertEqual(total_clusters, config["clusters"], |
| 376 |
f"File should have exactly {config['clusters']} cluster(s)") |
| 377 |
|
| 378 |
config["size"], _ = get_file_basic_info( |
| 379 |
config["path"], config["handle"]) |
| 380 |
|
| 381 |
# Wipe files with swapped handles and extents |
| 382 |
# Wipe file1 using file2's handle and extents |
| 383 |
wipe_file_direct(file_configs[1]["handle"], file_configs[0]["extents"], |
| 384 |
cluster_size, file_configs[0]["size"]) |
| 385 |
# Wipe file2 using file1's handle and extents |
| 386 |
wipe_file_direct(file_configs[0]["handle"], file_configs[1]["extents"], |
| 387 |
cluster_size, file_configs[1]["size"]) |
| 388 |
|
| 389 |
for config in file_configs: |
| 390 |
if config["handle"]: |
| 391 |
close_file(config["handle"]) |
| 392 |
config["handle"] = None |
| 393 |
|
| 394 |
for config in file_configs: |
| 395 |
with open(config["path"], 'rb') as f: |
| 396 |
config["content_after"] = f.read() |
| 397 |
|
| 398 |
# Verify results |
| 399 |
# File 1 (originally 1 cluster) wiped with File 2's extents (2 clusters) |
| 400 |
self.assertNotEqual(file_configs[0]["content_after"], file_configs[0]["content_before"], |
| 401 |
"File 1 still contains original content after wiping") |
| 402 |
self.assertTrue(all(byte == 0 for byte in file_configs[0]["content_after"][:cluster_size]), |
| 403 |
"First cluster of file 1 was not properly zeroed out") |
| 404 |
# File 1 should grow to match file 2's size (2 clusters) |
| 405 |
self.assertEqual(len(file_configs[0]["content_after"]), cluster_size * 2, |
| 406 |
f"File 1 size should grow to 2 clusters ({cluster_size * 2} bytes)") |
| 407 |
|
| 408 |
# File 2 (originally 2 clusters) wiped with File 1's extents (1 cluster) |
| 409 |
self.assertNotEqual(file_configs[1]["content_after"], file_configs[1]["content_before"], |
| 410 |
"File 2 still contains all original content after wiping") |
| 411 |
# First cluster should be zeroed out |
| 412 |
first_cluster = file_configs[1]["content_after"][:cluster_size] |
| 413 |
self.assertTrue(all(byte == 0 for byte in first_cluster), |
| 414 |
"First cluster of file 2 was not properly zeroed out") |
| 415 |
# Second cluster should still have original data |
| 416 |
second_cluster = file_configs[1]["content_after"][cluster_size:cluster_size * 2] |
| 417 |
self.assertEqual(second_cluster, file_configs[1]["content"] * cluster_size, |
| 418 |
"Second cluster of file 2 should still contain original data") |
| 419 |
# File 2 size should remain the same (2 clusters) |
| 420 |
self.assertEqual(len(file_configs[1]["content_after"]), cluster_size * 2, |
| 421 |
f"File 2 size should remain 2 clusters ({cluster_size * 2} bytes)") |
| 422 |
|
| 423 |
finally: |
| 424 |
for config in file_configs: |
| 425 |
if config.get("handle"): |
| 426 |
with suppress(Exception): |
| 427 |
close_file(config["handle"]) |
| 428 |
|
| 429 |
def test_not_included(self): |
| 430 |
"""Notify users there are more tests""" |
| 431 |
self.skipTest( |
| 432 |
"More wiping tests available at https://github.com/bleachbit/windows-wipe/blob/master/testwipe.py") |
| 433 |
|
| 434 |
def test_extents_a_minus_b(self): |
| 435 |
"""Unit test for extents_a_minus_b()""" |
| 436 |
def a_minus_b_as_set(a, b): |
| 437 |
result = set() |
| 438 |
for start, end in extents_a_minus_b(a, b): |
| 439 |
self.assertLessEqual(start, end) |
| 440 |
result.update(range(start, end + 1)) |
| 441 |
return result |
| 442 |
|
| 443 |
def as_set(extents): |
| 444 |
result = set() |
| 445 |
for start, end in extents: |
| 446 |
result.update(range(start, end + 1)) |
| 447 |
return result |
| 448 |
|
| 449 |
cases = [ |
| 450 |
# (a, b) |
| 451 |
([(0, 100)], [(0, 50)]), # tail of A past the last B range |
| 452 |
([(500, 600)], [(0, 100)]), # B entirely before A, no overlap |
| 453 |
([(0, 100)], [(150, 200)]), # B entirely after A, no overlap |
| 454 |
([(0, 100)], []), # B empty |
| 455 |
([], [(0, 100)]), # A empty |
| 456 |
([(0, 100)], [(0, 100)]), # fully covered |
| 457 |
([(0, 100)], [(40, 60)]), # B in the middle of A |
| 458 |
([(0, 100)], [(0, 30), (40, 100)]), # multiple B ranges |
| 459 |
([(0, 10), (20, 30), (40, 50)], [ |
| 460 |
(5, 25), (45, 60)]), # multiple A and B |
| 461 |
([(10, 20), (30, 40)], [(50, 60)]), # B after all of A |
| 462 |
] |
| 463 |
for a, b in cases: |
| 464 |
with self.subTest(a=a, b=b): |
| 465 |
got = a_minus_b_as_set(a, b) |
| 466 |
expected = as_set(a) - as_set(b) |
| 467 |
self.assertEqual(got, expected) |
| 468 |
|
| 469 |
|
| 470 |
if __name__ == '__main__': |
| 471 |
unittest.main() |