TExcelTAD
Home › Reverse Engineering & Binary Analysis › Imports as Behaviour Hints

Imports as Behaviour Hints

A program can only affect the world through the operating system: to open a file, start a process, connect to a host or change the registry it must call an API, and on Windows and dynamically linked Linux most of those calls are listed by name in the import table. Reading imports is therefore reading a list of capabilities: not proof of what the program does, but a strong hint of what it can do. Triage tools turn import lists into capability reports (Mandiant's capa does it with hundreds of rules over imports, strings and code). This lesson builds a tiny version and shows both its power and how programs hide imports.

Definitions

  • Capability hint: an imported function (or group of functions) that implies an ability: connect (outbound network), execve/CreateProcessW (start programs), ptrace (debug or inspect other processes), RegSetValueExW (write the registry), CryptEncrypt/BCryptEncrypt (encrypt data).
  • Combinations matter more than single functions: VirtualAllocEx + WriteProcessMemory + CreateRemoteThread together is the textbook pattern of process injection (writing code into another process and running it). Each alone has legitimate uses (debuggers, game overlays, accessibility tools).
  • Hidden imports: functions resolved at run time with dlopen/dlsym (Linux) or LoadLibrary/GetProcAddress (Windows) don't appear in the import table; their names may still appear as strings, or be replaced by hashes of the names.
  • Imphash: a hash of the normalised import list (as computed by the pefile library), used to cluster PE samples built from the same source.

A capability report from an import list

The example maps imports to capabilities with a small rule table and reports two synthetic Windows import lists: a backup tool and an unknown sample. The API names are real Windows functions; the programs are invented.

python · try it yourself
import hashlib

RULES = {  # capability: (functions, how many must be present)
    "reads and writes files":         ({"CreateFileW", "ReadFile", "WriteFile"}, 2),
    "enumerates files":               ({"FindFirstFileW", "FindNextFileW"}, 2),
    "network client (Winsock)":       ({"WSAStartup", "socket", "connect", "send", "recv"}, 3),
    "HTTP client (WinINet)":          ({"InternetOpenW", "InternetOpenUrlW", "InternetReadFile"}, 2),
    "starts processes":               ({"CreateProcessW", "ShellExecuteW", "WinExec"}, 1),
    "writes the registry":            ({"RegCreateKeyExW", "RegSetValueExW"}, 1),
    "encrypts data (CNG)":            ({"BCryptOpenAlgorithmProvider", "BCryptEncrypt", "BCryptGenRandom"}, 2),
    "process injection pattern":      ({"OpenProcess", "VirtualAllocEx", "WriteProcessMemory", "CreateRemoteThread"}, 3),
    "resolves APIs at run time":      ({"LoadLibraryW", "LoadLibraryA", "GetProcAddress"}, 2),
    "checks for a debugger":          ({"IsDebuggerPresent", "CheckRemoteDebuggerPresent"}, 1),
}

def report(name, imports):
    funcs = {f for fs in imports.values() for f in fs}
    print(f"== {name}: {len(imports)} DLLs, {len(funcs)} functions")
    for cap, (needles, need) in RULES.items():
        hit = sorted(funcs & needles)
        if len(hit) >= need:
            print(f"  {cap:<32} {', '.join(hit)}")
    # imphash in the style of pefile: dll (lower, no extension) + '.' + function (lower), comma-joined
    norm = ",".join(f"{dll.lower().rsplit('.', 1)[0]}.{f.lower()}" for dll, fs in imports.items() for f in fs)
    print(f"  imphash-style MD5: {hashlib.md5(norm.encode()).hexdigest()}")

backup_tool = {
    "KERNEL32.dll": ["CreateFileW", "ReadFile", "WriteFile", "CloseHandle", "FindFirstFileW", "FindNextFileW",
                     "GetLastError", "ExitProcess"],
    "BCRYPT.dll":   ["BCryptOpenAlgorithmProvider", "BCryptEncrypt", "BCryptGenRandom"],
    "ADVAPI32.dll": ["RegCreateKeyExW", "RegSetValueExW"],
}
unknown_sample = {
    "KERNEL32.dll": ["OpenProcess", "VirtualAllocEx", "WriteProcessMemory", "CreateRemoteThread",
                     "LoadLibraryA", "GetProcAddress", "IsDebuggerPresent", "Sleep"],
    "WININET.dll":  ["InternetOpenW", "InternetOpenUrlW", "InternetReadFile"],
}
report("backup_tool.exe (synthetic)", backup_tool)
report("unknown_sample.exe (synthetic)", unknown_sample)
== backup_tool.exe (synthetic): 3 DLLs, 13 functions
  reads and writes files           CreateFileW, ReadFile, WriteFile
  enumerates files                 FindFirstFileW, FindNextFileW
  writes the registry              RegCreateKeyExW, RegSetValueExW
  encrypts data (CNG)              BCryptEncrypt, BCryptGenRandom, BCryptOpenAlgorithmProvider
  imphash-style MD5: e55e16ba42a0255fa2530262fcd4dfef
== unknown_sample.exe (synthetic): 2 DLLs, 11 functions
  HTTP client (WinINet)            InternetOpenUrlW, InternetOpenW, InternetReadFile
  process injection pattern        CreateRemoteThread, OpenProcess, VirtualAllocEx, WriteProcessMemory
  resolves APIs at run time        GetProcAddress, LoadLibraryA
  checks for a debugger            IsDebuggerPresent
  imphash-style MD5: 5037c47138fbcb2be421a29583c94c39

The backup tool "reads and writes files, enumerates files, encrypts data, writes the registry": also the capability list of ransomware. Imports alone can't tell an encrypting backup tool from ransomware; the context (a signed vendor, a configuration UI, files written to a backup folder rather than overwritten in place) does. The unknown sample is far more suspicious: injection, run-time API resolution, a debugger check and an HTTP client together form the profile of a downloader that injects into another process. That is a hypothesis for the dynamic analysis to test in a lab, not a verdict.

Hiding imports, and finding them anyway

On Linux the same idea applies to nm -D. The session builds three toys (none of them is run): one that uses sockets directly, one that starts a program, and one that looks up connect by name at run time with dlsym, so the import table no longer shows it.

bash · try it yourself
cat > net.c <<'SRC'
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int main(void) {
    int s = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(9000) };
    connect(s, (struct sockaddr *)&a, sizeof a);
    close(s);
    return 0;
}
SRC
cat > spawn.c <<'SRC'
#include <unistd.h>
int main(void) {
    char *argv[] = { "/bin/true", 0 };
    if (fork() == 0) execv(argv[0], argv);
    return 0;
}
SRC
cat > hidden.c <<'SRC'
#include <dlfcn.h>
#include <sys/socket.h>
typedef int (*connect_fn)(int, const struct sockaddr *, socklen_t);
int main(void) {
    connect_fn f = (connect_fn)dlsym(RTLD_DEFAULT, "connect");   /* resolved at run time */
    return f ? 0 : 1;
}
SRC
for p in net spawn hidden; do gcc -O2 $p.c -o $p; done
caps() {
  imports=$(nm -D "$1" | awk '$1=="U"{print $2}' | sed 's/@.*//' | grep -v '^__' | sort | tr '\n' ' ')
  printf '%-7s imports: %s\n' "$1" "$imports"
  for f in socket connect execv fork dlsym ptrace; do
    case " $imports " in *" $f "*) printf '        -> %s\n' "$f";; esac
  done
}
for p in net spawn hidden; do caps $p; done
echo "== strings in hidden that look like function names"
strings -n 6 hidden | grep -xE 'connect|socket|execv'
net     imports: close connect socket
        -> socket
        -> connect
