Contact us in messengers or by phone.

whatsapp telegram viber phone email
+79214188555

How forensics recover reliably deleted data

Марат

Private access level
Full members of NP "MOD"
Joined
Jun 5, 2013
Messages
445
Reaction score
6
Points
18
Location
г. Екатеринбург, Свердловская обл.
Website
www.detective-bureau.com
For the investigator who analyzes the suspect’s computer, there is always data of particular interest. But it seems to some that if you overwrite the area where the file was located with random data, then nothing will be restored. This is true, but only in part. Even after such reinsurance, data can often be retrieved!

What happens when a file is deleted? Very simple: in the file system, one attribute is changed for it, and thus it is marked as deleted. At the same time, the contents of the file still remain on the hard drive, and it can be restored using one of the many paid and free programs (for example, R-Studio). We have written many times about how to safely delete files without the possibility of recovery. Fortunately, a huge number of shredder utilities have been developed, which, using simple techniques, overwrite the disk sections on which the deleted data was located. Thus, even when using recovery technologies, in which data is read directly from magnetic media, it will be impossible to recover deleted files. Even real professionals in the field of data recovery have assured us of the effectiveness of this approach. But - the gurus still have loopholes for extracting information!

Image files

Let's start by looking at a simple case - deleting a regular photo. Suppose we have a folder with photos, and we get rid of one of them. And we delete by all the rules, overwriting the desired area of the disk several times. In theory, nothing else should betray its existence (unless we ourselves had previously copied it to another folder and forgot about it). But here, just many people forget about one feature of Windows - the file Thumbs.db. This is a special storage used by the operating system, which contains thumbnails of images from the current folder. If you select the "Page Thumbnails" display mode in the explorer, then the OS will take the thumbnails of the images just from this file. It is created in each folder in which there are pictures, and contains thumbnails of images in JPEG format (regardless of the format of the original image).

Let's conduct a small experiment - create a folder and place any three pictures there. Now open this directory in Explorer - Thumbs.db has appeared (to see this file, you need to enable the display of hidden files). We can view and analyze it using the Thumbnail Database Viewer utility. The program, as expected, shows thumbnails for all three files. And now we will delete one of them using the SDelete program or any other program for the safe deletion of data:

sdelete.exe -p 2 file1.jpg

The parameter p is responsible for the number of passes of the shredder, that is, it indicates how many times the file will be overwritten before deletion. As a result, the image will be permanently erased from the hard drive. But let's see if this deletion somehow affected Thumbs.db? Reopening it, and what do we see? The thumbnail for the deleted picture is still in place! It turns out that the file can easily contain thumbnails of already deleted images. And on this, as I was told, more than one smart person was caught ...

How to avoid this? Very simple - you just need to disable thumbnail caching in Thumbs.db files. On Windows XP, you must set the DisableThumbnailCache key in the HKEY_CURRENT_USER \ Software \ Microsoft \ Windows \ CurrentVersion \ Explorer \ Advanced key to "1". On Windows 7, this key is named NoThumbnailCache and is located in HKEY_CURRENT_USER \ Software \ Microsoft \ Windows \ CurrentVersion \ Policies \ Explorer. And, of course, it is important not to forget to delete all Thumbs.db.

Swap file

Substations on the part of the operating system on only one file with thumbnails do not end there. As you work with a document, information about it falls into various parts of the OS — a temporary folder, registry, and so on. Therefore, it is very difficult to track and delete all data associated with a file. On top of that, there are places where a copy of a file can happen by accident (sometimes such an accident can be very expensive). I am talking about the page file (pagefile.sys) and the memory swap used during Hibernation mode (hiberfil.sys). It is obviously impossible to predict the contents of the swap file, and no one can guarantee anything. I suggest in another experiment to make sure that this is a dangerous place.

Since the operating system just doesn’t allow you to view or copy the swap file, we have two options: use special utilities or boot into another OS and access the file from it. The second method seemed simpler to me, since the Back Track, stuffed with various utilities, including for file recovery, was at hand. Therefore, having booted from LiveCD, I mounted the Windows partition and went to the "BackTrack-> Forensic" section, from where I launched the Foremost utility. This wonderful console program can recover files based on their headers and internal structure. It is only necessary to transfer the name of the input file in which the search will be carried out, and indicate the directory where all the data found will be saved:

#foremost -i /mnt/hda1/pagefile.sys -o / root / Desktop / page_file -v -q

As the input file, I specified the swap file /mnt/hda1/pagefile.sys, and the directory for saving the results was / root / Desktop / page_file. The program began its work. In a short time, Foremost managed to find and extract 524 files.

Statistics of extracted files:
jpg: = 73
gif: = 4
gif: = 19
jpg: = 77
jpg: = 95
doc: = 1
pgp: = 65
pgp: = 62
pgp: = 44
pgp: = 36
dat: = 7
lnk: = 3
cookie: = 38

