MAGIC(4)

πŸ“¦
version 5.47 Β· 4 versions
, in alpine 3.24

πŸ’… MAGIC(4) β€” file command's magic pattern file πŸ’…

okay so bestie, this is the Kernel Interfaces Manual page for MAGIC(4), and it literally documents the format of magic files as used by file(1) version 5.47. file(1) figures out what type a file is usingβ€”among other testsβ€”a test for whether the file contains certain β€œmagic patterns”. iconic behavior πŸ’–. The database of those β€œmagic patterns” usually lives in a binary file at /usr/share/misc/magic.mgc or in a directory of source text magic pattern fragment files at /usr/share/misc/magic. That database specifies what patterns are to be tested for, what message or MIME type to print if a particular pattern is found, and additional information to extract from the file. no cap.

πŸŽ€ NAME πŸŽ€

magic β€” the file command's magic pattern file πŸŽ€

✨ DESCRIPTION ✨

So here's the format of the source fragment files used to build this database: every line of a fragment file specifies a test to be performed. A test compares the data starting at a particular offset in the file with a byte value, a string or a numeric value. If the test succeeds, a message is printed. The line consists of the following fields:

offset β€” a number specifying the offset (in bytes) into the file of the data which is to be tested. This offset can be a negative number if it is:

  • the first direct offset of the magic entry (at continuation level 0), in which case it is interpreted as an offset from the end end of the file going backwards. This works only when a file descriptor to the file is available and it is a regular file.
  • a continuation offset relative to the end of the last up-level field (&).

If the offset starts with the symbol +, then all offsets are interpreted as from the beginning of the file (the default).

type β€” the type of the data to be tested. The possible values are:

  • byte β€” a one-byte value.
  • short β€” a two-byte value in this machine's native byte order.
  • long β€” a four-byte value in this machine's native byte order.
  • quad β€” an eight-byte value in this machine's native byte order.
  • float β€” a 32-bit single precision IEEE floating point number in this machine's native byte order.
  • double β€” a 64-bit double precision IEEE floating point number in this machine's native byte order.
  • string β€” a string of bytes. The string type specification can be optionally followed by a /<width> option and optionally followed by a set of flags [bCcftTtWw]*. Slash characters can be used to separate options for readability. The width limits the number of characters to be copied. Zero means all characters. The following flags are supported:
    • b β€” force binary file test.
    • C β€” use upper case insensitive matching: upper case characters in the magic match both lower and upper case characters in the target, whereas lower case characters in the magic only match upper case characters in the target. (not valid for regex)
    • c β€” use lower case insensitive matching: lower case characters in the magic match both lower and upper case characters in the target, whereas upper case characters in the magic only match upper case characters in the target. (not valid for regex) To do a complete case insensitive match, specify both β€œc” and β€œC”.
    • f β€” require that the matched string is a full word, not a partial word match.
    • s β€” don't include the match length in the offset computation. (only valid for search and regex)
    • T β€” trim the string, i.e. leading and trailing whitespace is deleted before the string is printed.
    • t β€” force text file test.
    • W β€” compact whitespace in the target, which must contain at least one whitespace character. (not valid for regex) If the magic has n consecutive blanks, the target needs at least n consecutive blanks to match.
    • w β€” treat every blank in the magic as an optional blank. (not valid for regex)
  • pstring β€” a Pascal-style string where the first byte/short/int is interpreted as the unsigned length. The length defaults to byte and can be specified as a modifier. The following modifiers are supported:
    • B β€” a byte length (default).
    • H β€” a 2 byte big endian length.
    • h β€” a 2 byte little endian length.
    • L β€” a 4 byte big endian length.
    • l β€” a 4 byte little endian length.
    • J β€” the length includes itself in its count.

