An introduction to ClamAV signatures
ClamAV is an open-source engine that quietly scans a large part of the world's e-mail gateways, file servers, upload forms, and CI pipelines. Most people only ever feed it the official daily.cvd, but the engine also loads plain-text signature files from its database directory, which makes it a cheap way to turn your own threat intelligence into blocking at the perimeter. The catch is that the signature formats are very different from YARA rules. This post covers the formats an incident responder needs and the habits that keep a signature specific, fast, and safe to deploy.
The signature zoo
ClamAV decides what a signature is by the extension of the file it lives in. The ones you will actually write:
.hdb/.hsb: file hashes (MD5 in.hdb; SHA-1 or SHA-256 in.hsb)..mdb/.msb: hashes of individual PE sections..imp: PE import hashes (imphash)..ndb: "extended" body signatures - one hex pattern, a target type, and an offset..ldb: logical signatures - several hex patterns combined with a logical expression, plus file-level constraints. This is the format you should write most of the time..cdb: container metadata (file names, sizes, and encryption inside archives)..yar/.yara: a subset of YARA..ign2,.fp,.sfp: names of signatures to ignore and hashes of files to allow.
There are more (.ftm for file type magic, .pdb/.wdb for phishing URLs, .idb for icons, .crb for certificates, .cbc for bytecode), but the list above covers what an incident responder needs. All of them are text files; drop them in the database directory (/var/lib/clamav on most Linux systems) or pass them with clamscan -d, and the engine loads them next to the official databases.
Anatomy of a logical signature
The running example is Ymir, the ransomware our team analyzed in 2024. The detection uses two unique strings, five weaker ones, and a file size limit - it fires on either unique string, or on any three of the weaker ones:
Win.Ransomware.Ymir-1;Engine:81-255,Target:1,FileSize:0-5242880;(0|1)|((2|3|4|5|6)>2,3);3643356f793264567236::fwa;443a32303234303833313135343833332d303627303027;494e434944454e545f5245504f52542e706466::wa;706f7765727368656c6c202d772068202d632053746172742d536c656570202d5365636f6e647320353b2052656d6f76652d4974656d202d466f726365202d50617468;73657475702d71746f782d7838365f36342d72656c656173652e657865;783634646267::f;436861436861
Hard to read? Yes. One signature is one line, and every string is hex. Split by its semicolons, the structure is:
Win.Ransomware.Ymir-1 ; name
Engine:81-255,Target:1,FileSize:0-5242880 ; target description block
(0|1)|((2|3|4|5|6)>2,3) ; logical expression over subsignatures 0..6
3643356f793264567236::fwa ; 0: "6C5oy2dVr6" (fullword, wide + ascii)
443a3230323430383331... ; 1: "D:20240831154833-06'00'"
494e434944454e545f5245504f52542e706466::wa ; 2: "INCIDENT_REPORT.pdf" (wide + ascii)
706f7765727368656c6c202d7720... ; 3: "powershell -w h -c Start-Sleep ..."
73657475702d71746f782d783836... ; 4: "setup-qtox-x86_64-release.exe"
783634646267::f ; 5: "x64dbg" (fullword)
436861436861 ; 6: "ChaCha"
Reading the pieces:
- Target description block.
Target:1restricts the signature to PE files.FileSize:0-5242880is the 5 MB limit, in bytes (the range is inclusive).Engine:81-255is the range of engine functionality levels (FLEVEL) allowed to load the signature. When present,Enginemust come first in the block. - Logical expression. Subsignatures are referred to by index.
(0|1)is "either unique string".(2|3|4|5|6)>2,3is "any three of the weaker ones", the block must produce more than two matches and at least three different subsignatures must match. The second number matters,(2|3|4|5|6)>2alone is satisfied byChaChaappearing three times. - Modifiers.
::fwaafter a pattern means full word (f), in UTF-16 (w) or ASCII (a);::imakes it case-insensitive.
One thing a logical signature cannot do is query the PE import table. To require an import such as memmove from msvcrt.dll, add the two names as subsignatures (6d73766372742e646c6c::i and 6d656d6d6f7665::f) and require them in the expression. It is less precise than parsing the import directory, but it is cheap and it keeps the detection in one file.
Naming: ClamAV has an official naming convention - Platform.Category.Name-SignatureID-Revision, where the platform is Win, Unix, Osx, Andr, Doc, Pdf, Html, Multios, etc., and the category is Ransomware, Trojan, Downloader, Exploit, Phishing, and so on. For your own signatures, Platform.Category.Name-Revision is enough. The name is all the context an analyst gets in a clamd log line, so make it say what was detected. ClamAV appends .UNOFFICIAL to every signature that does not come from the official databases, so this one is reported as Win.Ransomware.Ymir-1.UNOFFICIAL.
Metadata: there is no meta section. Keep the author, description, date, reference, and sample hashes in comments above the signature in your source repository. A header like this is fine:
# Win.Ransomware.Ymir-1 | Cristian Souza | 2026-11-17
# ref: https://securelist.com/new-ymir-ransomware-found-in-colombia/114493/
# hash: cb88edd192d49db12f444f764c3bdc287703666167a4ca8d533d51f86ba428d8
# strings: 6C5oy2dVr6 | D:20240831154833-06'00' | INCIDENT_REPORT.pdf | ...
Hashes: the easy way, and its limits
The fastest signature to write is a hash. sigtool prints it in the right format:
sigtool --sha256 ymir.exe >> custom.hsb
# cb88edd192d49db12f444f764c3bdc287703666167a4ca8d533d51f86ba428d8:2733568:ymir.exe
# edit the name afterwards:
cb88edd192d49db12f444f764c3bdc287703666167a4ca8d533d51f86ba428d8:2733568:Win.Ransomware.Ymir-2
# if you only have the hash, not the size:
cb88edd192d49db12f444f764c3bdc287703666167a4ca8d533d51f86ba428d8:*:Win.Ransomware.Ymir-2:73
The fields are hash:size:name. The size can be *, but then the line must end with a minimum FLEVEL of 73 (:73), or the engine rejects it. Prefer a pinned size when you have it, ClamAV then only has to check the hash on files of that exact length. A hash catches exactly one file, which is fine for blocking a known dropper on a mail gateway and useless for a family. Two hash variants cover more ground:
- Section hashes (
.mdb/.msb):sigtool --mdb ymir.exeprints oneSection{N}: size:hashline per PE section; the signature issize:hash:name(size first, the reverse of.hsb). A hash of the code section survives repacking of the resources, changed icons, and re-signing, which is how a lot of commodity malware is "rebuilt". Never hash the.rsrcsection or anything the linker fills identically across unrelated programs. - Import hashes (
.imp):sigtool --imp ymir.exeprintsImphash: hash:size; the signature ishash:size:name.
Picking strings
Good strings are the ones tied to the malware and nothing else, such as PDB paths, mutex and pipe names, C2 formats, custom error messages, dropped file names, registry keys, and, one level deeper, crypto constants and decryption loops. Avoid runtime library strings, common imports as the only evidence, and fragments of compressed data. Two things are specific to ClamAV:
- Everything is hex.
sigtool --hex-dumpconverts text:echo -n "6C5oy2dVr6" | sigtool --hex-dump. For UTF-16LE strings, add the::wmodifier to the ASCII hex instead of writing the zero bytes yourself. - Normalization. By default ClamAV normalizes HTML, JavaScript, and plain-text files before matching, everything is lowercased, whitespace is collapsed, HTML comments are removed, and JavaScript is run through its own normalizer. For HTML, the raw file is not scanned at all. A signature written against the raw file will silently miss for
Target:3(normalized HTML) andTarget:7(normalized ASCII). Dump the normalized form withsigtool --html-normalise=page.htmlorclamscan --leave-temps --tempdir=/tmp/normand write your strings against that.
The target types you will use: 0 any file, 1 PE, 2 OLE2, 3 normalized HTML, 4 mail, 5 graphics, 6 ELF, 7 normalized ASCII, 9 Mach-O, 10 PDF, 11 Flash, 12 Java class. Picking the right one is the single biggest performance win available, since a Target:1 signature is never even considered for a PDF.
Hex patterns and wildcards
Hex patterns support these wildcards:
?? any byte
a? / ?a high / low nibble fixed
{4} exactly 4 bytes
{1-4} 1 to 4 bytes
{-16} {16-} up to 16 / 16 or more bytes
* any number of bytes
(41|42) one of the alternatives
!(00|ff) anything but these bytes
(B) (L) (W) word boundary / line boundary / non-alphanumeric char
Take a string-decryption loop:
8A 04 0E mov al, [esi+ecx] ; load encrypted byte
34 5C xor al, 5Ch ; family-specific key
2C 11 sub al, 11h ; family-specific constant
88 04 0F mov [edi+ecx], al ; store decrypted byte
41 inc ecx
3B CA cmp ecx, edx
72 F1 jb short loop_start
A balanced pattern keeps the opcodes and the two family-specific constants, and leaves the registers, the increment, and the jump distance open. Written that way as an .ndb line anchored to the code section, the first attempt does not load:
# rejected: "Can't find a static subpattern of length 2"
Win.Ransomware.Example-1:1:S0+0,65536:8a04??345c2c118804??{1-4}3b??72??
# accepted: the piece after the gap now has two fixed bytes
Win.Ransomware.Example-1:1:S0+0,65536:8a04??345c2c118804??{1-4}3bca72
This is the rule that catches most people. * and {n-m} split a pattern into pieces, and every piece must contain at least two adjacent fixed bytes. The tail 3b??72?? has none, so I pinned the operands of the cmp and dropped the trailing wildcard. For the same reason a pattern cannot start with * or a range (a leading ?? is fine). A fixed-length {n} with n < 128 does not split anything, since the engine expands it to ?? bytes.
Each split also costs something, the engine matches the pieces separately and correlates them afterwards, so a signature with three * in it is really four signatures plus bookkeeping. Prefer {n-m} with a tight range, and when you need a long gap, use two subsignatures of a logical signature instead.
Offsets and anchors
The third field of an .ndb line (and the optional prefix of a logical subsignature) says where the pattern may occur. * means anywhere; everything else narrows the search and makes the match more specific:
* anywhere in the file
0 exactly at offset 0
EOF-64 64 bytes before the end
EP+0 at the entry point (PE, ELF, Mach-O)
EP+0,32 between EP and EP+32 (",maxshift" turns an offset into a window)
S0+0,65536 in the first 64 KB of section 0
SE1 anywhere in section 1
SL+0 at the start of the last section
VI each version-info key/value (PE only)
Anchors let a signature use the structure of the file: EP+0 matches code at the entry point, and SL+0 catches a payload appended as the last section without caring about its name. They also reduce false positives: an Sx or SEx anchor ties a string to the section where it belongs, such as the ransom note that Ymir embeds in .data.
The VI anchor is worth knowing on its own. It walks every key/value pair of the PE version information and checks whether the pair starts with the pattern, so you can match, for example, a CompanyName that begins with "Microsoft". The pattern is the UTF-16 key followed by the beginning of the value, and only ?? and (aa|bb) are allowed in it. You rarely build it by hand: clamscan --debug prints a ready-to-paste VI: line for every pair it finds.
Writing the logical expression
The expression language is small: &, |, parentheses, and comparisons on match counts. The count operators are where most mistakes happen:
0&1&2 all three subsignatures
(0|1)&2 0 or 1, plus 2
0=0&1 1 present and 0 absent (negation is "=0")
0>3 subsignature 0 matched more than 3 times
(1|2|3)>2,3 more than 2 matches, from at least 3 different subsignatures
(1|2|3)=2,2 exactly 2 matches, from 2 different subsignatures
A few things to keep in mind:
- Without the second number,
(1|2|3)>2counts occurrences, not distinct strings. To express "N of" you need>N-1,N. - Negation (
=0) is a legitimate way to write false-positive filters - put the string that only the clean software has as a subsignature and require it to be absent. - Up to 64 subsignatures per signature, but a signature that needs 40 of them is probably three signatures.
- Every subsignature is searched regardless of the expression, so there is no short-circuit benefit to ordering them. Order only matters for PCRE, which can refer only to the subsignatures before it.
Beyond plain patterns, three special subsignature types pull their weight:
PCRE. Trigger/regex/flags runs a regular expression only after the trigger (a logical expression over the preceding subsignatures) is satisfied. This is the right way to use a regex in ClamAV, a cheap static pattern decides whether the regex runs at all.
Win.Trojan.GatePanel-1;Engine:81-255,Target:0;1;2f676174652e7068703f69643d;0/\/gate\.php\?id=[0-9a-f]{16}/
Here subsignature 0 is the literal /gate.php?id=, and the PCRE is triggered by it. Note the expression is just 1 (the regex is what decides). The trigger only switches the regex on; it does not tell it where to look. Without an offset, the regex searches the whole file. With one (EP+0:0/.../), it is tried only at that offset, unless you add the r flag (search from the offset onward) or give a window (0,256:0/.../: the match may start anywhere in it; add the e flag to require the whole match inside it). The g flag (find all matches) makes a regex slower.
Byte compare. 0(>>4#il4#>1000) reads four raw bytes (i), little-endian (l), four bytes after the start of subsignature 0, and requires the value to be greater than 1000. Use it to validate a size or version field next to a marker instead of hard-coding the bytes. Use h or d instead of i only when the number is stored as hex or decimal text. It needs Engine:100-255 (ClamAV 0.101).
Image fuzzy hash. fuzzy_img#<hash> matches an image by a pHash-like fingerprint, which is how you detect a brand logo reused in phishing kits. Combine it with Container:CL_TYPE_HTML or CL_TYPE_MAIL so it only fires where that logo does not belong. The hash must match exactly. In practice it usually survives re-encoding and resizing, but not cropping or editing. Get the hash with sigtool --fuzzy-img logo.png. It needs Engine:150-255 (ClamAV 0.105).
Containers and context
ClamAV unpacks archives, mail, OLE2, and PDF streams recursively and scans every inner object, and the target description block can see that nesting. Container:CL_TYPE_ZIP means "the scanned file is directly inside a ZIP", and Intermediates:CL_TYPE_MAIL>CL_TYPE_ZIP means "inside a ZIP that is attached to an e-mail". That is a precision tool, a .lnk file is normal on a disk and suspicious inside an ISO attached to a message.
Container metadata signatures (.cdb) go one step further and match on what an archive says about its contents without extracting them, which also works for encrypted archives:
# VirusName:ContainerType:ContainerSize:FileNameREGEX:FileSizeInContainer:FileSizeReal:IsEncrypted:FilePos:Res1:Res2
Email.Malware.EncryptedZipWithExe-1:CL_TYPE_ZIP:*:(?i).*\.(exe|scr|js|vbs|lnk|iso)$:*:*:1:*:*:*
This one flags any encrypted ZIP whose listing contains an executable extension, a pattern that is almost always a malicious attachment and that no content signature could ever match, since the content is encrypted. Note that .cdb uses a real regex for the file name (case-sensitive unless it starts with (?i)), and that it fires on the archive itself, not on the inner file.
Testing your signatures
Test every signature against more positives than the samples you wrote it from, a goodware set, and a large corpus, and keep it all under version control. The commands:
# load only your signatures, print which one matched
clamscan -d custom.ldb -r --infected --no-summary /cases/samples/
# everything the engine knows about a file (types, sections, VI lines, normalized temps)
clamscan -d custom.ldb --debug --leave-temps --tempdir=/tmp/clam ymir.exe
# convert strings, hashes, sections, imphash
echo -n "6C5oy2dVr6" | sigtool --hex-dump
sigtool --sha256 ymir.exe
sigtool --mdb ymir.exe
sigtool --imp ymir.exe
# decode a signature back to something readable
sigtool --decode-sigs < custom.ldb
# inspect the official databases
sigtool --info daily.cvd
sigtool --unpack daily.cvd # into the current directory
sigtool --find-sigs Ymir # search the database directory by name
Two ClamAV-specific checks belong in every test run:
- Load it on the oldest engine you support. A signature whose
Engine:range (ormin_flevelfield in.ndband.hsblines) excludes the running engine is silently skipped at load time, which is what you want. A signature that uses a newer feature without declaring it is a parse error, and one parse error fails the whole database load, official databases included,clamscanexits without scanning, andclamdrefuses to start. On a reload,clamd(0.103 and later) keeps the previous database and logs the failure, so your new signatures never go live and the only trace is in its log. - Check the whole database against your goodware set, not just the new line.
clamscanstops at the first match per file by default; a new signature can be shadowed by an existing one during testing and only start firing (wrongly) once the other is removed.--allmatchshows every signature that hits.
When a false positive shows up in production you do not have to touch the signature immediately, an .ign2 file with the signature name (without the .UNOFFICIAL suffix) silences it, and an .fp/.sfp line (MD5 or SHA-256 of the clean file, same format as .hdb/.hsb) allows one file while you fix the root cause.
YARA rules in ClamAV
ClamAV loads .yar files directly, which is tempting if you already maintain a YARA rule set. It works for simple rules, with real limitations: no modules at all (no pe, no math, no hash), no global rules, no external variables, no compiled rules, at most 64 strings per rule, and the same two-fixed-bytes rule for hex strings (a rule that breaks it is skipped with a warning). Every condition is driven by string matches, so a rule whose condition is only filesize < 200KB never runs; you need a string in it. And for HTML the rules only see ClamAV's normalized view, so a rule tuned against raw pages may miss.
My recommendation is: use .yar in ClamAV for string-only rules you already have and trust, and write anything that needs structure (entry point, sections, version info, containers, byte compare) as a native .ldb, which is the format the engine was built around.
Deploying
Custom signatures live next to the official ones. Keep them in a file with a clear name (cristianzsh-custom.ldb rather than custom.ldb) so nobody wonders where a detection came from, reload clamd (clamdscan --reload or kill -USR2), and confirm in the log that the reload succeeded with the expected signature count.
For a fleet, serve the file over HTTPS and point freshclam at it with DatabaseCustomURL. By default freshclam test-loads a downloaded database before installing it, so a broken file does not reach clamd.
Run the verification in your deployment step, the engine loads plain-text databases without checking a signature.
A quick checklist
- Narrowest
Targettype and aFileSizerange in every logical signature; Engine:(ormin_flevel) set to the lowest level the signature actually needs, and tested on that engine;- Unique artefacts and groups of weaker strings, combined with
|and>N-1,N; ::fon short strings,::waonly when the encoding varies,::ionly when the case does;- Two adjacent fixed bytes in every piece of a pattern, and
{n-m}instead of*; - Offsets and anchors (
EP,Sx,SL,VI) wherever the position carries information; - Regexes only as triggered PCRE subsignatures, behind a literal trigger;
- Strings written against the normalized form for HTML and text targets;
- Name in
Platform.Category.Name-Revisionform; author, reference, and sample hashes in the source repository; - Tested with
--allmatchagainst goodware and against samples not used to write it; - Loaded on the oldest supported engine without errors.
Conclusion
Although ClamAV signatures are hard to learn, the payoff is a detection that runs on the mail gateway and the file server for free, on the infrastructure you already have. I also advise the usage of AI tools to help you structure your rules easily. Happy hunting!