The utility conveniently sorted all files by type and sorted them into different folders. The first thing I did was to check what got into the jpg folder. Of all the recovered files, about half refused to be displayed, but the other was perfectly visible. And what was not among the pictures: a couple of pictures that I deleted recently; many small images from websites; Facebook friends avatars and more. Honestly, I did not plan to detect so many images. In addition to the pictures, I also wanted to know what the only doc-file that got into the page file. But, unfortunately, Word only cursed that the file was damaged and could not open it. An unexpected surprise awaited me in the cookie folder - scrolling through a few files, I found the addresses of videos that I watched almost a year ago on YouTube. Here is another proof that even deleting all cookies and history in the browser can still be punctured.

What can be done here? There are several options. The first is to disable the swap file altogether. To do this, go to "Control Panel-> System and Security-> System-> Advanced System Settings-> Performance-> Advanced-> Virtual Memory-> Change" and select the "No paging file" option. The second option is to force the operating system to overwrite all the data in the swap file before turning off the computer. This mode is activated if you set the ClearPageFileAtShutdown key in the HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ Control \ Session Manager \ Memory Management value to "1". Unfortunately, the second method is very slow, and shutting down the system will take quite a long time, so whether to put it into practice or not, decide for yourself. A similar situation exists with the hiberfil.sys file. It can also be simply disabled, which will save additional disk space.

By the way, you can also explore the swap file under Windows. But since the operating system does not allow viewing and copying using standard tools, we need the FTK Imager program. Go to the "File-> Add Evidence Item" section and indicate the drive where the page file is located. A directory tree will appear in the left pane where you need to select pagefile.sys and use the export function through the context menu. The swap file will be copied to the folder specified by us without any problems, and no system locks from this moment will prevent it from being analyzed. For analysis, by the way, you can use DiskDigger or PhotoRec. The first is simpler, but the second can restore a wider range of different file formats.

Defragmentation

Let's move on to the next reason for the appearance of ghost files. To make it clearer and more understandable - again, we will conduct a small experiment. For him, we need a flash drive and the ability to handle WinHex. First, we will provide the conditions for the experience by deleting all the data from the flash drive. To do this, run WinHex, give the Open Disk command and select our device in the window that appears. After opening, completely select all its contents (Ctrl + A) and hammer it with zeros (Ctrl + L). One note - the dubbing process takes a sufficient amount of time, so I recommend taking a smaller flash drive. From this moment on, there is no data on the drive and, moreover, there is no file system. So the next step is to format the flash drive in NTFS. By default, Windows XP only allows the USB flash drive to be formatted in FAT, but NTFS is required for our manipulations. For the operating system to format the device to the file system we need, you need to go to the device manager, find the USB flash drive there and set the "Optimize for performance" option in the parameters. After that, Windows will be able to format the USB flash drive in NTFS.

The goal of our experience is to see what happens to files during defragmentation. To do this, we will create artificial fragmentation on our information carrier. Take any three jpeg files and any three audio files or video clips (the main thing is that their size be larger than jpegs) and copy them to a USB flash drive in the following order: 1.mp3, 1.jpg, 2.mp3, 2.jpg , 3.mp3, 3.jpg.

I wonder how they are located on the disk? To see this, we will use the DiskView tool from Mark Russinovich. It displays a graphical diagram of the disk, on which you can determine the location of the data or find out which file is occupied by certain clusters (for this you need to click on the cluster with the mouse). Double-clicking provides more detailed information about the file to which the cluster is allocated. Run the program, select our flash drive and click <Refresh> . First comes a green bar, indicating system clusters, but right after it is the area of blue clusters representing our files written one after another. Now create fragmentation by deleting all the audio files. Click again <Refresh> and we see that before each jpeg-file there is an empty area. Now briefly switch to WinHex. To make sure once again that there are no unnecessary graphic files on the flash drive, we will search by signature: look for the sequence "jfif" that is present in the header of any jpeg file. As a result, the editor, as expected, found exactly three such sequences, by the number of remaining files.

Well, the time has come to put things in order: it doesn’t matter when the files are scattered around like this :). We launch defragmentation, so beloved by users, for our media:

C: \ Documents and Settings \ Administrator> defrag h:
Windows Disk Defragmenter
Copyright (c) 2001 Microsoft Corp. and Executive Software International, Inc.

Analysis report
7.47 GB Total, 7.43 GB (99%) Free, 0% Fragmented (0% file fragmentation)

Defragmentation report
7.47 GB Total, 7.43 GB (99%) Free, 0% Fragmented (0% file fragmentation)

