Kontaktieren Sie uns in Messenger oder per Telefon.

whatsapp telegram viber phone email
+79214188555

How forensics recover deleted data

DronVR

Nivel de acceso privado
Registrado
1 Jun 2014
Mensajes
284
Puntuación de reacción
262
Puntos
63
How forensics recover deleted data

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).

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 Explorer, then the OS will take thumbnail previews of the images 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

Parameter R It 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 came across.

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_USERSoftware MicrosoftWindowsCurrentVersionExplorerAdvanced section to "1". On Windows 7, this key is named NoThumbnailCache and is located in HKEY_CURRENT_USERSoftware Microsoft WindowsCurrentVersionPoliciesExplorer. 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'm talking about a page file ( pagefile.sys ) and the memory swap used during mode Hibernation ( 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:

Código:
 #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 section
HKEY_LOCAL_MACHINE \ SYSTEM \ CurrentControlSet \ ControlSession ManagerMemory Management value "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 program [DLMURL="https://anonym.to/?https://accessdata.com/support/adownloads"] FTK Imager [/ DLMURL ]. 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 [DLMURL="https://anonym.to/?https://diskdigger.org/"] DiskDigger [/ DLMURL] or [DLMURL="https://anonym.to/?http : //www.cgsecurity.org/wiki/PhotoRec "] PhotoRec [/ DLMURL]. 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 use the tool [DLMURL="https://anonym.to/?https://technet.microsoft.com/en-us/sysinternals/bb896650"] DiskView [/ DLMURL] by 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. The time has come to put things in order: it doesn’t matter when files are scattered like this on a disk. We launch defragmentation, so beloved by users, for our media:

Código:
 C: Documents and SettingsAdministrator> 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 “jfif” signature. 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 that 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 that looks in binary form as follows: 01100001011011100111010001101001. Suppose that magnetic microscopy has correctly detected all the bits except the last one - as a result of such 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 case a “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:

Código:
 -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 MonthDayYear 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, well-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ódigo:
 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:

Código:
 for / R c: tools% i in (*) do timestomp.exe% i -z "monday 3/12/2009 10:00:00 pm"
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.


Programs for safe data deletion:
  • Eraser 6.0.8;
  • SDelete 1.51;
  • Freeraser
  • Overwrite 0.1.5;
  • Secure Delete
  • CCleaner 3.03.
Source @Blacktime
 
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_USERSoftware MicrosoftWindowsCurrentVersionExplorerAdvanced значение «1». В Windows 7 этот ключ имеет имя NoThumbnailCache и находится в HKEY_CURRENT_USERSoftwareMicrosoft WindowsCurrentVersionPoliciesExplorer. И, само собой, важно не забыть удалить все Thumbs.db.

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

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

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

Código:
#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\ ControlSession ManagerMemory Management значение «1». К сожалению, второй метод очень медленный, и выключение системы будет занимать достаточно длительное время, так что применять его на практике или нет — решай сам. Аналогичная ситуация и с файлом hiberfil.sys. Его также можно попросту отключить, что сэкономит дополнительное место на диске.



Кстати, исследовать файл подкачки можно и под виндой. Но так как операционная система не дает его просмотреть и скопировать с помощью штатных средств, нам понадобится программка [DLMURL="https://anonym.to/?https://accessdata.com/support/adownloads"]FTK Imager[/DLMURL]. Переходим в раздел «File-> Add Evidence Item» и указываем диск, где находится файл подкачки. На панели слева отобразится дерево каталогов, где необходимо выбрать pagefile.sys и воспользоваться функцией экспорта через контекстное меню. Файл подкачки без проблем скопируется в указанную нами папку, и никакие блокировки системы с этого момента не помешают его анализировать. Для анализа, кстати, можно воспользоваться [DLMURL="https://anonym.to/?https://diskdigger.org/"]DiskDigger[/DLMURL] или [DLMURL="https://anonym.to/?https://www.cgsecurity.org/wiki/PhotoRec"]PhotoRec[/DLMURL]. Первая — проще, но вторая умеет восстанавливать более широкий круг различных форматов файлов.

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

Перейдем к следующей причине появления файлов-призраков. Чтобы было наглядней и понятней — опять же проведем небольшой эксперимент. Для него нам понадобится флешка и умение обращаться с 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.

Интересно, как же они расположились на диске? Чтобы посмотреть это, воспользуемся тулзой [DLMURL="https://anonym.to/?https://technet.microsoft.com/ru-ru/sysinternals/bb896650"]DiskView[/DLMURL] от Марка Руссиновича. Она выводит графическую схему диска, на которой можно определить местоположение данных или узнать, какой файл занимает те или иные кластеры (для этого нужно щелкнуть на кластер мышью). Двойной щелчок позволяет получить более подробную информацию о файле, которому выделен кластер. Запускаем программу, выбираем нашу флешку и нажимаем <Refresh>. Сначала идет зеленая полосочка, обозначающая системные кластеры, а вот сразу за ней — область синих кластеров, представляющих наши файлы, записанные друг за другом. Теперь создадим фрагментацию, удалив все аудиофайлы. Снова нажимаем <Refresh> и видим, что перед каждым jpeg-файлом есть пустая область. Теперь ненадолго переключимся в WinHex. Чтобы еще раз убедиться, что на флешке нет никаких лишних графических файлов, проведем поиск по сигнатуре: ищем последовательность «jfif», присутствующую в заголовке любого jpeg-файла. В итоге редактор, как и ожидалось, нашел ровно три таких последовательности, по числу оставшихся файлов. Пришло время навести порядок: не дело, когда файлы вот так разбросаны по диску. Запускаем дефрагментацию, столь любимую пользователями, для нашего носителя:

Código:
C:Documents and SettingsAdministrator>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, которая позволяет менять время создания, модификации или доступа для заданного файла. Основные опции для ее использования:

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

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

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

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

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

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

Código:
for /R c:tools %i in (*) do timestomp.exe %i -z "monday 3/12/2009 10:00:00 pm"
Безопасное удаление данных – это не панацея. Смею Вас заверить, что описанные лазейки — не единственные в своем роде. И тот, кто по роду деятельности проводит экспертизы компьютеров на профессиональном уровне, знает, где и как найти необходимые ему данные.


Программы для безопасного удаления данных:
  • Eraser 6.0.8;
  • SDelete 1.51;
  • Freeraser;
  • Overwrite 0.1.5;
  • Secure Delete;
  • CCleaner 3.03.
Источник @Blacktime
Última edición: