Magic Number Definition
A magic number is a number embedded at or near the beginning of a file that indicates its file format (i.e., the type of file it is). It is also sometimes referred to as a file signature.
Magic numbers are generally not visible to users. However, they can easily be seen with the use of a hex editor, which is a specialized program that shows and allows modification of every byte in a file.
For common file formats, the numbers conveniently represent the names of the file types. Thus, for example, the magic number for image files conforming to the widely used GIF87a format in hexadecimal (i.e., base 16) terms is 0x474946383761, which when converted into ASCII is GIF87a. ASCII is the de facto standard used by computers and communications equipment for character encoding (i.e., associating alphabetic and other characters with numbers).
Likewise, the magic number for image files having the subsequently introduced GIF89a format is 0x474946383961. For both types of GIF (Graphic Interchange Format) files, the magic number occupies the first six bytes of the file. They are then followed by additional general information (i.e., metadata) about the file.
Similarly, a commonly used magic number for JPEG (Joint Photographic Experts Group) image files is 0x4A464946, which is the ASCII equivalent of JFIF (JPEG File Interchange Format). However, JPEG magic numbers are not the first bytes in the file; rather, they begin with the seventh byte. Additional examples include 0x4D546864 for MIDI (Musical Instrument Digital Interface) files and 0x425a6831415925 for bzip2 compressed files.
Magic numbers are not always the ASCII equivalent of the name of the file format, or even something similar. For example, in some types of files they represent the name or initials of the developer of that file format. Also, in at least one type of file the magic number represents the birthday of that format’s developer.
Various programs make use of magic numbers to determine the file type. Among them is the command line (i.e., all-text mode) program named file, whose sole purpose is determining the file type.
Although they can be useful, magic numbers are not always sufficient to determine the file type. The main reason is that some file types do not have magic numbers, most notably plain text files, which include HTML (hypertext markup language), XHTML (extensible HTML) and XML (extensible markup language) files as well as source code.
Fortunately, there are also other means that can be used by programs to determine file types. One is by looking at a file’s character set (e.g., ASCII) to see if it is a plain text file. If it is determined that a file is a plain text file, then it is often possible to further categorize it on the basis of the start of the text, such as for HTML files and #! (the so-called shebang) for script (i.e., short program) files.
Another way to determine file types is through the use of filename extensions (e.g., .exe, .html and .jpg), which are required on the various Microsoft operating systems but only to a small extent on Linux and other Unix-like operating systems. However, this approach has the disadvantage that it relatively easy for a user to accidentally change or remove the extensions, in which case it becomes difficult to determine the file type and use the file.
Still another way that is possible in the case of some commonly used filesystems is through the use of file type information that is embedded in each file’s metadata. In Unix-like operating systems, such metadata is contained in inodes, which are data structures (i.e., efficient ways of storing information) that store all the information about files except their names and their actual data.
Magic numbers are referred to as magic because the purpose and significance of their values are not apparent without some additional knowledge. The term magic number is also used in programming to refer to a constant that is employed for some specific purpose but whose presence or value is inexplicable without additional information.
Created August 21, 2006.
Copyright © 2006 The Linux Information Project. All Rights Reserved.
Источник
Работа с магическими числами в Linux
Цель этой статьи — дать представление о магических числах и заголовках файлов, о том, как извлечь файл на основе магических чисел и как повредить и восстановить файл на основе магических чисел в среде Linux.
Волшебные числа
Магические числа — это первые несколько байтов файла, которые являются уникальными для определенного типа файлов. Эти уникальные биты упоминаются как магические числа, также иногда называемые сигнатурой файла.
Эти байты могут использоваться системой для « различения и распознавания разных файлов » без расширения файла.
Обнаружение магических чисел в сигнатурах файлов
Большинство файлов имеют подписи в байтах в начале файла, но некоторые файловые системы могут даже иметь подпись файла со смещениями, отличными от начала. Например, файловая система ext2 / ext3 имеет байты 0x53 и 0xEF в 1080-й и 1081-й позиции.
- Некоторые файлы, однако, не имеют магических чисел, таких как текстовые файлы, но могут быть идентифицированы путем проверки набора символов (ASCII в случае текстовых файлов).
Это можно сделать с помощью команды: - Магические числа / подписи файлов обычно не видны пользователю, но их можно увидеть с помощью шестнадцатеричного редактора или команды «xxd», как указано ниже. Эти байты необходимы для открытия файла.
- Изменение / повреждение этих байтов сделает файл бесполезным, так как большинство инструментов не получат доступ к этим файлам из-за возможного повреждения.
- Команда file в Linux reader читает магические числа файла и отображает тип файла на основе магического числа.
- Например, давайте возьмем пример файла PNG. Мы можем просмотреть шестнадцатеричный файл, введя следующую команду в терминале Linux (kali Linux используется в этой статье). Эта команда создает hexdump файла, который мы передаем ему.
Это дает следующий результат:
На этом изображении мы видим, что первый набор байтов файла
Эти цифры помогают системе определить тип используемого файла. Некоторые файлы, которые не записаны с их расширением, идентифицируются с помощью этих магических чисел.
Пример Zip-файла. Аналогичным образом используйте вышеупомянутую команду для Zip-файла.
На изображении выше мы видим, что файл начинается с:
Добавление одного файла в другой и идентификация деления с помощью магических чисел
Мы можем использовать python для выполнения этой операции. По сути, мы будем читать байты двух файлов и записывать их один за другим в пустой файл. В этой статье мы объединяем PNG с Zip-файлом.
«»»
Первые две строки открывают два файла для чтения побайтово
Третья строка открывает выходной файл для записи побайтно
«»»
input_file_1 = open ( «image.png» , ‘rb’ ).read()
input_file_2 = open ( «test.zip» , ‘rb’ ).read()
output_file = open ( «output.png» , ‘wb’ )
Используя этот код Python, мы получаем файл output.png. При запуске команды:
в этом файле мы видим, что он начинается с того же гексагона 8950 4e47 0d0a 1a0a. Однако, если мы запустим команду
который будет искать магические числа (PK — это ASCII-эквивалент 50 3b) zip-файла среди гексагона,
мы получим следующий вывод:
На этом рисунке мы видим, что магические числа zip-файла присутствуют в шестнадцатеричном формате png, что означает, что мы успешно добавили шестнадцатеричный файл zip-файла к png. Следующим шагом является отделение этого zip-файла от png.
Существует простая утилита binwalk, которая помогает нам легко выполнить эту задачу, набрав:
Как использовать магические числа и смещения для извлечения zip-файла из вывода:
- Найдите начальное смещение файла, который вы хотите извлечь: в этом примере мы хотим извлечь файл zip из PNG. Итак, мы сначала ищем заголовок ZIP. Как показано на предыдущем рисунке, мы выполняем команду ‘xxd output.png | Греп «ПК». На этом рисунке мы видим смещение в левом столбце. Для zip-файла смещение будет 00001c90.
- Вычислите количество бит по смещению, с которого начинается заголовок вашего файла: Теперь мы должны вычислить количество бит по смещению, с которого начинается zip-файл. Мы можем вручную посчитать это и наблюдать, что это 00001c95 (каждое шестнадцатеричное значение соответствует 1 биту)
- Преобразуйте это шестнадцатеричное значение в десятичное: это можно сделать, открыв IDLE Python (типа «python» в терминале Linux. Теперь мы должны преобразовать это значение в десятичное. В IDLE Python мы должны просто добавить 0x в начало значение, найденное на предыдущем шаге.
- Используйте следующую команду:
В вышеупомянутой команде «if» обозначает входной файл, «skip» обозначает количество битов, которые необходимо пропустить, чтобы достичь начала файла, который мы хотим извлечь, «bs» относится к числу байтов, которые должны быть прочитанным за раз, а ‘of’ относится к имени выходного файла.
Обратитесь к рисунку ниже, чтобы увидеть использование шагов 3 и 4:
Как повредить файл, изменив его магический номер?
Изменение магических номеров файла делает файл бесполезным. Нам будет показана ошибка всякий раз, когда мы пытаемся открыть файл с искаженным заголовком.
- Скачать редактор hex : чтобы испортить файл, нам нужен редактор hex. hexedit — популярный инструмент, используемый для того же самого. Вы можете установить его используя:
Вы можете открыть файл, набрав
Вы увидите такой вывод:
Чтобы сохранить и выйти, нажмите Ctrl X, а затем Y.
На рисунке выше мы видим, что первые 2 байта были изменены на 00 00, а справа мы видим, что текст изменился с .PNG на ..NG
Как восстановить файл с поврежденным магическим номером?
Давайте воспользуемся примером, показанным на картинке выше, где я повредил первые два байта PNG. Если вы попытаетесь открыть PNG сейчас, он выдаст ошибку «Не удалось загрузить файл», а не «PNG». Это доказательство того, что система смотрит на магическое число перед открытием файла. Зная, что магические числа PNG начинаются с 89 50, мы можем вернуть байты к их первоначальному значению.
Давайте посмотрим на другой пример, используя изображение в формате JPEG.
Давайте сначала посмотрим, как выглядит рабочий гекс в формате jpeg:
оригинальные магические числа байты
JPEG с поврежденными магическими байтами будет выглядеть так:
Мы замечаем, что магические байты в этом
И, следовательно, файл jpg не откроется, если вы попытаетесь открыть его. Мы получаем эту ошибку:
Файл JPG обычно имеет магическое число «FFD8 DDE0», «FFD8 FFDB» или «FFD8 FFE1».
С этим знанием все, что нам нужно сделать, это попробовать эти комбинации в качестве заголовков файла. Для этого требуется тот же процесс, что и при повреждении файла.
- Открыть гекседит
- Измените первые несколько байтов, наведя курсор и введя нужные значения
- Сохранить (Ctrl X) и выйти
- Попробуйте открыть файл. Повторите шаги со следующим возможным магическим числом, если файл не открывается
При изменении магических байтов на FFD8 FFE0 изображение открывается правильно.
Эта статья предоставлена Дипаком Шриватсавом . Если вы как GeeksforGeeks и хотели бы внести свой вклад, вы также можете написать статью с помощью contribute.geeksforgeeks.org или по почте статьи contribute@geeksforgeeks.org. Смотрите свою статью, появляющуюся на главной странице GeeksforGeeks, и помогите другим вундеркиндам.
Пожалуйста, пишите комментарии, если вы обнаружите что-то неправильное или вы хотите поделиться дополнительной информацией по обсуждаемой выше теме.
Источник
Working with Magic numbers in Linux
This article aims at giving an introduction to magic numbers and file headers, how to extract a file based on magic numbers, and how to corrupt and repair a file based on magic numbers in the Linux environment.
Magic Numbers
Magic numbers are the first few bytes of a file that are unique to a particular file type. These unique bits are referred to as magic numbers, also sometimes referred to as a file signature.
These bytes can be used by the system to “differentiate between and recognize different files” without a file extension.
Locating Magic Numbers in File Signatures
Most files have the signatures in the bytes at the beginning of the file, but some file systems may even have the file signature at offsets other than the beginning. For example, file system ext2/ext3 has bytes 0x53 and 0xEF at the 1080th and 1081st position.
- Some files, however, do not have magic numbers, such as plain text files, but can be identified by checking the character set (ASCII in the case of text files).
This can be done by using the command: - Magic numbers/File signatures are typically not visible to the user but can be seen by using a hex editor or by using the ‘xxd’ command as mentioned below. These bytes are essential for a file to be opened.
- Changing/corrupting these bytes will render the file useless as most tools will not access these files due to potential damaging.
- The file command in Linux reader reads the magic numbers of a file and displays the file type based on the magic number.
- For example, let us take the example of a PNG file. We can view the hex of a file by typing the following command in a Linux terminal (kali Linux used in this article). This command creates a hexdump of the file we pass to it.
This produces the following output:-
In this image, we see that the first set of bytes of the file are
These numbers help the system identify the type of file being used. Some files that are not written with their extension, are identified with the help of these magic numbers.
An example of a Zip file, Similarly, use the above mentioned command on a zip file.
In the above image, we can see that the file starts with:
Appending One File to another and identifying the division with Magic numbers
We can use python to perform this operation. Essentially, we will read the bytes of two files, and write them one by one to another empty file. In this article, we will combine a PNG with a Zip file.
Using this python code, we obtain a file output.png. On running the command:
on this file, we notice that it begins with the same 8950 4e47 0d0a 1a0a hex. However, if we run the command
which will search for the magic numbers (PK is the ASCII equivalent of 50 4b) of a zip file amongst the hex,
we will get the following output:
In this picture, we can see that the zip file magic numbers are present in the hex of the png, meaning that we have successfully appended the hex of the zip file to that of the png. The next step is to separate this zip file from the png.
There is a simple utility, ‘binwalk’ that helps us perform this task easily by typing:
How to use the magic numbers and offsets to extract the zip file from the output :
- Find the beginning offset of the file you wish to extract: In this example, we wish to extract the zip file from the PNG. So we first look for the ZIP header. As shown in the previous picture, we carry out the command ‘xxd output.png | grep “PK” ‘. In this picture, we see the offset on the left column. For the zip file, the offset will be 00001c90.
- Calculate the number of bits from the offset where your file header starts: We must now calculate the number of bits from the offset at which the zip file starts. We can manually count this and observe it to be 00001c95 (each hex value corresponds to 1 bit)
- Convert this hex value to decimal: This may be done by opening a python IDLE (type ‘python’ in a Linux terminal. We must now convert this value to a decimal. In a python IDLE, we must simply add 0x to the beginning of the value found in the previous step.
- Use the following command:
In the above-mentioned command, ‘if’ stands for the input file, ‘skip’ denotes the number of bits that must be skipped to reach the beginning of the file that we wish to extract, ‘bs’ refers to the number of bytes that must be read at a time, and ‘of’ refers to the output file name.
Refer to the picture below to see the usage of steps 3 and 4:
How to corrupt a file by changing its Magic Number?
Changing the magic numbers of a file renders the file useless. We will be showed an error whenever we try to open a file that has a distorted header.
- Download hex editor: To corrupt a file, we require a hex editor. hexedit is a popular tool used for the same. You can install it using:
You can open the file by typing
You will see an output like this:
To save and exit, press ctrl X and then Y.
In the above picture, we see that the first 2 bytes have been changed to 00 00, and on the right, we can see that the text has changed from .PNG to ..NG
How to repair a file that has a corrupted magic number?
Let us use the example shown in the picture above where I have corrupted the first two bytes of the PNG. If you try to open the PNG now, it will give you an error saying “Could not load file”, not a “PNG”. This is proof that a system looks at the magic number before opening a file. Knowing that the PNG magic numbers start with 89 50, we can change the bytes back to their original value.
Let us look at another example, using a jpeg image.
Lets first see what a working jpeg hex looks like:
the original magic number bytes are
A JPEG with corrupted magic bytes would look like this:
We notice that the magic bytes in this are
And hence the jpg file will not open if you try to open it. We get this error:
A JPG file typically has magic number “FFD8 DDE0”, “FFD8 FFDB” or “FFD8 FFE1”.
With this knowledge, all we would have to do is try these combinations as headers for the file. Doing this requires the same process as file corruption.
- Open hexedit
- Change the first few bytes by hovering with cursor and entering the required values
- Save (Ctrl X) and exit
- Try opening the file. Repeat steps with next possible magic number if the file does not open
On changing the magic bytes to FFD8 FFE0, the picture opens properly.
This article is contributed by Deepak Srivatsav. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Источник