Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
Distribution Points, but none with an http:// URL, so its revocation
status is not checked online (thanks to SecBuddyF of Tencent Keen
Security Lab for reporting the issue)
- fixed excessive CPU use when parsing malformed MSI sector chains and
incorrect rejection of valid chains that link to sector 0

### 2.16 (2026.11.13)

Expand Down
5 changes: 3 additions & 2 deletions cmake/CMakeTest.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,8 @@ if(Python3_FOUND AND NOT cryptography_error)
# certificates, which make the signature exceed the 4 KiB mini stream
# cutoff. The invalid "duplicate_signature" tree has two DigitalSignature
# streams, which must not be kept when signing or removing the signature.
foreach(tree "nested" "no_streams" "duplicate_signature")
# The "zero_links" case exercises FAT and MiniFAT links to sector 0.
foreach(tree IN ITEMS "nested" "no_streams" "duplicate_signature" "zero_links")
set(tree_file "${FILES}/tree_${tree}")
add_test(NAME "msi_tree_${tree}_create"
COMMAND ${Python3_EXECUTABLE} "${TEST_DIR}/check_msi_tree.py"
Expand Down Expand Up @@ -397,7 +398,7 @@ if(Python3_FOUND AND NOT cryptography_error)
"msi_tree_${tree}_verify_resigned")
set(OUTPUT_FILES ${OUTPUT_FILES} "${tree_file}.msi" "${tree_file}_signed.msi"
"${tree_file}_removed.msi" "${tree_file}_resigned.msi")
endforeach(tree "nested" "no_streams" "duplicate_signature")
endforeach()