Defragmentation has passed, let's see what has changed on the flash drive. Click on <Refresh> in DiskView, and what do we see? Files that were located at a distance from each other are carefully transferred to the beginning of the disk, and are placed strictly sequentially. Now attention! Defragmented files copied to the beginning of the disk, placing them sequentially, but did she overwrite their previous copy with zeros? To answer this question, we again turn to the powerful hexadecimal editor. Search again for "jfif". Oops, now instead of the three lines found, we get as many as six! And this can only mean one thing - now each file is presented in duplicate. Any of them can be easily restored using DiskDigger or Photorec. Now imagine that instead of graphic files we had some confidential documents or files with credit card information. Even if we used utilities like Sdelete and rewrote these three files hundreds of times before deleting them, their ghosts would still remain on the disk and exist there indefinitely. Until overwritten by anything else. And all this time they can be restored!

Truth and myths about magnetic microscopy

Very often people go to two extremes. Some openly hammer on their safety and store on the screw all the incriminating information, being sure that <Shift+Delete> save them. Others, on the contrary, wipe the screw every day and reinstall the OS. Maybe I'm exaggerating. Nevertheless, quite often one has to read disputes on the Web about how many times it is necessary to rewrite a screw so that information cannot be restored. I propose empirically to find out whether one full rewrite is enough to permanently delete all data. So, again, let's take our experimental flash drive and completely rewrite it with zeros, and then format it in NTFS. To check, let’s drop some file on it: let it be JPEG again. It can be easily found in WinHex by the signature "jfif". I have it located at offset 274432. Well, let's start the shredder (I used the HDD Wipe Tool) and erase the entire disk. Now, if you look at WinHex, which is located at offset 274432, then we will see only zeros. To reassure and be more confident, you can try to recover data using DiskDigger, Photorec, Foremost and other utilities. But this is obviously a waste of time - nothing will come of them.

“Well,” you say, “what about the serious devices available to the competent authorities who can recover data?” Well, let's talk about magnetic microscopy. The essence of the method is to determine the state of each bit before overwriting it. That is, whether it was equal to one or zero. Take ASCII encoded text. Each character is encoded with eight bits in such a way that even if only one bit is restored incorrectly, a completely different character is obtained. For example, there is a sequence of “anti” characters, which looks in binary form as follows: 01100001011011100111010001101001. Suppose that magnetic bits have correctly detected all the bits except the last - as a result of this restoration we get the sequence “anth”. The problem turns out. And we are talking about the simplest text file. Imagine what will happen in the case of structured formats - such as archives, database files, executable files, and so on. In addition to this, the method is quite slow and expensive. So in many cases, the use of magnetic microscopy gives the same exact result as restoration by tossing a coin onto the tails. Therefore, there is no need to rewrite the disc three times.

Best defense is attack

What can be done to complicate the lives of people whom your computer may get for examination? There are several options. In the event that an “interesting” file is found on the computer, the time of its creation will be strong evidence against its owner. To trace the chain of events, experts also rely on the creation / access / modification time of the file. So why not confuse the footprints? There is such a wonderful utility on metasploit.com as Timestomp, which allows you to change the creation, modification or access time for a given file. The main options for its use:

-m <date> sets the date of the last file modification
-a <date> sets the date of the last access to the file
-c <date> sets file creation time
-e <date> sets file modification time stored in MFT
-z <date> sets four of the above parameters

The date is set as follows: DayofWeek Month \ Day \ Year HH: MM: SS [AM | PM].

There is also a very interesting option -b, which sets the above attributes in such a way that the EnCase program known in computer forensics circles does not see them and displays them empty :).

Thus, to change the file attributes, it is enough to execute the command in the console:

c: \> timestomp.exe boot.ini -z "sunday 1/12/2099 10:00:00 pm"

You can easily sketch a script that recursively changes the temporary attributes of files. The simplest option is as follows:

for / R c: \ tools \% i in (*) do timestomp.exe% i -z "monday 3/12/2009 10:00:00 pm"

There are other ways to spoil the life of fellow researchers of other people's HDDs. In their work, they use programs written by ordinary people, and therefore - containing errors. Yes, we can exploit vulnerabilities in the software used to search for evidence. You can read more about this in one of the reports from the DefCon conference.

Conclusion

Secure Data Deletion is not a panacea. I dare to assure you that the loopholes described are not the only ones of their kind. And who, by occupation, conducts computer expertise at a professional level, knows where and how to find the data he needs. Now your safety is in your hands - do not let “ghostbusters” find a single “ghost” on your computer. And even better - do not give them a reason to come to visit you :).

Programs for safe data deletion:

Eraser 6.0.8;
SDelete 1.51;
Freeraser
Overwrite 0.1.5;
Wipe 2.3.1;
Secure Delete
CCleaner 3.03.
 