The string is not NUL terminated. β€œJ” is used rather than the more valuable β€œI” because this type of length is a feature of the JPEG format.

  • date β€” a four-byte value interpreted as a UNIX date.
  • qdate β€” an eight-byte value interpreted as a UNIX date.
  • ldate β€” a four-byte value interpreted as a UNIX-style date, but interpreted as local time rather than UTC.
  • qldate β€” an eight-byte value interpreted as a UNIX-style date, but interpreted as local time rather than UTC.
  • qwdate β€” an eight-byte value interpreted as a Windows-style date.
  • msdosdate β€” a two-byte value interpreted as FAT/DOS-style date.
  • msdostime β€” a two-byte value interpreted as FAT/DOS-style time.
  • beid3 β€” a 32-bit ID3 length in big-endian byte order.
  • beshort β€” a two-byte value in big-endian byte order.
  • belong β€” a four-byte value in big-endian byte order.
  • bequad β€” an eight-byte value in big-endian byte order.
  • befloat β€” a 32-bit single precision IEEE floating point number in big-endian byte order.
  • bedouble β€” a 64-bit double precision IEEE floating point number in big-endian byte order.
  • bedate β€” a four-byte value in big-endian byte order, interpreted as a Unix date.
  • beqdate β€” an eight-byte value in big-endian byte order, interpreted as a Unix date.
  • beldate β€” a four-byte value in big-endian byte order, interpreted as a UNIX-style date, but interpreted as local time rather than UTC.
  • beqldate β€” an eight-byte value in big-endian byte order, interpreted as a UNIX-style date, but interpreted as local time rather than UTC.
  • beqwdate β€” an eight-byte value in big-endian byte order, interpreted as a Windows-style date.
  • bemsdosdate β€” a two-byte value in big-endian byte order, interpreted as FAT/DOS-style date.
  • bemsdostime β€” a two-byte value in big-endian byte order, interpreted as FAT/DOS-style time.
  • bestring16 β€” a two-byte unicode (UCS16) string in big-endian byte order.
  • leid3 β€” a 32-bit ID3 length in little-endian byte order.
  • leshort β€” a two-byte value in little-endian byte order.
  • lelong β€” a four-byte value in little-endian byte order.
  • lequad β€” an eight-byte value in little-endian byte order.
  • lefloat β€” a 32-bit single precision IEEE floating point number in little-endian byte order.
  • ledouble β€” a 64-bit double precision IEEE floating point number in little-endian byte order.
  • ledate β€” a four-byte value in little-endian byte order, interpreted as a UNIX date.
  • leqdate β€” an eight-byte value in little-endian byte order, interpreted as a UNIX date.
  • leldate β€” a four-byte value in little-endian byte order, interpreted as a UNIX-style date, but interpreted as local time rather than UTC.
  • leqldate β€” an eight-byte value in little-endian byte order, interpreted as a UNIX-style date, but interpreted as local time rather than UTC.
  • leqwdate β€” an eight-byte value in little-endian byte order, interpreted as a Windows-style date.
  • lemsdosdate β€” a two-byte value in little-endian byte order, interpreted as FAT/DOS-style date.
  • lemsdostime β€” a two-byte value in little-endian byte order, interpreted as FAT/DOS-style time.
  • lestring16 β€” a two-byte unicode (UCS16) string in little-endian byte order.
  • melong β€” a four-byte value in middle-endian (PDP-11) byte order.
  • medate β€” a four-byte value in middle-endian (PDP-11) byte order, interpreted as a UNIX date.
  • meldate β€” a four-byte value in middle-endian (PDP-11) byte order, interpreted as a UNIX-style date, but interpreted as local time rather than UTC.
  • indirect β€” starting at the given offset, consult the magic database again. The offset of the indirect magic is by default absolute in the file, but one can specify /r to indicate that the offset is relative from the beginning of the entry. πŸ¦‹

Okay bestie, picking up right where we left offβ€”here’s the rest of the type lore, and it’s lowkey iconic πŸ’–

  • name β€” Define a β€œnamed” magic instance that other use magic entries can call, like a subroutine call. For named instances, direct magic offsets are relative to the offset of the previous matched entry, but indirect offsets are relative to the beginning of the file as usual. Named magic entries return true if there was a match while evaluating the entry, or if there was already a previous existing match. iykyk
  • use β€” Recursively call the named magic starting from the current offset. If the name of the referenced magic begins with a ^, then the endianness is switched: say the magic mentioned leshort, it gets treated as beshort and vice versa. This is super useful for not duplicating rules for different endianness. slay
  • regex β€” A regular expression match in extended POSIX regular expression syntax (like egrep). The type spec can optionally be followed by /[c][s][l]. The c flag makes the match case-insensitive, the s flag updates the offset to the start offset of the match (instead of the end), and the l modifier changes the length limit to mean number of lines instead of a byte count. Lines are delimited by the platform’s native line delimiter. When you specify a line count, an implicit byte count is also computed assuming each line is 80 characters long. If neither a byte nor a line count is specified, the search is limited automatically to 8KiB. Note: ^ and $ match the beginning and end of individual lines, not the beginning and end of the file.