spawn   imports: execv fork
        -> execv
        -> fork
hidden  imports: dlsym
        -> dlsym
== strings in hidden that look like function names
connect

net and spawn declare their capabilities openly. hidden imports only dlsym, but the name connect is still in its strings, which is why analysts read imports and strings together. A more careful author would hash or encrypt the name; then the clue is the dlsym/GetProcAddress call itself and the loop that computes hashes before it.

How analysts detect hidden or misleading imports

  • Run-time resolvers (dlopen/dlsym, LoadLibrary/GetProcAddress, or a manual walk of the PEB's module list and export tables in Windows malware) in a small import table: look for the names as strings, then for hashing loops (constants such as the ROR-13 rotation or FNV primes near string comparisons).
  • Syscalls without imports: a syscall instruction in application code on Linux, or direct syscall stubs on Windows (bypassing ntdll), means the program talks to the kernel directly; it doesn't appear in any import list. EDRs watch for these.
  • Compare static and dynamic views: ltrace/strace on Linux, API Monitor or a debugger on Windows show what was actually called (Tracing).

How defenders and developers use this

  • Detection rules over imports and strings (YARA's pe module: pe.imports("kernel32.dll", "CreateRemoteThread"); capa rules) flag samples for analysts; tuned with known-good software to keep false positives down.
  • Allow-listing by publisher signature and hash is stronger than any capability heuristic for deciding what may run.
  • For developers: import what you use normally and don't imitate malware patterns (runtime-resolving APIs to "protect" a program) without a good reason; security products will flag it.

Pitfalls

  • Imports are capabilities, not behaviour: a library may import functions the program never reaches.
  • Statically linked code has no imports for the parts it carries itself (static Linux binaries; Go programs on Linux, which use their own syscall layer).
  • Common runtime imports (__libc_start_main, the C runtime's GetModuleHandleW, IsDebuggerPresent in MSVC's CRT start-up code) appear in benign programs too; know the compiler's baseline.
  • imphash is fragile: reordering or adding one import changes it. The example's version is simplified: pefile drops only the .dll, .ocx and .sys extensions and turns ordinal imports from a few DLLs (such as ws2_32 and oleaut32) into names before hashing.

Practice

1. Which three Windows API functions together form the classic remote process-injection pattern?

VirtualAllocEx (allocate memory in the target), WriteProcessMemory (copy code into it) and CreateRemoteThread (run it), usually after OpenProcess.

2. Why can't imports distinguish a backup tool that encrypts files from ransomware?

Both need file enumeration, reading, writing and encryption. Context decides: signatures, configuration, where output goes, whether originals are overwritten, ransom notes, network behaviour.

3. hidden imports only dlsym. What would you change in the analysis if no suspicious strings were found either?

Look at the code around the dlsym call: the name argument is built at run time (decoded, or matched by hash). Run it in a lab under ltrace -e dlsym to see the name it passes.

Test yourself

What does an import list tell you about a program?

  1. Exactly what it does
  2. What it is able to do through the OS: capability hints to confirm by analysis
  3. Who wrote it
  4. Nothing useful

How did the hidden toy avoid importing connect?

  1. It used a system call
  2. It looked the function up by name at run time with dlsym
  3. It was stripped
  4. It was statically linked

Which finding most strongly suggests run-time API resolution in a Windows sample?

  1. Imports of ReadFile and WriteFile
  2. A tiny import table with LoadLibrary and GetProcAddress, plus API names in strings or a hashing loop
  3. A digital signature
  4. A .rdata section

What is imphash used for?

  1. Encrypting imports
  2. Clustering PE samples built from the same code by hashing their normalised import list
  3. Verifying signatures
  4. Unpacking