Original message
Для следователя, проводящего анализ компьютера подозреваемого, всегда есть данные, представляющие особый интерес. Но некоторым кажется, что если перезаписать область, где находился файл, случайными данными, то восстановить уже ничего не удастся. Это правда, но лишь отчасти. Даже после такой перестраховки данные нередко удается извлечь!

Что происходит при удалении файла? Очень просто: в файловой системе для него меняется один атрибут, и таким образом он помечается как удаленный. При этом содержание файла по-прежнему остается на жестком диске, и его можно восстановить с помощью одной из множества платных и бесплатных программ (например, R-Studio). Мы много раз писали о том, как безопасно удалить файлы без возможности восстановления. Благо для этого разработано огромное количество утилит-шредеров, которые с помощью несложных методик перезаписывают участки диска, на которых были расположены удаленные данные. Таким образом даже при использовании технологий восстановления, при которых производится считывание данных непосредственно с магнитных носителей, восстановить удаленные файлы будет невозможно. В эффективности такого подхода нас заверяли даже настоящие профессионалы в области восстановления данных. Но — лазейки для извлечения информации у гуру все-таки есть!

Файлы изображений

Начнем с рассмотрения простого случая — удаления обычной фотографии. Допустим, у нас есть папка с фотографиями, и мы избавляемся от одной из них. Причем удаляем по всем правилам, перезаписав нужную область диска несколько раз. По идее больше ничего не должно выдавать ее существования (если мы сами до этого не скопировали ее в другую папку и не забыли про это). Но тут-то как раз многие и забывают об одной особенности Windows — файле Thumbs.db. Это специальное хранилище, используемое операционной системой, в котором находятся эскизы изображений из текущей папки. Если в проводнике выбрать режим отображения "Эскизы страниц", то операционка будет брать уменьшенные превьюшки изображений как раз из этого файла. Он создается в каждой папке, в которой есть картинки, и содержит уменьшенные эскизы изображений в формате JPEG (вне зависимости от формата исходного изображения).

Проведем небольшой эксперимент — создадим папку и поместим туда три любых картинки. Теперь откроем эту директорию в проводнике — появился Thumbs.db (чтобы увидеть этот файл, надо включить отображение скрытых файлов). Мы можем просмотреть и проанализировать его с помощью утилиты Thumbnail Database Viewer. Программа, как и положено, показывает эскизы для всех трех файлов. А теперь удалим один из них с помощью программы SDelete или любой другой программы для безопасного удаления данных:

sdelete.exe -p 2 file1.jpg

Параметр р отвечает за количество проходов шредера, то есть указывает, сколько раз файл будет перезаписан перед удалением. В результате изображение будет безвозвратно стерто с жесткого диска. Но посмотрим, повлияло ли как-то это удаление на Thumbs.db? Заново открываем его, и что мы видим? Эскиз для удаленной картинки по-прежнему на месте! Получается, что файл легко может содержать эскизы уже удаленных изображений. И на этом, как мне рассказывали, попался не один умный человек…

Как этого избежать? Очень просто — нужно просто отключить кэширование эскизов в файлах Thumbs.db. На Windows XP необходимо установить для ключа DisableThumbnailCache в разделе HKEY_CURRENT_USER\Software\ Microsoft\Windows\CurrentVersion\Explorer\Advanced значение "1". В Windows 7 этот ключ имеет имя NoThumbnailCache и находится в HKEY_CURRENT_USER\Software\Microsoft\ Windows\CurrentVersion\Policies\Explorer. И, само собой, важно не забыть удалить все Thumbs.db.

Файл подкачки

Подставы со стороны операционной системы на одном только файле с эскизами не заканчиваются. По мере работы с документом информация о нем попадает в различные части ОС — временную папку, реестр и так далее. Поэтому очень трудно отследить и удалить все связанные с файлом данные. Вдобавок ко всему, есть места, где копия файла может оказаться совершенно случайно (иногда такая случайность может стоить очень дорого). Я говорю о файле подкачки (pagefile.sys) и свопе памяти, используемом во время режима Hibernation (hiberfil.sys). Предсказать содержимое файла подкачки заведомо невозможно, и тут никто ничего не может гарантировать. Предлагаю еще на одном эксперименте убедиться в том, что это — опасное место.

Поскольку просмотреть или скопировать файл подкачки операционная система просто так не дает, то у нас есть два варианта: задействовать специальные утилиты или же загрузиться в другую операционку и получить доступ к файлу из нее. Мне второй способ показался более простым, так как под рукой был Back Track, начиненный различными утилитами, в том числе и для восстановления файлов. Поэтому, загрузившись с LiveCD, я смонтировал виндовый раздел и пошел в раздел "BackTrack->Forensic", откуда запустил утилиту Foremost. Эта замечательная консольная прога умеет восстанавливать файлы исходя из их заголовков и внутренней структуры. Необходимо лишь передать имя входного файла, в котором будет осуществляться поиск, и указать директорию, куда будут сохранены все найденные данные:

#foremost -i /mnt/hda1/pagefile.sys -o /root/Desktop/page_file -v -q

В качестве входного файла я указал файл подкачки /mnt/hda1/pagefile.sys, а директорию для сохранения результатов — /root/Desktop/page_file. Программа начала свою работу. За короткое время Foremost сумел найти и извлечь 524 файла.

Статистика извлеченных файлов:
jpg:= 73
gif:= 4
gif:= 19
jpg:= 77
jpg:= 95
doc:= 1
pgp:= 65
pgp:= 62
pgp:= 44
pgp:= 36
dat:= 7
lnk:= 3
cookie:= 38

Утилита удобно отсортировала все файлы по типу и разложила по разным папкам. Первым делом я полез проверять, что же попало в папку jpg. Из всех восстановленных файлов около половины отказалось отображаться, зато другая — отлично просматривалась. И чего только не было среди картинок: пара фоток, которые я не так давно удалил; много мелких изображений с веб-сайтов; аватарки друзей из Facebook и прочее. Честно сказать, я не планировал обнаружить так много изображений. Кроме картинок мне хотелось еще узнать, что за единственный doc-файл, который попал в файл подкачки. Но, к сожалению, Word лишь ругнулся, что файл попорчен и не смог его открыть. Неожиданный сюрприз ждал меня в папке cookie — бегло пролистав несколько файлов, я обнаружил адреса роликов, которые я смотрел чуть ли не год назад на YouTube. Вот и еще одно доказательство, что даже удалив в браузере все куки и историю, все равно можно проколоться.

Что тут можно сделать? Есть несколько вариантов. Первый — отключить вообще файл подкачки. Для этого надо зайти в "Control Panel-> System and Security-> System-> Advanced System Settings-> Performance-> Advanced-> Virtual Memory-> Change" и выбрать опцию "No paging file". Второй вариант — заставить операционную систему затирать все данные в файле подкачки перед выключением компьютера. Такой режим активируется, если установить для ключа ClearPageFileAtShutdown в разделе HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\ Control\Session Manager\Memory Management значение "1". К сожалению, второй метод очень медленный, и выключение системы будет занимать достаточно длительное время, так что применять его на практике или нет — решай сам. Аналогичная ситуация и с файлом hiberfil.sys. Его также можно попросту отключить, что сэкономит дополнительное место на диске.

Кстати, исследовать файл подкачки можно и под виндой. Но так как операционная система не дает его просмотреть и скопировать с помощью штатных средств, нам понадобится программка FTK Imager. Переходим в раздел "File-> Add Evidence Item" и указываем диск, где находится файл подкачки. На панели слева отобразится дерево каталогов, где необходимо выбрать pagefile.sys и воспользоваться функцией экспорта через контекстное меню. Файл подкачки без проблем скопируется в указанную нами папку, и никакие блокировки системы с этого момента не помешают его анализировать. Для анализа, кстати, можно воспользоваться DiskDigger или PhotoRec. Первая — проще, но вторая умеет восстанавливать более широкий круг различных форматов файлов.

Дефрагментация

Перейдем к следующей причине появления файлов-призраков. Чтобы было наглядней и понятней — опять же проведем небольшой эксперимент. Для него нам понадобится флешка и умение обращаться с WinHex’ом. Сначала обеспечим условия для опыта, удалив все данные с флешки. Для этого запустим WinHex, отдадим команду Open Disk и в появившемся окне выберем наш девайс. После открытия полностью выделяем все его содержимое (Ctrl+A) и забиваем нулями (Ctrl+L). Одно замечание — процесс перезаписи занимает достаточное количество времени, так что рекомендую взять флешку поменьше. С этого момента на драйве нет данных и, более того, нет файловой системы. Так что следующим шагом будет форматирование флешки в NTFS. По умолчанию Windows XP дает форматировать флешку только в FAT, но для наших манипуляций требуется NTFS. Чтобы операционная система позволила отформатировать устройство в нужную нам файловую систему, необходимо зайти в диспетчер устройств, найти там флешку и в параметрах установить опцию "Optimize for performance". После этого винда сможет отформатировать флешку в NTFS.

Цель нашего опыта — посмотреть, что происходит с файлами во время дефрагментации. Для этого создадим искусственную фрагментацию на нашем носителе информации. Возьмем три любых jpeg-файла и три каких-нибудь аудиофайла или видеоклипа (главное, чтобы их размер был больше jpeg’ов) и скопируем их на флешку в следующем порядке: 1.mp3, 1.jpg, 2.mp3, 2.jpg, 3.mp3, 3.jpg.

Интересно, как же они расположились на диске? Чтобы посмотреть это, воспользуемся тулзой DiskView от Марка Руссиновича. Она выводит графическую схему диска, на которой можно определить местоположение данных или узнать, какой файл занимает те или иные кластеры (для этого нужно щелкнуть на кластер мышью). Двойной щелчок позволяет получить более подробную информацию о файле, которому выделен кластер. Запускаем программу, выбираем нашу флешку и нажимаем <Refresh>. Сначала идет зеленая полосочка, обозначающая системные кластеры, а вот сразу за ней — область синих кластеров, представляющих наши файлы, записанные друг за другом. Теперь создадим фрагментацию, удалив все аудиофайлы. Снова нажимаем <Refresh> и видим, что перед каждым jpeg-файлом есть пустая область. Теперь ненадолго переключимся в WinHex. Чтобы еще раз убедиться, что на флешке нет никаких лишних графических файлов, проведем поиск по сигнатуре: ищем последовательность "jfif", присутствующую в заголовке любого jpeg-файла. В итоге редактор, как и ожидалось, нашел ровно три таких последовательности, по числу оставшихся файлов.

Ну что ж, пришло время навести порядок: не дело, когда файлы вот так разбросаны по диску :). Запускаем дефрагментацию, столь любимую пользователями, для нашего носителя:

C:\Documents and Settings\Administrator>defrag h:
Windows Disk Defragmenter
Copyright (c) 2001 Microsoft Corp. and Executive Software International, Inc.

Analysis Report
7,47 GB Total, 7,43 GB (99%) Free, 0% Fragmented (0% file fragmentation)

Defragmentation Report
7,47 GB Total, 7,43 GB (99%) Free, 0% Fragmented (0% file fragmentation)

Дефрагментация прошла, посмотрим, что изменилось на флешке. Жмем на <Refresh> в программе DiskView, и что мы видим? Файлы, которые располагались на расстоянии друг от друга, аккуратно перенесены в начало диска, и располагаются строго последовательно. А теперь внимание! Дефрагментация скопировала файлы в начало диска, расположив их последовательно, но перезаписала ли она их предыдущую копию нулями? Чтобы ответить на этот вопрос, опять обратимся к мощному шестнадцатиричному редактору. Снова проведем поиск по "jfif". Оп-па, теперь вместо трех найденных строк получаем целых шесть! И это может означать только одно — теперь каждый файл представлен в двух экземплярах. Любой из них легко восстанавливается с помощью DiskDigger’a или Photorec’a. А теперь представь, что вместо графических файлов у нас были какие-то конфиденциальные документы или файлы с данными по кредиткам. Даже если бы мы использовали утилиты типа Sdelete и переписали перед удалением эти три файла сотни раз, их призраки все равно остались бы на диске и существовали там неопределенно долгое время. До тех пор, пока не будут перезаписаны чем-либо еще. И все это время их можно будет восстановить!

Правда и мифы о магнитной микроскопии

Очень часто люди впадают в две крайности. Одни откровенно забивают на свою безопасность и хранят на винте всю компрометирующую информацию, будучи уверенными, что <Shift+Delete> их спасет. Другие же, наоборот, каждый день затирают винт и заново устанавливают операционку. Быть может, я утрирую. Тем не менее, довольно часто приходится читать в Сети споры о том, сколько же раз надо перезаписать винт, чтобы информацию невозможно было восстановить. Предлагаю опытным путем выяснить, хватит ли одной полной перезаписи, чтобы безвозвратно удалить все данные. Итак, опять возьмем нашу подопытную флешку и полностью перезапишем ее нулями, после чего отформатируем в NTFS. Для проверки закинем на нее какой-нибудь файл: пусть это будет опять же JPEG. Его легко можно найти в WinHex’е по сигнатуре "jfif". У меня он расположился по смещению 274432. Ну что ж, запустим шредер (я юзал HDD Wipe Tool) и затрем весь диск. Теперь, если посмотреть в WinHex, что расположилось по смещению 274432, то мы увидим только нули. Для успокоения и большей уверенности можно попробовать восстановить данные с помощью DiskDigger, Photorec, Foremost и прочих утилит. Но это заведомо пустая трата времени — ничего у них не выйдет.

"Хорошо, — скажешь ты, — а как же насчет серьезных приборов, имеющихся у компетентных органов, которые умеют восстанавливать данные?" Ну что ж, давай поговорим о магнитной микроскопии. Суть метода в том, чтобы определить состояние каждого бита до его перезаписи. То есть, был ли он равен единице или нулю. Возьмем текст в кодировке ASCII. Каждый символ кодируется восемью битами таким образом, что если даже всего один бит восстановлен неверно — получается совсем другой символ. Например, есть последовательность символов "anti", выглядящая в бинарном виде следующим образом: 01100001011011100111010001101001. Предположим, что магнитная микроскопия правильно определила все биты, кроме последнего — в результате такого восстановления мы получаем последовательность "anth". Неувязочка получается. И это мы говорим о простейшем текстовом файле. Представь, что будет в случае со структурированными форматами — такими как архивы, файлы БД, исполняемые файлы и так далее. Вдобавок к этому метод достаточно медленный и дорогой. Так что во многих случаях использование магнитной микроскопии дает такой же точный результат, как и восстановление путем подбрасывания монетки на "орел-решка". Поэтому нет никакой необходимости по три раза перезаписывать диск.