Heads up bestie: regexes can take exponential time to process and their performance is hard to predict, so their use is discouraged. In production environments, check their performance carefully. Also limit the size of the string to search by specifying /<length>, so you don’t get performance issues scanning long files.
  • search β€” A literal string search starting at the given offset. You can use the same modifier flags as for string patterns. The search expression must include the range in the form /number, i.e. the number of positions where the match will be attempted, starting from the start offset. Great for searching larger binary expressions with variable offsets, using \ escapes for special characters. The order of the modifier and the number doesn’t matter. flexible much?
  • default β€” Meant to be used with the test x (which is always true) and it has no type. It matches when no other test at that continuation level has matched before. You can clear the matched tests for a continuation level with the clear test.
  • clear β€” This test is always true and clears the match flag for that continuation level. Intended to be used with the default test.
  • der β€” Parse the file as a DER Certificate file. The test field is used as a DER type to match. The DER types are: eoc, bool, int, bit_str, octet_str, null, obj_id, obj_desc, ext, real, enum, embed, utf8_str, rel_oid, time, res2, seq, set, num_str, prt_str, t61_str, vid_str, ia5_str, utc_time, gen_time, gr_str, vis_str, gen_str, univ_str, char_str, bmp_str, date, tod, datetime, duration, oid-iri, rel-oid-iri. These types can be followed by an optional numeric size, which indicates the field width in bytes. certificate realness πŸ”₯
  • guid β€” A Globally Unique Identifier, parsed and printed as XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX. Its format is a string.
  • offset β€” A quad value indicating the current offset of the file. Can be used to determine the size of the file or the magic buffer. For example, these magic entries:
-0      offset  x       this file is %lld bytes
-0      offset  <=100   must be more than 100 \
    bytes and is only %lld
  • octal β€” A string representing an octal number.

For compatibility with the Single Unix Standard, the type specifiers are all like β€œsame energy” and here’s the tea: dC and d1 are equivalent to byte; uC and u1 are equivalent to ubyte; dS and d2 are equivalent to short; uS and u2 are equivalent to ushort; dI, dL, and d4 are equivalent to long; uI, uL, and u4 are equivalent to ulong; d8 is equivalent to quad; u8 is equivalent to uquad; and s is equivalent to string. Also, dQ is equivalent to quad and uQ is equivalent to uquad. no cap

Vibe check: each top-level magic pattern (levels are explained below) gets classified as text or binary based on the types used. regex and search types are classified as text tests, unless non-printable characters are used in the pattern. All other tests are classified as binary. A top-level pattern counts as a text test when all its patterns are text patterns; otherwise it’s a binary pattern. When matching a file, binary patterns are tried first. If no match is found and the file looks like text, then its encoding is determined and the text patterns are tried.

Numeric types can optionally be followed by an operand and a numeric value, meaning the value gets modified according to that operand and numeric value before any comparisons happen. Supported operands: &, |, ↑, +, -, *, /, %. Prepending a u to the type means ordered comparisons should be unsigned.

πŸ§ͺ test

The value to compare with the value from the file. If the type is numeric, this value is specified in C form; if it’s a string, it’s specified as a C string with the usual escapes allowed (e.g. \n for newline).

Numeric values may be preceded by a character indicating the operation: = means the file value must equal the specified value; < means the file value must be less than the specified value; > means the file value must be greater than the specified value; & means the file value must have set all the bits that are set in the specified value; ^ means the file value must have clear any of the bits that are set in the specified value; ~ means the value specified after is negated before tested; and x means any value will match. If the character is omitted, it’s assumed to be =. Operators &, ^, and ~ don’t work with floats and doubles. The operator ! specifies that the line matches if the test does not succeed.

Numeric values are specified in C form; e.g. 13 is decimal, 013 is octal, and 0x13 is hexadecimal.

Numeric operations are not performed on date typesβ€”instead the numeric value is interpreted as an offset.

For string values, the string from the file must match the specified string. Operators =, <, and > (but not &) can be applied to strings. The length used for matching is that of the string argument in the magic file. This means a line can match any non-empty string (usually used to then print the string) with >\0 (because all non-empty strings are greater than the empty string).

Dates are treated as numerical values in the respective internal representation.

