Overloaded function.
parse(filename: str, config: lief._lief.PE.ParserConfig = <lief._lief.PE.ParserConfig object at 0x796719c8d770>) -> Optional[lief._lief.PE.Binary]
Parse the PE binary from the given file path and return a Binary
object
parse(raw: list[int], config: lief._lief.PE.ParserConfig = <lief._lief.PE.ParserConfig object at 0x796719c8d790>) -> Optional[lief._lief.PE.Binary]
Parse the PE binary from the given list of bytes and return a lief.PE.Binary
object
parse(obj: Union[io.IOBase | os.PathLike], config: lief._lief.PE.ParserConfig = <lief._lief.PE.ParserConfig object at 0x796719c8d7b0>) -> Optional[lief._lief.PE.Binary]
Parse the PE binary from the given parameter and return a lief.PE.Binary
object
Bases: object
This class is used to tweak the PE Parser (Parser
)
Parse PE Exports Directory
Parse PE Import Directory
Parse PE relocations
Parse PE resources tree
Parse PE Authenticode signature
Bases: Binary
Class which represents a PE binary which is the main interface to manage and modify a PE executable.
This object can be instantiated through lief.parse()
or lief.PE.parse()
while the constructor of this object can be used to craft a binary from scratch (see: 02 - Create a PE from scratch)
Add a function to the given Import
name
Add an Import
by name
Add a Relocation
to the binary
Add a Section
to the binary.
Compute the authentihash according to the ALGORITHMS
given in the first parameter
Authentihash MD5 value
Authentihash SHA1 value
Authentihash SHA-256 value
Authentihash SHA-512 value
Return the CodeViewPDB
if present
Re-compute the value of checksum
. If both values do not match, it could mean that the binary has been modified after the compilation.
This value is computed by LIEF for the current binary object.
Return an iterator over the DataDirectory
Return the DataDirectory
object from the given TYPES
type
Return the Debug
Return an iterator over the DelayImport
Return the DosHeader
DOS stub content as a list
of bytes
Function
found in the Exception directory
All Function
found in the binary
Return the DelayImport
from the given name or None if not not found
Return the Export
object
Return the Import
from the given name or None if not not found
Return the Section
object from the given name or None if not not found
True
if the current binary has LoadConfiguration
True
if the binary imports the given library name
True
if the current binary has delay imports (DelayImport
)
True
if the current binary uses Exceptions
True
if the binary imports the given library name
True
if the current binary uses Relocation
True
if the current binary has a Resources
object
True
if the current binary has a RichHeader
object
Return the Header
Return an iterator over the Import
libraries
True
if the binary was compiled with a reproducible build directive (Debug
)
Bases: object
Iterator over lief._lief.PE.Signature
Bases: object
Iterator over lief._lief.PE.DataDirectory
Bases: object
Iterator over lief._lief.PE.Debug
Bases: object
Iterator over lief._lief.PE.DelayImport
Bases: object
Iterator over lief._lief.PE.Import
Bases: object
Iterator over lief._lief.PE.Relocation
Bases: object
Iterator over lief._lief.PE.Section
Bases: object
Iterator over lief._lief.PE.Symbol
Return the LoadConfiguration
object or None if not present
Header that follows the header
. It is named optional from the COFF specifications but it is mandatory in a PE file.
Return the overlay content as a list
of bytes
Return the original overlay offset
Try to predict the RVA of the given function name in the given import library name
Return an iterator over the Relocation
Remove the Section
given in first parameter
Remove all imported libraries
Return the ResourceNode
tree or None if not not present
Return the ResourcesManager
to manage resources
RichHeader
object (if present)
Convert a relative virtual address to an offset
The conversion is performed by looking for the section that encompasses the provided RVA.
Return the Section
which encompasses the provided offset. It returns None if a section can’t be found.
Return the Section
which encompasses the provided relative virtual address. If a section can’t be found, it returns None.
Return binary’s an iterator over the PE’s Section
Return an iterator over the Signature
objects
Size of all the PE headers
Return binary’s Symbol
TLS
object (if present)
Convert an absolute virtual address into an offset
See: rva_to_offset()
Overloaded function.
verify_signature(self, checks: lief._lief.PE.Signature.VERIFICATION_CHECKS = lief.PE.VERIFICATION_CHECKS.DEFAULT) -> lief._lief.PE.Signature.VERIFICATION_FLAGS
Verify the binary against the embedded signature(s) (if any)
First off, it checks that the embedded signatures are correct (c.f.
lief.PE.Signature.check()
) and then it checks that the authentihash matcheslief.PE.ContentInfo.digest
One can tweak the verification process with the
lief.PE.Signature.VERIFICATION_CHECKS
flagsSee also
verify_signature(self, signature: lief._lief.PE.Signature, checks: lief._lief.PE.Signature.VERIFICATION_CHECKS = lief.PE.VERIFICATION_CHECKS.DEFAULT) -> lief._lief.PE.Signature.VERIFICATION_FLAGS
Verify the binary with the Signature object provided in the first parameter It can be used to verify a detached signature:
detached = lief.PE.Signature.parse("sig.pkcs7") binary.verify_signature(detached)
Return the binary’s virtual size.
This value should match sizeof_image
Build the binary and write the result to the given output
file
Bases: Object
Class which represents the DosHeader, the first structure presents at the beginning of a PE file.
Most of the attributes of this structures are not relevant, except addressof_new_exeheader
Duplicate the current instance of this object
Bases: Object
Class that represents the PE header (which follows the lief.PE.DosHeader
)
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Add the given CHARACTERISTICS
to the header
The CHARACTERISTICS
that indicate the attributes of the file.
Return the CHARACTERISTICS
as a list
Duplicate the current instance of this object
True
if the header has the given CHARACTERISTICS
The target machine architecture (MACHINE_TYPES
)
Number of sections in the binary
The number of entries in the symbol table. This data can be used to locate the string table which immediately follows the symbol table.
This value should be zero for an image because COFF debugging information is deprecated.
The file offset of the COFF symbol table, or zero if no COFF symbol table is present.
This value should be zero for an image because COFF debugging information is deprecated.
Remove the given CHARACTERISTICS
from the header
Signature (or magic byte) of the header. It must be: PE\0\0
Size of the OptionalHeader
AND the data directories which follows this header.
This value is equivalent to: sizeof(pe_optional_header) + NB_DATA_DIR * sizeof(data_directory)
This size should be either:
0xE0 (224) for a PE32 (32 bits)
0xF0 (240) for a PE32+ (64 bits)
The low 32 bits of the number of seconds since 00:00 January 1, 1970 that indicates when the file was created.
Bases: Object
Class which represents the PE OptionalHeader structure.
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Add the given DLL_CHARACTERISTICS
The address of the entry point relative to the image base when the executable file is loaded into memory. For program images, this is the starting address. For device drivers, this is the address of the initialization function.
An entry point is optional for DLLs. When no entry point is present, this field must be zero.
Address relative to the imagebase where the binary’s code starts
Address relative to the imagebase where the binary’s data starts.
Warning
This value is not present for PE64
files
The image file checksum. The algorithm for computing the checksum is incorporated into IMAGHELP.DLL
. The following are checked for validation at load time all drivers, any DLL loaded at boot time, and any DLL that is loaded into a critical Windows process.
Duplicate the current instance of this object
Some characteristics (DLL_CHARACTERISTICS
) of the underlying binary like the support of the PIE.
The prefix dll
comes from the official PE specifications but these characteristics are also used for executables
dll_characteristics
as a list of DLL_CHARACTERISTICS
The alignment factor (in bytes) that is used to align the raw data of sections in the image file. The value should be a power of 2 between 512 and 64K, inclusive. The default value is 512. If the section_alignment
is less than the architecture’s page size, then file_alignment
must match section_alignment
.
True
if the given DLL_CHARACTERISTICS
is in the dll_characteristics
The preferred base address when mapping the binary in memory
According to the PE specifications, this value is reserved and should be 0.
Magic value (PE_TYPE
) that identifies a PE32
from a PE64
The major version number of the image.
The linker major version number
The major version number of the required operating system.
The major version number of the subsystem.
The minor version number of the image.
The linker minor version number
The minor version number of the required operating system.
The minor version number of the subsystem
The number of DataDirectory
that follow this header
Remove the given DLL_CHARACTERISTICS
The alignment (in bytes) of sections when they are loaded into memory. It must be greater than or equal to file_alignment
and the default is the page size for the architecture.
The size of the code .text
section or the sum of all the sections that contain code (ie. Section
with the flag CNT_CODE
)
The combined size of an MS-DOS stub, PE header, and section headers rounded up to a multiple of file_alignment
.
The size of the local heap space to commit.
The size of the local heap space to reserve.
Only sizeof_heap_commit
is available one page at a time until the reserve size is reached.
The size (in bytes) of the image, including all headers, as the image is loaded in memory. It must be a multiple of section_alignment
and should match virtual_size
.
The size of the initialized data which are usually located in the .data
section. If the initialized data are split across multiple sections, it is the sum of the sections.
The sections associated with the initialized data are usually identified with the flag CNT_INITIALIZED_DATA
The size of the stack to commit.
The size of the stack to reserve.
Only sizeof_stack_commit
is committed, the rest is made available one page at a time until the reserve size is reached.
The size of the uninitialized data which are usually located in the .bss
section. If the uninitialized data are split across multiple sections, it is the sum of the sections.
The sections associated with the uninitialized data are usually identified with the flag CNT_UNINITIALIZED_DATA
Target subsystem (SUBSYSTEM
) like Driver, XBox, Windows GUI, ..
Reserved, must be zero.
Bases: Object
Class that represents a PE data directory entry
Bases: object
The underlying integer value
Duplicate the current instance of this object
Relative virtual address of the content associated with the current data directory
Section
associated with the current data directory or None if not linked
Size in bytes of the content associated with the current data directory
Type (TYPES
) of the current data directory
Bases: Section
Class which represents a PE section.
It extends the base class lief.Section
Overloaded function.
__init__(self, content: list[int], name: str = '', characteristics: int = 0) -> None
Constructor from content
, name
and characteristics
__init__(self, name: str) -> None
Constructor from a name
Bases: object
The underlying integer value
The CHARACTERISTICS
that describe the characteristics of the section
characteristics
as a list
Duplicate the current instance of this object
True
if the section has the given CHARACTERISTICS
The number of line-number entries for the section. This value should be zero for an image because COFF debugging information is deprecated.
The number of relocation entries for the section.
See: pointerto_relocation
Section padding content as bytes
The file pointer to the beginning of line-number entries for the section. This is set to zero if there are no COFF line numbers. This value should be zero for an image because COFF debugging information is deprecated and modern debug information relies on the PDB files.
The offset of the section data in the PE file. Alias of offset
The file pointer to the beginning of the COFF relocation entries for the section. This is set to zero for executable images or if there are no relocations.
For modern PE binaries, this value is usually set to 0 as the relocations are managed by Relocation
.
Alias of size
(size of the data in the section)
The total size of the section when loaded into memory.
If this value is greater than sizeof_raw_data
, the section is zero-padded.
Bases: Object
Class that represents a PE import
Overloaded function.
__init__(self) -> None
Default constructor
__init__(self, library_name: str) -> None
Constructor from a library name
Overloaded function.
add_entry(self, entry: lief._lief.PE.ImportEntry) -> lief._lief.PE.ImportEntry
Add an ImportEntry
(function) to the current import
add_entry(self, function_name: str) -> lief._lief.PE.ImportEntry
Add an ImportEntry
(function) to the current import
Return the DataDirectory
associated with this import.
It should be the one at index lief.PE.DataDirectory.TYPES.IMPORT_TABLE
. It can return None if the Import directory can’t be resolved.
Iterator over the ImportEntry
(functions)
The index of the first forwarder reference
Return the ImportEntry
with the given name or None if not found
Return the relative virtual address of the given function within the Import Address Table
Return the DataDirectory
associated with the IAT
table.
It should be the one at index lief.PE.DataDirectory.TYPES.IAT
. It can return None if the IAT directory can’t be resolved.
The RVA of the import address table (IAT
). The content of this table is identical to the content of the Import Lookup Table (ILT
) until the image is bound.
Warning
This address could change when re-building the binary
The RVA of the import lookup table. This table contains the name
or the ordinal
for all the imports.
Bases: object
Iterator over lief._lief.PE.ImportEntry
Library name (e.g. kernel32.dll
)
The stamp that is set to zero until the image is bound.
After the image is bound, this field is set to the time/data stamp of the DLL
Bases: Symbol
Class that represents an entry (i.e. an import) in the import table (Import
).
It extends the lief.Symbol
generic class that provides the lief.Symbol.name
and lief.Symbol.value
Overloaded function.
__init__(self, import_name: str) -> None
Constructor from a name
__init__(self, data: int, name: str = '') -> None
Constructor from a data
and an optionally name
__init__(self, data: int, type: lief._lief.PE.PE_TYPE, name: str = '') -> None
Constructor from a data
, a type
and an optional name
__init__(self, name: str, type: lief._lief.PE.PE_TYPE) -> None
Constructor from a name
, and a type
Duplicate the current instance of this object
Raw value
Demangled representation of the symbol or an empty string if it can’t be demangled.
Index into the lief.PE.Export.entries
that is used to speed-up the symbol resolution
Original address of the entry in the Import Address Table
Value of the current entry in the Import Address Table. It should match the lookup table value.
True
if it is an import by ordinal
Import name if not ordinal
Ordinal value (if any). See: is_ordinal
Bases: Object
Class that represents a PE delay import
Constructor from a library name
Reserved and should be zero according to the PE specifications
RVA of the bound delay-load import address table or 0 if the table does not exist.
Duplicate the current instance of this object
Iterator over the DelayImportEntry
(functions)
The RVA of the module handle (in the .data
section) It is used for storage by the routine that is supplied to manage delay-loading.
RVA of the delay-load import address table.
Bases: object
Iterator over lief._lief.PE.DelayImportEntry
Library name (e.g. kernel32.dll
)
RVA of the delay-load import names table. The content of this table has the layout as the Import lookup table
The timestamp of the DLL to which this image has been bound.
RVA of the unload delay-load import address table or 0 if the table does not exist.
According to the PE specifications, this table is an exact copy of the delay import address table that can be used to to restore the original IAT the case of unloading.
Bases: Symbol
Class that represents an entry (i.e. a delay import) in the delay import table (DelayImport
).
It extends the lief.Symbol
generic class that provides the lief.Symbol.name
and lief.Symbol.value
The meaning of lief.Symbol.value
for this PE object is the address (as an RVA) in the IAT where the resolution should take place
Duplicate the current instance of this object
Raw value
Demangled representation of the symbol or an empty string if it can’t be demangled.
Index into the lief.PE.Export.entries
that is used to speed-up the symbol resolution
Value of the current entry in the delay-loaded import address table. See: iat
True
if it is an import by ordinal
Delay import name if not ordinal
Ordinal value (if any). See: is_ordinal
Bases: Object
Class which represents the PE Thread Local Storage. This PE structure is also used to implement binary/library constructors.
Default constructor
Pointer to an array of TLS callback functions.
The array is null-terminated, so if there is no callback, this field points to 4 bytes set to zero.
See: callbacks
The location to receive the TLS index assigned by the loader. This location should be located in a writable section like .data
.
Tuple (start address, end address)
of the TLS template. The template is a block of data that is used to initialize TLS data. The system copies all of this data each time a thread is created, so it must not be corrupted.
Note
These addresses are not RVA. It is addresses for which there should be a base relocation in the .reloc
section.
List of the callback associated with the current TLS.
These functions are called before any other functions.
The four bits [23:20] describe alignment info. Possible values are those defined as IMAGE_SCN_ALIGN_*
, which are also used to describe alignment of section in object files. The other 28 bits are reserved for future use.
Duplicate the current instance of this object
The initial content used to initialize TLS data.
DataDirectory
associated with the TLS object (or None if not linked)
True
if there is a DataDirectory
associated with the TLS object
Section
associated with the TLS object (or None if not linked)
Size in bytes of the zeros to be padded after the data specified by data_template
.
Bases: Symbol
True
if symbols are located in a section
Bases: Object
Class which represents the Base Relocation Block Usually, we find this structure in the .reloc
section
Add a new RelocationEntry
The total number of bytes in the base relocation block. block_size = sizeof(BaseRelocationBlock) + nb_of_relocs * sizeof(uint16_t = RelocationEntry)
Duplicate the current instance of this object
Iterator over the RelocationEntry
Bases: object
Iterator over lief._lief.PE.RelocationEntry
The RVA for which the offset of the relocation entries (RelocationEntry) is added
Bases: Relocation
Class which represents an entry of the PE relocation table.
It extends the lief.Relocation
object to provide an uniform API across the file formats.
Bases: object
The underlying integer value
Raw data of the relocation:
Offset - relative to virtual_address
- where the relocation occurs
Type of the relocation
Bases: Object
Class which represents a PE Export
Duplicate the current instance of this object
Iterator over the ExportEntry
According to the PE specifications this value is reserved and should be set to 0
Bases: object
Iterator over lief._lief.PE.ExportEntry
The major version number (can be user-defined)
The minor version number (can be user-defined)
The name of the library exported (e.g. KERNEL32.dll
)
The starting number for the exports. Usually this value is set to 1
The time and date that the export data was created
Bases: Symbol
Class which represents a PE Export entry (cf. lief.PE.Export
)
Demangled representation of the symbol or an empty string if it can’t be demangled.
Bases: Object
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Return an iterator over x509
certificates
Check the integrity of the signature and return a lief.PE.Signature.VERIFICATION_FLAGS
By default, it performs the following verifications:
It must contain only one signer info (signers
)
lief.PE.Signature.digest_algorithm
must match:
The x509 certificate specified by lief.PE.SignerInfo.serial_number
and lief.PE.SignerInfo.issuer
must exist within lief.PE.Signature.certificates
Given the x509 certificate, compare lief.PE.SignerInfo.encrypted_digest
against either:
hash of authenticated attributes (authenticated_attributes
) if present
hash of ContentInfo
If they are Authenticated attributes, check that a PKCS9_MESSAGE_DIGEST (lief.PE.PKCS9MessageDigest
) attribute exists and that its value matches hash of ContentInfo
Check the validity of the PKCS #9 counter signature if present
If the signature doesn’t embed a signing-time in the counter signature, check the certificate validity. (See lief.PE.Signature.VERIFICATION_CHECKS.LIFETIME_SIGNING
and lief.pe.Signature.VERIFICATION_CHECKS.SKIP_CERT_TIME
)
See: lief.PE.Signature.VERIFICATION_CHECKS
to tweak the behavior
Return the ContentInfo
Return the algorithm (ALGORITHMS
) used to sign the content of ContentInfo
Find the x509
certificate according to its serial number
Overloaded function.
find_crt_issuer(self, issuer: str) -> lief._lief.PE.x509
Find the x509
certificate according to its issuer
find_crt_issuer(self, issuer: str, serialno: list[int]) -> lief._lief.PE.x509
Find the x509
certificate according to its issuer AND its serial number
Overloaded function.
find_crt_subject(self, subject: str) -> lief._lief.PE.x509
Find the x509
certificate according to its subject
find_crt_subject(self, subject: str, serialno: list[int]) -> lief._lief.PE.x509
Find the x509
certificate according to its subject AND its serial number
Bases: object
Iterator over lief._lief.PE.x509
Bases: object
Iterator over lief._lief.PE.SignerInfo
Return the raw original signature as a byte object
Return an iterator over the signers (SignerInfo
)
Version of the signature. It should be 1
Bases: Object
Interface over PKCS #7 attribute
Bases: object
The underlying integer value
Concrete type of the attribute
Bases: Attribute
Interface over the structure described by the OID 1.2.840.113549.1.9.3
(PKCS #9) The internal structure is described in the: RFC #2985: PKCS #9 - Selected Object Classes and Attribute Types Version 2.0
ContentType ::= OBJECT IDENTIFIER
OID as described in RFC #2985 (string object)
Bases: Attribute
Interface over the structure described by the OID 1.3.6.1.4.1.311.2.4.1
The internal structure is not documented but we can infer the following structure:
MsSpcNestedSignature ::= SET OF SignedData
With SignedData
, the structure described in PKCS #7 RFC (See: lief.PE.Signature
)
Underlying Signature
object
Bases: Attribute
Interface over the structure described by the OID 1.3.6.1.4.1.311.2.1.11
The internal structure is described in the official document: Windows Authenticode Portable Executable Signature Format
SpcStatementType ::= SEQUENCE of OBJECT IDENTIFIER
According to the documentation:
The SpcStatementType MUST contain one Object Identifier with either
the value ``1.3.6.1.4.1.311.2.1.21 (SPC_INDIVIDUAL_SP_KEY_PURPOSE_OBJID)`` or
``1.3.6.1.4.1.311.2.1.22 (SPC_COMMERCIAL_SP_KEY_PURPOSE_OBJID)``.
Bases: Attribute
Interface over the structure described by the OID 1.2.840.113549.1.9.25.4
(PKCS #9)
The internal structure is described in the RFC #2985: PKCS #9 - Selected Object Classes and Attribute Types Version 2.0
sequenceNumber ATTRIBUTE ::= {
WITH SYNTAX SequenceNumber
EQUALITY MATCHING RULE integerMat
SINGLE VALUE TRUE
ID pkcs-9-at-sequenceNumber
}
SequenceNumber ::= INTEGER (1..MAX)
Number as described in the RFC
Bases: Attribute
Interface over the structure described by the OID 1.2.840.113549.1.9.6
(PKCS #9)
The internal structure is described in the RFC #2985: PKCS #9 - Selected Object Classes and Attribute Types Version 2.0
counterSignature ATTRIBUTE ::= {
WITH SYNTAX SignerInfo
ID pkcs-9-at-counterSignature
}
Return the SignerInfo
as described in the RFC #2985
Bases: Attribute
Interface over the structure described by the OID 1.2.840.113549.1.9.4
(PKCS #9)
The internal structure is described in the RFC #2985: PKCS #9 - Selected Object Classes and Attribute Types Version 2.0
messageDigest ATTRIBUTE ::= {
WITH SYNTAX MessageDigest
EQUALITY MATCHING RULE octet
SINGLE VALUE TRUE
ID pkcs-9-at-messageDigest
}
MessageDigest ::= OCTET STRING
Message digeset as a blob of bytes as described in the RFC
Bases: Attribute
Interface over the structure described by the OID 1.2.840.113549.1.9.5
(PKCS #9)
The internal structure is described in the RFC #2985: PKCS #9 - Selected Object Classes and Attribute Types Version 2.0
signingTime ATTRIBUTE ::= {
WITH SYNTAX SigningTime
EQUALITY MATCHING RULE signingTimeMatch
SINGLE VALUE TRUE
ID pkcs-9-at-signingTime
}
SigningTime ::= Time -- imported from ISO/IEC 9594-8
Time as a list [year, month, day, hour, min, sec]
Bases: Attribute
Interface over the structure described by the OID 1.3.6.1.4.1.311.2.1.12
The internal structure is described in the official document: Windows Authenticode Portable Executable Signature Format
SpcSpOpusInfo ::= SEQUENCE {
programName [0] EXPLICIT SpcString OPTIONAL,
moreInfo [1] EXPLICIT SpcLink OPTIONAL
}
Other information such as an URL
Program description provided by the publisher
Bases: Content
Digest used to hash the file. This should match digest_algorithm
Bases: object
Object representing a RSA key
RSA private exponent (in bytes)
RSA public exponent (in bytes)
RSA public modulus (in bytes)
First prime factor (in bytes)
Second prime factor (in bytes)
True if it embeds a private key
True if it embeds a public key
Size of the public modulus in bits
Bases: Object
Interface over a x509 certificate
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Policy information terms as list of OID (see RFC #5280)
Indicates one or more purposes for which the certified public key may be used (list of OID)
Verify this certificate against a list of root CA (list of x509
objects) It returns a set of flags defined by VERIFICATION_FLAGS
signer = binary.signatures[0].signers[0]
microsoft_ca_bundle = lief.PE.x509.parse("bundle.pem")
print(signer.cert.is_trusted_by(microsoft_ca_bundle))
Issuer of the certificate
Return the underlying public-key scheme (KEY_TYPES
)
Purpose of the key contained in the certificate (see KEY_USAGE
)
The raw bytes associated with this x509 cert (DER encoded)
If the underlying public-key scheme is RSA, return the RsaInfo
associated with this certificate. Otherwise, return None
Unique id for certificate issued by a specific CA.
The signature of the certificate
Signature algorithm (OID)
Subject of the certificate
Start time of certificate validity
End time of certificate validity
Verify that this certificate has been used to trust the given x509
certificate
It returns a set of flags defined by VERIFICATION_FLAGS
ca = lief.PE.x509.parse("ca.crt")[0]
signer = lief.PE.x509.parse("signer.crt")[0]
print(ca.verify(signer)) # lief.PE.x509.VERIFICATION_FLAGS.OK
X.509 version. (1=v1, 2=v2, 3=v3)
Bases: Object
ContentInfo as described in the RFC 2315
ContentInfo ::= SEQUENCE {
contentType ContentType,
content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL
}
ContentType ::= OBJECT IDENTIFIER
In the case of PE signature, ContentType must be set to SPC_INDIRECT_DATA_OBJID OID: 1.3.6.1.4.1.311.2.1.4
and content is defined by the structure: SpcIndirectDataContent
SpcIndirectDataContent ::= SEQUENCE {
data SpcAttributeTypeAndOptionalValue,
messageDigest DigestInfo
}
SpcAttributeTypeAndOptionalValue ::= SEQUENCE {
type ObjectID,
value [0] EXPLICIT ANY OPTIONAL
}
For PE signature, SpcAttributeTypeAndOptionalValue.type
is set to SPC_PE_IMAGE_DATAOBJ
(OID: 1.3.6.1.4.1.311.2.1.15
) and the value is defined by SpcPeImageData
DigestInfo ::= SEQUENCE {
digestAlgorithm AlgorithmIdentifier,
digest OCTETSTRING
}
AlgorithmIdentifier ::= SEQUENCE {
algorithm ObjectID,
parameters [0] EXPLICIT ANY OPTIONAL
}
Bases: Object
OID of the content type. This value should match SPC_INDIRECT_DATA_OBJID
Duplicate the current instance of this object
An alias for content_type
Duplicate the current instance of this object
Return the digest (authentihash) if the underlying content type is SPC_INDIRECT_DATA_OBJID
. Return empty bytes otherwise.
Return the hash algorithm used to generate the digest
Bases: Object
SignerInfo as described in the RFC 2315 #Section 9.2
SignerInfo ::= SEQUENCE {
version Version,
issuerAndSerialNumber IssuerAndSerialNumber,
digestAlgorithm DigestAlgorithmIdentifier,
authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
encryptedDigest EncryptedDigest,
unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
}
EncryptedDigest ::= OCTET STRING
Return an iterator over the authenticated attributes (Attribute
)
x509
certificate used by this signer. If it can’t be found, it returns None
Algorithm (ALGORITHMS
) used to hash the file. This value should match ContentInfo.digest_algorithm
and Signature.digest_algorithm
Return the signature created by the signing certificate’s private key
Return algorithm (ALGORITHMS
) used to encrypt the digest
Return the authenticated or un-authenticated attribute matching the given lief.PE.SIG_ATTRIBUTE_TYPES
It returns the first entry that matches the given type. If it can’t be found, it returns None
Return the authenticated attribute matching the given lief.PE.SIG_ATTRIBUTE_TYPES
It returns the first entry that matches the given type. If it can’t be found, it returns None
Return the un-authenticated attribute matching the given lief.PE.SIG_ATTRIBUTE_TYPES
It returns the first entry that matches the given type. If it can’t be found, it returns a nullptr
The X509 issuer used to sign the signed-data (see: lief.PE.x509.issuer
)
Bases: object
Iterator over lief._lief.PE.Attribute
The X509 serial number used to sign the signed-data (see: lief.PE.x509.serial_number
)
Return an iterator over the unauthenticated attributes (Attribute
)
Should be 1
Bases: Attribute
This class exposes the ms-counter-signature.
Return an iterator over x509
certificates
Bases: object
Iterator over lief._lief.PE.x509
Bases: object
Iterator over lief._lief.PE.SignerInfo
Return an iterator over the signers (SignerInfo
)
Bases: Content
Interface over the structure described by the OID 1.2.840.113549.1.9.16.1.4
(PKCS #9)
The internal structure is described in the RFC #3161
TSTInfo ::= SEQUENCE {
version INTEGER { v1(1) },
policy TSAPolicyId,
messageImprint MessageImprint,
serialNumber INTEGER,
genTime GeneralizedTime,
accuracy Accuracy OPTIONAL,
ordering BOOLEAN DEFAULT FALSE,
nonce INTEGER OPTIONAL,
tsa [0] GeneralName OPTIONAL,
extensions [1] IMPLICIT Extensions OPTIONAL
}
TSAPolicyId ::= OBJECT IDENTIFIER
MessageImprint ::= SEQUENCE {
hashAlgorithm AlgorithmIdentifier,
hashedMessage OCTET STRING
}
Accuracy ::= SEQUENCE {
seconds INTEGER OPTIONAL,
millis [0] INTEGER (1..999) OPTIONAL,
micros [1] INTEGER (1..999) OPTIONAL
}
Bases: Attribute
Interface over the structure described by the OID 1.3.6.1.4.1.311.10.3.28
(szOID_PLATFORM_MANIFEST_BINARY_ID
)
The internal structure is not documented but we can infer the following structure:
szOID_PLATFORM_MANIFEST_BINARY_ID ::= SET OF BinaryID
BinaryID ::= UTF8STRING
The manifest id
Bases: Attribute
SigningCertificateV2 ::= SEQUENCE {
certs SEQUENCE OF ESSCertIDv2,
policies SEQUENCE OF PolicyInformation OPTIONAL
}
ESSCertIDv2 ::= SEQUENCE {
hashAlgorithm AlgorithmIdentifier DEFAULT {algorithm id-sha256},
certHash OCTET STRING,
issuerSerial IssuerSerial OPTIONAL
}
IssuerSerial ::= SEQUENCE {
issuer GeneralNames,
serialNumber CertificateSerialNumber
}
PolicyInformation ::= SEQUENCE {
policyIdentifier OBJECT IDENTIFIER,
policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo OPTIONAL
}
Bases: object
Class that is used to rebuild a raw PE binary from a PE::Binary object
Constructor that takes a Binary
Perform the build process
Rebuild the DOS stub
Rebuild the import table into another section
Rebuild the binary’s overlay
Rebuild the relocation table in another section
Rebuid the resources in another section
Rebuild TLS object in another section
Return the build result as a list
of bytes
Patch the original import table in order to redirect functions to the new import table.
This setting should be used with build_imports
set to True
Write the build result into the output
file
Bases: Object
Class which represents a Node in the resource tree. It is extended by lief.PE.ResourceData
and lief.PE.ResourceNode
Add a ResourceData
to the current node
Add a ResourceDirectory
to the current node
Node’s childs
Duplicate the current instance of this object
Overloaded function.
delete_child(self, node: lief._lief.PE.ResourceNode) -> None
Delete the given ResourceNode
from childs
delete_child(self, id: int) -> None
Delete the ResourceNode
with the given id
from childs
Current depth of the entry in the resource tree
True
if the current resource uses a name
Integer that identifies the Type, Name, or Language ID entry.
True
if the current resource is a ResourceData
True
if the current resource is a ResourceDirectory
Bases: object
Iterator over lief._lief.PE.ResourceNode
Resource’s name
Bases: ResourceNode
Default constructor
Resource characteristics. This field is reserved for future use. It is currently set to zero.
The major version number, set by the user.
The minor version number, set by the user.
The number of directory entries immediately following the Name entries that use numeric IDs for Type, Name, or Language entries.
The number of directory entries immediately following the table that use strings to identify Type, Name, or Language entries (depending on the level of the table
The time that the resource data was created by the resource compiler.
Bases: ResourceNode
Class which represents a Data Node in the PE resources tree
Default constructor
Return the code page that is used to decode code point values within the resource data. Typically, the code page is the Unicode code page.
Resource content
Offset of the content within the resource
Warning
This value can change when re-building the resource table
Reserved value. Should be 0
Bases: Object
The Resource Manager provides an enhanced API to manipulate the resource tree
Bases: object
The underlying integer value
Return list of ResourceAccelerator
present in the resource
Add an icon to the resources
Switch the given icons
Return the list of the ResourceDialog
present in the resource
Return ResourceNode
with the given TYPE
or None if not found.
True
if resources contain ResourceAccelerator
true
if the resources contain ResourceDialog
True
if resources contain HTML resource
true
if the resources contain ResourceIcon
True
if the resources contain a Manifest element
True
if resources contain ResourceStringTable
True
if the resource has the given TYPE
true
if the resources contain a ResourceVersion
HTML resource as the list of string
Return the list of the ResourceIcon
present in the resource
Bases: object
Iterator over lief._lief.PE.ResourceAccelerator
Bases: object
Iterator over lief._lief.PE.ResourceDialog
Bases: object
Iterator over lief._lief.PE.ResourceIcon
Bases: object
Iterator over lief._lief.PE.ResourceStringTable
Manifest as a string
Return list of ResourceStringTable
present in the resource
Return list of TYPE
present in the resources
Return the ResourceVersion
Bases: Object
Bits per pixel
Number of colors in image (0 if >=8bpp)
Height in pixels of the image
Id associated with the icon
Language associated with the icon
Color Planes
Reserved (must be 0)
Save the icon to the given filepath
Sublanguage associated with the icon
Width in pixels of the image
Bases: Object
Representation of a dialog box.
Windows allows two kinds of dialog box:
Simple one
Extended one
is_extended
can be used to determine which one is implemented
The character set to be used
The width, in dialog box units, of the dialog box.
The height, in dialog box units, of the dialog box.
Return list of DIALOG_BOX_STYLES
associated with the style
member
The extended windows styles (EXTENDED_WINDOW_STYLES
)
Return list of EXTENDED_WINDOW_STYLES
associated with the extended_style
member
Check if the style
member has the given DIALOG_BOX_STYLES
Check if the extended_style
member has the given EXTENDED_WINDOW_STYLES
Check if the style
member has the given WINDOW_STYLES
The help context identifier for the dialog box window
True
if the dialog is an extended one
Bases: object
Iterator over lief._lief.PE.ResourceDialogItem
Iterator over the controls (ResourceDialogItem
) that defines the Dialog (Button, Label…)
Primary language associated with the dialog
The point size of the font to use for the text in the dialog box and its controls.
Indicate whether a template is an extended dialog box template:
0xFFFF
: Extended dialog box template
Other value: Standard dialog box template
The style of the dialog box. This member can be a combination of WINDOW_STYLES
and DIALOG_BOX_STYLES
Return list of WINDOW_STYLES
associated with the style
member
Secondary language associated with the dialog
The title of the dialog box
The name of the typeface for the font
The version number of the extended dialog box template. This member must be set to 1.
The weight of the font
The x-coordinate, in dialog box units, of the upper-left corner of the dialog box.
The y-coordinate, in dialog box units, of the upper-left corner of the dialog box.
Bases: Object
This class represents an item in the lief.PE.ResourceDialog
The width, in dialog box units, of the control
The height, in dialog box units, of the control
The extended styles for the window
The help context identifier for the control
The control identifier
True
if the control is an extended one
The style of the control. This member can be a combination of WINDOW_STYLES
values and one or more of the control style values.
Initial text of the control
The x-coordinate, in dialog box units, of the upper-left corner of the control
The y-coordinate, in dialog box units, of the upper-left corner of the control
Bases: Object
Class that represents the data associated with the RT_VERSION
entry
See: VS_VERSIONINFO
ResourceFixedFileInfo
associated with the version (if any). This object describes various information about the application’s version.
If not present, this property is set to None
True
if the version contains a ResourceFixedFileInfo
True
if the version contains a ResourceStringFileInfo
True
if the version contains a ResourceVarFileInfo
Signature of the structure. Must be VS_VERSION_INFO
Remove the ResourceFixedFileInfo
from the version
Remove the ResourceStringFileInfo
from the version
Remove the ResourceVarFileInfo
from the version
ResourceStringFileInfo
associated with the version (if any) This object describes various information about the application’s version. The underlying structure is basically a dictionary (key/value)
If the current ResourceVersion
does not use ResourceStringFileInfo
, it returns None.
The type of data in the version resource * 1
if it contains text data * 0
if it contains binary data
ResourceVarFileInfo
associated with the version (if any) This object describes information about languages supported by the application.
If the current ResourceVersion
does not use ResourceVarFileInfo
, it returns None.
Bases: Object
Representation of the VS_FIXEDFILEINFO structure
The least significant 32 bits of the file’s 64-bit binary creation date and time stamp
The most significant 32 bits of the file’s 64-bit binary creation date and time stamp
Contains a bitmask that specifies the Boolean attributes of the file (FIXED_VERSION_FILE_FLAGS
)
Contains a bitmask that specifies the valid bits in file_flags
. A bit is valid only if it was defined when the file was created.
The operating system for which this file was designed (FIXED_VERSION_OS
)
The function of the file (FIXED_VERSION_FILE_SUB_TYPES
)
The general type of file (FIXED_VERSION_FILE_TYPES
)
The least significant 32 bits of the file’s binary version number
This member is used with file_version_MS
to form a 64-bits value used for numeric comparisons.
The most significant 32 bits of the file’s binary version number
This member is used with file_version_LS
to form a 64-bits value used for numeric comparisons.
The least significant 32 bits of the product with which this file was distributed
This member is used with product_version_MS
to form a 64-bits value used for numeric comparisons.
The most significant 32 bits of the product with which this file was distributed
This member is used with product_version_LS
to form a 64-bits value used for numeric comparisons.
Must be set to 0xFEEF04BD
The binary version number of this structure.
The high-order word of this member contains the major version number.
The low-order word contains the minor version number
Bases: Object
This object describes information about languages supported by the application
Signature of the structure. Must be VarFileInfo
List of languages that the application supports
The least significant 16-bits must contain a Microsoft language identifier, and the most significant 16-bits must contain the CODE_PAGES
Either most or least 16-bits can be zero, indicating that the file is language or code page independent.
The type of data in the version resource
1
if it contains text data
0
if it contains binary data
Bases: Object
Representation of the StringFileInfo
structure
See: https://docs.microsoft.com/en-us/windows/win32/menurc/stringfileinfo
Signature of the structure. Must be StringFileInfo
List of the LangCodeItem items
Each key
indicates the appropriate language and code page for displaying the key: value
of items
The type of data in the version resource:
1
if it contains text data
0
if it contains binary data
Bases: Object
Class which represents the childs of the ResourceStringFileInfo
See: https://docs.microsoft.com/en-us/windows/win32/menurc/stringtable
CODE_PAGES
for which items
are defined.
See: https://docs.microsoft.com/en-us/windows/win32/intl/code-page-identifiers
A 8-digit hexadecimal number stored as an Unicode string
The four most significant digits represent the language identifier.
The four least significant digits represent the code page for which the data is formatted.
See:
The type of data in the version resource
1
if it contains text data
0
if it contains binary data
Bases: Object
Class which represents the not-so-documented rich header
This structure is usually located at the end of the dos_stub
and contains information about the build environment.
It is generated by the Microsoft linker link.exe and there are no options to disable or remove this information.
Overloaded function.
add_entry(self, entry: lief._lief.PE.RichEntry) -> None
Add a new RichEntry
add_entry(self, id: int, build_id: int, count: int) -> None
Duplicate the current instance of this object
Return an iterator over the RichEntry
within the header
Overloaded function.
hash(self, algo: lief._lief.PE.ALGORITHMS) -> list[int]
Compute the hash of the decoded rich header structure with the given hash
ALGORITHMS
hash(self, algo: lief._lief.PE.ALGORITHMS, xor_key: int) -> list[int]
Compute the hash of the rich header structure encoded with the provided key and the given hash
ALGORITHMS
Bases: object
Iterator over lief._lief.PE.RichEntry
Key used to encode the header (xor operation)
Overloaded function.
raw(self) -> list[int]
The raw structure of the Rich header without xor-encoding.
This function is equivalent as calling the other raw function with a xor_key set to 0
raw(self, xor_key: int) -> list[int]
Given this rich header, this function re-computes the raw bytes of the structure with the provided xor-key.
You can access the decoded data’s structure with the xor_key set to 0
Bases: Object
Class which represents an entry associated to the RichHeader
Contructor from id
, build_id
and count
Builder number of the tool (if any)
Duplicate the current instance of this object
Occurrence count
Type of the entry
Bases: Object
This class represents a generic entry in the debug data directory. For known types, this class is extended to provide a dedicated API (see: ! CodeCodeView)
Bases: object
The underlying integer value
Address of the debug data relative to the image base
Reserved should be 0
Duplicate the current instance of this object
The major version number of the debug data format.
The minor version number of the debug data format.
File offset of the debug data
Size of the debug data
The time and date when the debug data was created.
The format (TYPES
) of the debugging information
Bases: Debug
Bases: object
The underlying integer value
Type of the code view (SIGNATURES
)
Bases: CodeView
CodeView PDB specialization
Age value to verify. The age does not necessarily correspond to any known time value, it is used to determine if a .pdb file is out of sync with a corresponding .exe file.
The path to the .pdb
file
The GUID signature to verify against the .pdb file signature.
This attribute might be used to lookup remote PDB file on a symbol server
Return a reference to the parent lief.PE.CodeView
The 32-bit signature to verify against the .pdb file signature.
Bases: Debug
Bases: object
The underlying integer value
Bases: object
Iterator over lief._lief.PE.PogoEntry
Type of the pogo (SIGNATURES
)
Bases: Debug
This class represents a reproducible build entry from the debug directory. (IMAGE_DEBUG_TYPE_REPRO
). This entry is usually generated with the undocumented /Brepro linker flag.
See: https://nikhilism.com/post/2020/windows-deterministic-builds/
The hash associated with the reproducible build
Bases: Object
Class that represents the default PE’s LoadConfiguration
It’s the base class for any future versions of the structure
Bases: object
The underlying integer value
Characteristics of the structure.
Duplicate the current instance of this object
The default timeout value to use for is process’s critical sections that are abandoned.
The service pack version identifier.
Memory that must be freed before it is returned to the system, in bytes.
Total amount of free memory, in bytes
On recent the version of the structure, Microsoft renamed reserved1 to DependentLoadFlags. This is an alias for reserved1
Reserved for use by the system.
The global loader flags to clear for this process as the loader start the process.
The global loader flags to set for this process as the loader starts the process.
The VA of a list of addresses where the LOCK
prefix is used so that they can be replaced with NOP
on single processor machines.
Major Version
Maximum allocation size, in bytes.
Minor version
Setting this field to a non-zero value is equivalent to calling SetProcessAffinityMask
with this value during process startup (.exe only)
Process heap flags that correspond to the first argument of the HeapCreate
function. These flags apply to the process heap that is created during process startup.
Must be zero.
A pointer to a cookie that is used by Visual C++ or GS implementation.
Size of the structure which is an alias for characteristics
Date and time stamp value
(SDK) Version of the structure. (WIN_VERSION
)
Maximum virtual memory size, in bytes.
Bases: LoadConfiguration
LoadConfiguration
enhanced with SEH. It is associated with the WIN_VERSION
: SEH
Duplicate the current instance of this object
The count of unique handlers in the table.
The VA of the sorted table of RVAs of each valid, unique SE handler in the image.
Bases: LoadConfigurationV0
LoadConfigurationV0
enhanced with Control Flow Guard. It is associated with the WIN_VERSION
set to WIN_8_1
Bases: object
The underlying integer value
Duplicate the current instance of this object
The VA where Control Flow Guard check-function pointer is stored.
The VA where Control Flow Guard dispatch-function pointer is stored.
Return list of GUARD_CF_FLAGS
present in guard_flags
The count of unique RVAs in the guard_cf_function_table
The VA of the sorted table of RVAs of each Control Flow Guard function in the image.
Control Flow Guard related flags.
Check if the given GUARD_CF_FLAGS
is present in guard_flags
Bases: LoadConfigurationV1
LoadConfigurationV1
enhanced with code integrity. It is associated with the WIN_VERSION
set to WIN10_0_9879
CodeIntegrity
object
Duplicate the current instance of this object
Bases: LoadConfigurationV2
LoadConfigurationV2
with Control Flow Guard improved.
It is associated with the WIN_VERSION
set to WIN10_0_14286
Duplicate the current instance of this object
Number of entries in the guard_address_taken_iat_entry_table
VA of a table associated with CFG’s IAT checks
Number of entries in the guard_address_taken_iat_entry_table
VA of a table associated with CFG’s long jump
Bases: LoadConfigurationV3
LoadConfigurationV3
enhanced with:
Kind of dynamic relocations
Hybrid Metadata Pointer
It is associated with the WIN_VERSION
set to WIN10_0_14383
Duplicate the current instance of this object
VA of pointing to a IMAGE_DYNAMIC_RELOCATION_TABLE
Bases: LoadConfigurationV4
LoadConfigurationV4
enhanced nhanced with Return Flow Guard.
It is associated with the WIN_VERSION
set to WIN10_0_14901
Duplicate the current instance of this object
Offset of dynamic relocation table relative to the relocation table
The section index of the dynamic value relocation table
VA of the failure routine
VA of the failure routine fptr
Must be zero
Bases: LoadConfigurationV5
LoadConfigurationV5
enhanced with Hotpatch and improved RFG.
It is associated with the WIN_VERSION
set to WIN10_0_15002
Duplicate the current instance of this object
VA of the Function verifying the stack pointer
Offset to the hotpatch table
Bases: LoadConfigurationV6
Duplicate the current instance of this object
Bases: LoadConfigurationV7
Duplicate the current instance of this object
Bases: LoadConfigurationV8
Duplicate the current instance of this object
Bases: LoadConfigurationV9
Duplicate the current instance of this object
Bases: LoadConfigurationV10
Duplicate the current instance of this object
Overloaded function.
is_pe(file: str) -> bool
Check if the given file is a PE
is_pe(raw: list[int]) -> bool
Check if the given raw data is a PE
If the input file is a a valid PE
, return the PE_TYPE
. Otherwise, return a lief.lief_errors
.
Compute the hash of imported functions
Properties of the hash generated:
Order agnostic
Casse agnostic
Ordinal (in some extent) agnostic
If one needs the same output as Virus Total (i.e. pefile), you can use PEFILE
as second parameter.
Warning
The algorithm used to compute the imphash value has some variations compared to Yara, pefile, VT implementation
Bases: object
Take a Import
as input and try to resolve its ordinal imports.
If the strict
boolean parameter is set, a lief.lief_errors.not_found
error is returned upon the first non-resolvable ordinal.
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value
Bases: object
The underlying integer value