### Verify signature ###
Expand Down
30 changes: 20 additions & 10 deletions msi.c
Original file line number Diff line number Diff line change
Expand Up @@ -809,7 +809,7 @@ static const u_char *sector_offset_to_address(MSI_FILE *msi, uint32_t sector, ui
/* the header occupies the first sector */
uint64_t pos = ((uint64_t)sector + 1) * msi->m_sectorSize + offset;

if (sector >= MAXREGSECT || offset >= msi->m_sectorSize
if (sector > MAXREGSECT || offset >= msi->m_sectorSize
|| len > msi->m_sectorSize - offset || pos + len > msi->m_bufferLen) {
fprintf(stderr, "Corrupted file\n");
return NULL; /* FAILED */
Expand All @@ -822,8 +822,15 @@ static uint32_t get_fat_sector_location(MSI_FILE *msi, uint32_t fatSectorNumber)
uint32_t entriesPerSector, difatSectorLocation, fatSectorLocation;
const u_char *address;

/* Reject numbers the header does not account for before walking the DIFAT
* chain: a corrupt sector reference can otherwise be as large as 0xFFFFFFFF,
* which made the subtraction loop below iterate millions of times. */
if (fatSectorNumber >= msi->m_hdr->numFATSector) {
fprintf(stderr, "Invalid FAT sector number 0x%08X\n", fatSectorNumber);
return NOSTREAM; /* FAILED */
}
if (fatSectorNumber < DIFAT_IN_HEADER) {
return LE_UINT32(msi->m_hdr->headerDIFAT[fatSectorNumber]);
fatSectorLocation = LE_UINT32(msi->m_hdr->headerDIFAT[fatSectorNumber]);
} else {
fatSectorNumber -= DIFAT_IN_HEADER;
entriesPerSector = msi->m_sectorSize / 4 - 1;
Expand All @@ -843,12 +850,12 @@ static uint32_t get_fat_sector_location(MSI_FILE *msi, uint32_t fatSectorNumber)
return NOSTREAM; /* FAILED */
}
fatSectorLocation = GET_UINT32_LE(address);
if (fatSectorLocation == 0 || fatSectorLocation >= FREESECT) {
fprintf(stderr, "Get corrupted sector location 0x%08X\n", fatSectorLocation);
return NOSTREAM; /* FAILED */
}
return fatSectorLocation;
}
if (fatSectorLocation > MAXREGSECT) {
fprintf(stderr, "Get corrupted sector location 0x%08X\n", fatSectorLocation);
return NOSTREAM; /* FAILED */
}
return fatSectorLocation;
}

/* Lookup FAT */
Expand All @@ -869,7 +876,8 @@ static uint32_t get_next_sector(MSI_FILE *msi, uint32_t sector)
return NOSTREAM; /* FAILED */
}
nextSectorLocation = GET_UINT32_LE(address);
if (nextSectorLocation == 0 || nextSectorLocation >= FREESECT) {
/* A next sector is required here, so ENDOFCHAIN is not a valid location. */
if (nextSectorLocation > MAXREGSECT) {
fprintf(stderr, "Get corrupted sector location 0x%08X\n", nextSectorLocation);
return NOSTREAM; /* FAILED */
}
Expand Down Expand Up @@ -898,7 +906,7 @@ static int locate_final_sector(MSI_FILE *msi, uint32_t sector, uint32_t offset,
*/
static const u_char *mini_sector_offset_to_address(MSI_FILE *msi, uint32_t sector, uint32_t offset, uint32_t len)
{
if (sector >= MAXREGSECT || offset >= msi->m_minisectorSize ||
if (sector > MAXREGSECT || offset >= msi->m_minisectorSize ||
(msi->m_bufferLen - offset) / msi->m_minisectorSize <= sector) {
fprintf(stderr, "Corrupted file\n");
return NULL; /* FAILED */
Expand Down Expand Up @@ -961,7 +969,7 @@ static uint32_t get_next_mini_sector(MSI_FILE *msi, uint32_t miniSector)
return NOSTREAM; /* FAILED */
}
nextMiniSectorLocation = GET_UINT32_LE(address);
if (nextMiniSectorLocation == 0 || nextMiniSectorLocation >= FREESECT) {
if (nextMiniSectorLocation > MAXREGSECT) {
fprintf(stderr, "Get corrupted sector location 0x%08X\n", nextMiniSectorLocation);
return NOSTREAM; /* FAILED */
}
Expand Down Expand Up @@ -1003,6 +1011,8 @@ static int read_mini_stream(MSI_FILE *msi, uint32_t sector, uint32_t offset, cha
memcpy(buffer, address, copylen);
buffer += copylen;
len -= copylen;
if (len == 0)
break; /* the last mini sector of the stream has been read */
sector = get_next_mini_sector(msi, sector);
if (sector == NOSTREAM) {
fprintf(stderr, "Failed to get a next mini sector\n");
Expand Down
95 changes: 62 additions & 33 deletions tests/check_msi_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,27 @@
# an invalid file with two adjacent DigitalSignature streams,
# which must both be replaced or removed
"duplicate_signature": ["a", SIGNATURES[0], SIGNATURES[0], "b"],
# The mini stream spans two regular sectors, and its only stream spans
# several mini sectors. Both chains link backward to sector 0.
"zero_links": ["multi_sector"],
}


def stream_data(path: str) -> bytes:
"""Return the payload for a stream in a fixture."""
if path == "multi_sector":
return bytes(range(256)) * 2 + b"tail"
return f"data of {path}".encode()


def expected(tree: list, prefix: str = "") -> dict:
"""Return the paths of the storages (None) and streams (their data)."""
paths = {}
for node in tree:
if node in SIGNATURES:
continue # replaced or removed by osslsigncode
if isinstance(node, str):
paths[prefix + node] = f"data of {prefix}{node}".encode()
paths[prefix + node] = stream_data(prefix + node)
else:
paths[prefix + node[0] + "/"] = None
paths.update(expected(node[1], prefix + node[0] + "/"))
Expand All @@ -57,7 +67,7 @@ def flatten(tree: list) -> list:
def add(node, prefix: str) -> int:
index = len(nodes)
if isinstance(node, str):
nodes.append([node, STREAM, [], f"data of {prefix}{node}".encode()])
nodes.append([node, STREAM, [], stream_data(prefix + node)])
else:
nodes.append([node[0], STORAGE, [], b""])
nodes[index][2] = [add(child, f"{prefix}{node[0]}/") for child in node[1]]
Expand All @@ -67,7 +77,7 @@ def add(node, prefix: str) -> int:
return nodes


def dir_entries(nodes: list, streams: list, ministream: tuple) -> bytes:
def dir_entries(nodes: list, stream_starts: dict, ministream: tuple) -> bytes:
"""Return the directory entries, the root entry holds the mini stream
given by its first sector and its length."""
# link the children of each storage as a list of right siblings
Expand All @@ -79,7 +89,7 @@ def dir_entries(nodes: list, streams: list, ministream: tuple) -> bytes:
if kind == ROOT:
location = struct.pack("<IQ", *ministream)
elif kind == STREAM:
location = struct.pack("<IQ", streams.index(index), len(data))
location = struct.pack("<IQ", stream_starts[index], len(data))
else:
location = bytes(12)
encoded = (name + "\0").encode("utf-16le")
Expand All @@ -90,40 +100,59 @@ def dir_entries(nodes: list, streams: list, ministream: tuple) -> bytes:
return entries


def make(path: str, tree: list) -> None:
def add_chain(sectors: list, fat: list, size: int, data: bytes, reverse: bool = False) -> int:
"""Allocate a chain and return its start sector; reverse its physical order if requested."""
if not data:
return ENDOFCHAIN
chunks = [data[i:i + size].ljust(size, b"\0") for i in range(0, len(data), size)]
ids = list(range(len(sectors), len(sectors) + len(chunks)))
if reverse:
chunks.reverse()
ids.reverse()
sectors.extend(chunks)
fat.extend([ENDOFCHAIN] * len(chunks))
for sector, next_sector in zip(ids, ids[1:]):
fat[sector] = next_sector
return ids[0]


def pack_fat(fat: list) -> bytes:
"""Encode a one-sector FAT or MiniFAT."""
if len(fat) > SECTOR_SIZE // 4:
raise ValueError("the tree is too large")
return struct.pack("<128I", *(fat + [FREESECT] * (SECTOR_SIZE // 4 - len(fat))))


def make(path: str, tree: list, zero_links: bool = False) -> None:
"""Write a version 3 compound file with the tree and small streams."""
nodes = flatten(tree)
streams = [index for index, node in enumerate(nodes) if node[1] == STREAM]
ministream = b"".join(nodes[i][3].ljust(MINI_SECTOR_SIZE, b"\0") for i in streams)
# sector 0: FAT, sector 1: MiniFAT if needed, then the mini stream and the directory
fat = [FATSECT] + ([ENDOFCHAIN] if streams else [])
chains = []
for length in (len(ministream), len(nodes) * 128):
first, count = len(fat), -(-length // SECTOR_SIZE)
chains.append(first if count else ENDOFCHAIN)
if count:
fat += [first + i + 1 for i in range(count - 1)] + [ENDOFCHAIN]
if len(fat) > SECTOR_SIZE // 4 or len(streams) > SECTOR_SIZE // 4:
raise ValueError("the tree is too large")
# each stream gets a single mini sector and a single MiniFAT entry
if any(len(nodes[i][3]) > MINI_SECTOR_SIZE for i in streams):
raise ValueError("a stream is longer than a mini sector")
fat += [FREESECT] * (SECTOR_SIZE // 4 - len(fat))
minifat = b""
if streams:
minifat = struct.pack("<128I", *([ENDOFCHAIN] * len(streams)
+ [FREESECT] * (SECTOR_SIZE // 4 - len(streams))))
mini_sectors, minifat = [], []
stream_starts = {
index: add_chain(mini_sectors, minifat, MINI_SECTOR_SIZE, data, reverse=zero_links)
for index, (_, kind, _, data) in enumerate(nodes) if kind == STREAM
}
ministream = b"".join(mini_sectors)
# Normally the FAT is at sector 0. For zero_links, put the mini stream there
# instead and allocate the FAT after the data, so a chain link can point to 0.
sectors, fat = ([], []) if zero_links else ([b""], [FATSECT])
mini_start = add_chain(sectors, fat, SECTOR_SIZE, ministream, reverse=zero_links)
minifat_start = add_chain(sectors, fat, SECTOR_SIZE, pack_fat(minifat) if minifat else b"")
entries = dir_entries(nodes, stream_starts, (mini_start, len(ministream)))
dir_start = add_chain(sectors, fat, SECTOR_SIZE, entries)
fat_sector = 0
if zero_links:
fat_sector = len(sectors)
sectors.append(b"")
fat.append(FATSECT)
sectors[fat_sector] = pack_fat(fat)

header = bytes.fromhex("D0CF11E0A1B11AE1") + bytes(16)
header += struct.pack("<HHHHH", 0x3E, 3, 0xFFFE, 9, 6) + bytes(6)
header += struct.pack("<IIIIIIIII", 0, 1, chains[1], 0, 4096,
1 if streams else ENDOFCHAIN, len(minifat) // SECTOR_SIZE, ENDOFCHAIN, 0)
header += struct.pack("<109I", 0, *([FREESECT] * 108))
header += struct.pack("<IIIIIIIII", 0, 1, dir_start, 0, 4096,
minifat_start, int(bool(minifat)), ENDOFCHAIN, 0)
header += struct.pack("<109I", fat_sector, *([FREESECT] * 108))
with open(path, "wb") as file:
file.write(header + struct.pack("<128I", *fat) + minifat)
file.write(ministream.ljust(-(-len(ministream) // SECTOR_SIZE) * SECTOR_SIZE, b"\0"))
entries = dir_entries(nodes, streams, (chains[0], len(ministream)))
file.write(entries.ljust(-(-len(entries) // SECTOR_SIZE) * SECTOR_SIZE, b"\0"))
file.write(header + b"".join(sectors))


class CompoundFile:
Expand Down Expand Up @@ -241,7 +270,7 @@ def main() -> None:
if len(sys.argv) == 4 and sys.argv[1] in ("make", "check") and sys.argv[3] in TREES:
tree = TREES[sys.argv[3]]
if sys.argv[1] == "make":
make(sys.argv[2], tree)
make(sys.argv[2], tree, zero_links=sys.argv[3] == "zero_links")
else:
sys.exit(check(sys.argv[2], tree))
else:
Expand Down
Loading