The special test x always evaluates to true.

πŸ’¬ message

The message to be printed if the comparison succeeds. If the string contains a printf(3) format specification, the value from the file (with any specified masking performed) is printed using the message as the format string. If the string begins with \b, the message printed is the remainder of the string with no whitespace added before itβ€”multiple matches are normally separated by a single space. clean ✨

An APPLE 4+4 character APPLE creator and type can be specified as:

!:apple CREATYPE

A slash-separated list of commonly found filename extensions can be specified as:

!:ext   ext[/ext...]

i.e. the literal string !:ext followed by a slash-separated list of commonly found extensions. For example, for JPEG images:

!:ext jpeg/jpg/jpe/jfif

A MIME type is given on a separate line, which must be the next non-blank or comment line after the magic line that identifies the file type. Format:

!:mime  MIMETYPE

i.e. the literal string !:mime followed by the MIME type.

An optional strength can be supplied on a separate line that refers to the current magic description. Format:

!:strength OP VALUE

The operand OP can be +, -, *, or /, and VALUE is a constant between 0 and 255. This constant is applied using the specified operand to the currently computed default magic strength. periodt πŸ’…

okay so some file formats are extra πŸ’… β€” they've got bonus info that needs to be printed alongside the file type, or they need extra tests before you can even figure out what they truly are. These additional tests get introduced by one or more > characters sitting in front of the offset.

The number of > on a line tells you the level of the test; a line with no > at the beginning counts as level 0. And the tests are arranged in a tree-like hierarchy, which is lowkey iconic: if the test on a line at level n succeeds, then all the following tests at level n+1 get performed, and the messages get printed if the tests succeed, and this keeps rolling until a line with level n (or less) appears. For more complex files you can use empty messages to get just the "if/then" effect, like this:

0      string    MZ
>0x18  uleshort  <0x40   MS-DOS executable
>0x18  uleshort  >0x3f   extended PC executable (e.g., MS Windows)

Offsets do not need to be constant, bestie β€” they can also be read straight out of the file you're examining 🫢. If the first character following the last > is a (, then the string after the parenthesis is interpreted as an indirect offset. Meaning: the number after the parenthesis is used as an offset in the file, the value at that offset gets read, and that value is used again as an offset in the file. So it's offset-ception.

Indirect offsets are of the form:

(x [[.,][bBcCeEfFgGhHiIlmosSqQ]][+-][ y ])

The value of x is used as an offset in the file. A byte, id3 length, short or long is read at that offset depending on the [bBcCeEfFgGhHiIlLmsSqQ] type specifier. That value is treated as signed if , is specified, or unsigned if . is specified. The capitalized types interpret the number as a big endian value, whereas the small letter versions interpret it as a little endian value; the m type interprets the number as a middle endian (PDP-11) value. Then the value of y gets added to that number, and the result is used as an offset in the file. The default type if you don't specify one is long. Here are the recognized types, slay:

  • bcBC β€” Byte/Char, endian: N/A, size: 1
  • efg β€” Double, Little endian, size: 8
  • EFG β€” Double, Big endian, size: 8
  • hs β€” Half/Short, Little endian, size: 2
  • HS β€” Half/Short, Big endian, size: 2
  • i β€” ID3, Little endian, size: 4
  • I β€” ID3, Big endian, size: 4
  • l β€” Long, Little endian, size: 4
  • L β€” Long, Big endian, size: 4
  • m β€” Middle, Middle endian, size: 4
  • o β€” Octal, Textual, size: Variable
  • q β€” Quad, Little endian, size: 8
  • Q β€” Quad, Big endian, size: 8

That way variable length structures can be examined πŸ’–:

# MS Windows executables are also valid MS-DOS executables
0           string   MZ
>0x18       uleshort <0x40  MZ executable (MS-DOS)
# skip the whole block below if it is not an extended executable
>0x18       uleshort >0x3f
>>(0x3c.l)  string   PE\0\0 PE executable (MS-Windows)
>>(0x3c.l)  string   LX\0\0 LX executable (OS/2)

ngl this strategy of examining has a drawback though: you must make sure you eventually print something, or users may get empty output 😭 β€” like when there's neither PE\0\0 nor LE\0\0 in the example above.

If this indirect offset can't be used directly, simple calculations are possible: appending [+-*/%&|^]number inside parentheses lets you modify the value read from the file before it's used as an offset:

# MS Windows executables are also valid MS-DOS executables
0           string   MZ
# sometimes, the value at 0x18 is less that 0x40 but there's still an
# extended executable, simply appended to the file
>0x18       uleshort <0x40
>>(4.s*512) leshort  0x014c  COFF executable (MS-DOS, DJGPP)
>>(4.s*512) leshort  !0x014c MZ executable (MS-DOS)

Sometimes you don't know the exact offset because it depends on the length or position (when indirection was used before) of preceding fields. In that case you can specify an offset relative to the end of the last up-level field using & as a prefix to the offset:

0           string   MZ
>0x18       uleshort >0x3f
>>(0x3c.l)  string   PE\0\0    PE executable (MS-Windows)
# immediately following the PE signature is the CPU type
>>>&0       leshort  0x14c     for Intel 80386
>>>&0       leshort  0x8664    for x86-64
>>>&0       leshort  0x184     for DEC Alpha

Indirect and relative offsets can be combined, and honestly that's giving main character energy ✨:

0             string   MZ
>0x18         uleshort <0x40
>>(4.s*512)   leshort  !0x014c MZ executable (MS-DOS)
# if it's not COFF, go back 512 bytes and add the offset taken
# from byte 2/3, which is yet another way of finding the start
# of the extended executable
>>>&(2.s-514) string   LE      LE executable (MS Windows VxD driver)

Or the other way around πŸ¦‹:

0                 string   MZ
>0x18             uleshort >0x3f
>>(0x3c.l)        string   LE\0\0  LE executable (MS-Windows)
# at offset 0x80 (-4, since relative offsets start at the end
# of the up-level match) inside the LE header, we find the absolute
# offset to the code area, where we look for a specific signature
>>>(&0x7c.l+0x26) string   UPX     \b, UPX compressed

Or even both at once, because why not πŸ’€:

0                string   MZ
>0x18            uleshort >0x3f
>>(0x3c.l)       string   LE\0\0 LE executable (MS-Windows)
# at offset 0x58 inside the LE header, we find the relative offset
# to a data area where we look for a specific signature
>>>&(&0x54.l-3)  string   UNACE  \b, ACE self-extracting archive

Okay and if you have to deal with offset/length pairs in your file, even the second value in a parenthesized expression can be taken from the file itself, using another set of parentheses πŸ”₯. Just note: this additional indirect offset is always relative to the start of the main indirect offset.

0                 string       MZ
>0x18             uleshort     >0x3f
>>(0x3c.l)        string       PE\0\0 PE executable (MS-Windows)
# search for the PE section called ".idata"...
>>>&0xf4          search/0x140 .idata
# ...and go to the end of it, calculated from start+length;
# these are located 14 and 10 bytes after the section name
>>>>(&0xe.l+(-4)) string       PK\3\4 \b, ZIP self-extracting archive

And if you've got a list of known values at one particular continuation level, but you also want a switch-like default case πŸŽ€:

# clear that continuation level match
>18     clear   x
>18     lelong  1       one
>18     lelong  2       two
>18     default x
# print default match
>>18    lelong  x       unmatched 0x%x

✨ SEE ALSO ✨

  • file(1) β€” the command that reads this file. your fave, the one that actually runs all this magic πŸ’œ

πŸ’€ BUGS πŸ’€

Okay so here's the tea, and it's a whole thing. The formats long, belong, lelong, melong, short, beshort, and leshort do not depend on the length of the C data types short and long on the platform β€” even though the Single Unix Specification implies that they do πŸ™ˆ.

But like… as OS X Mountain Lion has passed the Single Unix Specification validation suite, and supplies a version of file(1) in which they do not depend on the sizes of the C data types β€” and that version is built for a 64-bit environment in which long is 8 bytes rather than 4 bytes β€” presumably the validation suite does not test whether, for example, long refers to an item with the same size as the C data type long. Make of that what you will 😭.

There should probably be type names int8, uint8, int16, uint16, int32, uint32, int64, and uint64, plus specified-byte-order variants of them, to make it clearer that those types have specified widths. periodt. πŸ”₯


okay that's the whole page bestie, you made it πŸŽ‰ this one came from the Debian crowd, dated November 24, 2025, and it's MAGIC(4) β€” go forth and identify files with confidence πŸ’…βœ¨πŸ¦‹

πŸ“¦ where this page comes from