LIEF - Library to Instrument Executable Formats

0.17.6 · active · verified Sat Apr 11

LIEF (Library to Instrument Executable Formats) is a robust, cross-platform library designed to parse, modify, and abstract various executable formats, including ELF, PE, Mach-O, OAT, DEX, VDEX, and ART. It provides a comprehensive, user-friendly API for C++, Python, Rust, and C, enabling detailed analysis, manipulation, and reconstruction of binaries without relying on disassemblers. Currently at version 0.17.6, LIEF maintains an active development and release cadence, with frequent updates addressing new features and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `lief.parse()` to automatically detect and parse an executable file (ELF on Linux/macOS, PE on Windows). It then prints basic information about the binary, showcasing format-specific attributes like ELF machine type or number of PE imported libraries. Replace the default paths with your target binaries.

import lief
import sys
import os

def analyze_binary(filepath):
    if not os.path.exists(filepath):
        print(f"Error: File not found at {filepath}")
        return

    binary = lief.parse(filepath)

    if binary is None:
        print(f"Could not parse {filepath} as an executable.")
        return

    print(f"\nAnalyzing: {filepath}")
    print(f"  Format: {binary.format}")
    print(f"  Entrypoint: {hex(binary.entrypoint)}")
    print(f"  Number of sections: {len(binary.sections)}")

    # Example: Accessing ELF-specific features
    if binary.format == lief.Binary.FORMATS.ELF:
        elf_binary = binary.as_elf()
        if elf_binary and elf_binary.header:
            print(f"  ELF Machine Type: {elf_binary.header.machine_type}")
            if elf_binary.dynamic_entries:
                print(f"  Number of dynamic entries: {len(elf_binary.dynamic_entries)}")

    # Example: Accessing PE-specific features
    elif binary.format == lief.Binary.FORMATS.PE:
        pe_binary = binary.as_pe()
        if pe_binary and pe_binary.header:
            print(f"  PE Machine Type: {pe_binary.header.machine_type}")
            if pe_binary.imports:
                print(f"  Number of imported libraries: {len(pe_binary.imports)}")

# Try to analyze common executables based on OS
if sys.platform.startswith('linux'):
    analyze_binary('/bin/ls')
elif sys.platform == 'win32':
    analyze_binary('C:\\Windows\\System32\\notepad.exe')
elif sys.platform == 'darwin':
    analyze_binary('/bin/ls') # macOS also uses ELF/MachO, /bin/ls is a good example
else:
    print("Unsupported OS for quickstart example.")

view raw JSON →