Лучшая защита — это нападение

Что можно сделать, чтобы усложнить жизнь людям, к которым может попасть для экспертизы твой компьютер? Тут есть несколько вариантов. В случае, если на компьютере нашли "интересный" файл, время его создания будет веским доказательством против его владельца. Чтобы проследить цепь событий, эксперты опираются также на время создания/доступа/модификации файла. Так почему бы не запутать следы? На сайте metasploit.com есть такая замечательная утилита, как Timestomp, которая позволяет менять время создания, модификации или доступа для заданного файла. Основные опции для ее использования:

-m <date> задает дату последней модификации файла
-a <date> задает дату последнего доступа к файлу
-c <date> задает время создания файла
-e <date> задает время модификации файла, хранящееся в MFT
-z <date> задает четыре вышеперечисленных параметра

Дата задается в следующем виде: DayofWeek Month\Day\Year HH:MM:SS [AM|PM].

Есть еще очень интересная опция -b, которая устанавливает вышеперечисленные атрибуты таким образом, что известная в кругах компьютерных криминалистов программа EnCase их не видит и отображает пустыми :).

Таким образом, чтобы поменять атрибуты файла, достаточно выполнить в консоли команду:

c:\>timestomp.exe boot.ini -z "sunday 1/12/2099 10:00:00 pm"

Легко можно набросать скриптик, который будет рекурсивно менять временные атрибуты файлов. Простейший вариант выглядит так:

for /R c:\tools\ %i in (*) do timestomp.exe %i -z "monday 3/12/2009 10:00:00 pm"

Есть и другие способы подпортить жизнь товарищам-исследователям чужих HDD. В своей работе они используют программы, написанные обычными людьми, а потому — содержащими ошибки. Да-да, мы можем использовать уязвимости программного обеспечения, применяемого для поиска улик. Подробней об этом можно почитать в одном из докладов с конференции DefCon.

Заключение

"Безопасное удаление данных" – это не панацея. Смею тебя заверить, что описанные лазейки — не единственные в своем роде. И тот, кто по роду деятельности проводит экспертизы компьютеров на профессиональном уровне, знает, где и как найти необходимые ему данные. Теперь твоя безопасность в твоих руках — не дай "охотникам за приведениями" найти ни одного "призрака" на твоем компе. А еще лучше — не давай им повода приходить к тебе в гости :).

Программы для безопасного удаления данных:

Eraser 6.0.8;
SDelete 1.51;
Freeraser;
Overwrite 0.1.5;
Wipe 2.3.1;
Secure Delete;
CCleaner 3.03.
Joined
Jan 21, 2011
Messages
1,086
Reaction score
202
Points
63
Location
Россия
Website
www.
Are there any such specialists at our Forum?
If he (they) is modest (s), then please inform in a "personal".
 
Original message
Есть ли на нашем Форуме подобные специалисты?
Если он(они) скромный(ые), то прошу сообщить в "личку".

Гудимов Анатолий Геннадиевич

Зарегистрированный
Joined
May 26, 2009
Messages
938
Reaction score
4
Points
18
Age
61
Location
Россия Санкт-Петербург, Москва.
Website
iapd.info
Powerful magnets - a panacea for recovering all data! : lol:
 
Original message
Мощные магниты - панацея от восстановления всех данных! :lol:

Детективное бюро Бориса Турецкого

Private access level
Full members of NP "MOD"
St. Petersburg section IAPD
Joined
Apr 1, 2013
Messages
158
Reaction score
42
Points
28
Age
34
Location
город Санкт-Петербург
Website
mydetektiv.ru
Thank you Marat!
Very useful stuff!
 
Original message
Спасибо, Марат!
Очень полезный материал!

Плотников Юрий Михайлович

Private access level
Full members of NP "MOD"
Joined
Jul 21, 2010
Messages
3,699
Reaction score
563
Points
113
Age
71
Location
Россия, Хабаровск. +7 914 544 16 90.
Website
www.sysk-dv.ru
Thank you Marat!
 
Original message
Спасибо, Марат!

Eugen

Private access level
Joined
Feb 7, 2011
Messages
205
Reaction score
6
Points
18
At the moment, it becomes popular water cooling and therefore it will be very difficult for an expert to restore something. And I want to draw attention to the fact that after deleting information from the disk, formatting, recording the same amount of information - the data cannot be restored. Another feature is who will recover the data, which program (if the recovery is not successful, no one can restore the data.)
 
Original message
На данный момент становится популярное водное охлаждение и поэтому эксперту очень трудно будет что то восстановить. И хочу обратить внимание, что после удаления информации с диска, форматирование, запись такого же размера информации - данные невозможно восстановить. Ещё одна особенность кто будет восстанавливать данные, какой программой (если восстановление не удачное никто восстановить данные не сможет.)
Joined
Jan 21, 2011
Messages
1,086
Reaction score
202
Points
63
Location
Россия
Website
www.
Марат said:
But it seems to some that if you overwrite the area where the file was located with random data, then nothing will be restored. This is true, but only in part. Even after such reinsurance, data can often be retrieved!

Евгений said:
And I want to draw attention to the fact that after deleting information from the disk, formatting, recording the same amount of information - the data cannot be restored.

Dear Colleagues!
On the issue of data recovery, you have two completely opposite opinions.
The law of unity and struggle of opposites. :)
I would like to read the opinion of a qualified IT expert in this thread.
 
Original message
Марат said:
Но некоторым кажется, что если перезаписать область, где находился файл, случайными данными, то восстановить уже ничего не удастся. Это правда, но лишь отчасти. Даже после такой перестраховки данные нередко удается извлечь!

Евгений said:
И хочу обратить внимание, что после удаления информации с диска, форматирование, запись такого же размера информации - данные невозможно восстановить.

Уважаемые коллеги!
По вопросу восстановления данных у вас два, совершенно противоположных мнения.
Закон единства и борьбы противоположностей. :)
Хотелось бы прочитать в этой теме мнение квалифицированного IT - эксперта.

Eugen

Private access level
Joined
Feb 7, 2011
Messages
205
Reaction score
6
Points
18
SKF Budaev and partners. Tula.
Yes, I do not argue, a person learns all his life. I have my own vision of the situation, I can also be mistaken - if so, provide a reasoned answer. (by the way, I did an experiment)
 
Original message
СКФ Будаев и партнёры. Тула.
Да я не спорю, человек учится всю жизнь. У меня есть своё видение ситуации, я тоже могу ошибиться - если это так предоставте аргументированный ответ. (к стати я проводил экспиремент)

Vlas

Участник
Joined
Jul 30, 2011
Messages
21
Reaction score
1
Points
3
"What can be done to complicate the lives of people to whom your computer may get for examination?"
You can use disk encryption. If protection like setting a password on the BIOS can be circumvented (it is ridiculous to even mention the password on WINDOWS), then nothing can be done with the encrypted drive.
You can encrypt using both the OS and third-party programs. In the first case, it is possible to encrypt even the system drive - in the other, only individual folders or non-system drives. If the password is long enough, then without knowing it, you can see the contents of such a disk only with the help of thermorectal cryptanalysis.
You can also use virtual machines.
Programs like VMWARE Workstation or VirtualBox allow you to run another virtual one under the main OS. In practice, this means computer-in-computer. On one computer, you can simultaneously run several independent from each other OS, while one will be the main and the other will be virtual in its window. In this case, the virtual machine will be stored on the computer as a file. Accordingly, "in which case" it all comes down to simply deleting the virtual machine file from the hard drive. If the removal was done correctly (by a special program-shredder), then it will be impossible to restore the virtual machine, as well as everything that was contained in it.
 
Original message
"Что можно сделать, чтобы усложнить жизнь людям, к которым может попасть для экспертизы твой компьютер?"
Можно использовать шифрование диска. Если защиты вроде установки пароля на BIOS можно обойти (про пароль на WINDOWS даже упоминать смешно) - то с шифрованным диском ничего сделать не получится.
Зашифровать можно как средствами самой OS так и сторонними программами. В первом случае возможно зашифровать даже системный диск - в другом только отдельные папки или несистемные диски. Если пароль будет достаточно длинный - то не зная его посмотреть содержимое такого диск можно будет только с помощью терморектального криптоанализа.
Еще можно использовать виртуальные машины.
Программы типа VMWARE Workstation или VirtualBox позволяют запустить под основной OS другую - виртуальную. Практически это означает "компьютер-в-компьютере". На одном компьютере можно одновременно запустить несколько независимых друг от друга OS, при этом одна будет основная а другая- виртуальная в своем окне. При этом храниться виртуальная машина будет на компьютере в виде файла. Соответственно "в случае чего" все сводится к простому удалению файла виртуальной машины с винчестера. Если удаление произведено грамотно (специальной программой-шредером), то восстановить виртуальную машину а равно и все что в ней содержалось будет невозможно.