"""Resolve the app-local PE dependency closure without consulting PATH or System32.""" from collections import deque from dataclasses import dataclass import hashlib from pathlib import Path import re # Windows 10+ supplies these libraries. Redistributables and driver-provided # libraries deliberately do not belong here. UCRT is an OS component on 10+. SYSTEM_DLLS = frozenset(""" advapi32.dll avrt.dll bcrypt.dll bcryptprimitives.dll cabinet.dll cfgmgr32.dll clbcatq.dll comctl32.dll comdlg32.dll combase.dll crypt32.dll cryptbase.dll cryptnet.dll cryptsp.dll d2d1.dll d3d11.dll d3d12.dll d3d9.dll dcomp.dll dbghelp.dll dnsapi.dll dwrite.dll dwmapi.dll dxgi.dll gdi32.dll gdi32full.dll hid.dll imagehlp.dll imm32.dll iphlpapi.dll kernel32.dll kernelbase.dll mpr.dll msimg32.dll msvcrt.dll mswsock.dll ncrypt.dll netapi32.dll normaliz.dll nsi.dll ntdll.dll ole32.dll oleacc.dll oleaut32.dll opengl32.dll powrprof.dll propsys.dll psapi.dll rpcrt4.dll sechost.dll secur32.dll setupapi.dll shcore.dll shell32.dll shlwapi.dll sspicli.dll ucrtbase.dll user32.dll userenv.dll usp10.dll uxtheme.dll version.dll wer.dll windowscodecs.dll winhttp.dll wininet.dll winmm.dll winspool.drv wintrust.dll wldap32.dll ws2_32.dll wtsapi32.dll """.split()) API_SET = re.compile(r"(?:api|ext)-ms-[a-z0-9-]+-l\d+-\d+-\d+\.dll\Z") VC_RUNTIME = re.compile(r"(?:vcruntime|msvcp|msvcr|msvcm|concrt|vcomp|vccorlib)\d[\w]*\.dll\Z") DEBUG_RUNTIME = re.compile( r"(?:(?:vcruntime|msvcp|msvcr|msvcm|concrt|vcomp|vccorlib)\d[\w]*d(?:_\w+)?" r"|mfc(?:m)?\d+u?d|ucrtbased|msvcrtd)\.dll\Z" ) DEVICE_NAME = re.compile(r"(?:con|prn|aux|nul|com[1-9]|lpt[1-9])\Z", re.I) def safe_basename(name): """Use a portable subset of Windows filenames that is also literal NSIS text.""" if (not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.+ -]{0,254}", name) or name.endswith((".", " ")) or DEVICE_NAME.fullmatch(name.split(".")[0].rstrip())): raise ValueError(f"Unsafe Windows/NSIS filename: {name!r}") return name def dll_name(value): name = safe_basename(value.decode("ascii")).lower() if not name.endswith((".dll", ".drv")): raise ValueError(f"Expected a DLL basename, got {name!r}") return name def dynamic_crt(name): return (bool(VC_RUNTIME.fullmatch(name)) or name in {"msvcrt.dll", "ucrtbase.dll"} or name.startswith(("api-ms-win-crt-", "ext-ms-win-crt-"))) @dataclass class Imports: libraries: dict[str, set[bytes | int]] forwarders: dict[bytes | int, tuple[str, bytes | int]] def descriptor_count(pe, directory, width): """pefile can skip unreadable DLL entries. Compare with the on-disk descriptors.""" if not (directory.VirtualAddress or directory.Size): return 0 if not directory.VirtualAddress or directory.Size < width: raise ValueError("Truncated PE import directory") data = pe.get_data(directory.VirtualAddress, directory.Size) if len(data) != directory.Size: raise ValueError("Truncated PE import directory") for offset in range(0, len(data) - width + 1, width): if not any(data[offset:offset + width]): return offset // width raise ValueError("Unterminated PE import directory") def inspect_pe(path, *, dll=False): # Linux packaging never imports pefile or needs its wheel installed. try: import pefile except ImportError as error: raise ValueError("Windows packaging requires: python -m pip install --require-hashes " "-r packaging/windows/requirements.txt") from error try: with pefile.PE(str(path), fast_load=True) as pe: if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B: raise ValueError("Expected an AMD64 PE32+ image") if not pe.FILE_HEADER.Characteristics & 0x0002: raise ValueError("PE is not an executable image") if bool(pe.FILE_HEADER.Characteristics & 0x2000) != dll: raise ValueError("Expected a DLL image" if dll else "Expected an executable, not a DLL") directories = pe.OPTIONAL_HEADER.DATA_DIRECTORY if pe.OPTIONAL_HEADER.NumberOfRvaAndSizes > len(directories): raise ValueError("Truncated PE data directories") before = len(pe.get_warnings()) pe.parse_data_directories([0, 1, 13]) # This heuristic says nothing about malformed data; real plugins may # import only LoadLibrary/GetProcAddress. All parsing warnings fail. warnings = [w for w in pe.get_warnings()[before:] if w != "Imported symbols contain entries typical of packed executables."] if warnings: raise ValueError("Malformed PE dependency data: " + "; ".join(warnings)) libraries = {} for index, width, attr in ((1, 20, "DIRECTORY_ENTRY_IMPORT"), (13, 32, "DIRECTORY_ENTRY_DELAY_IMPORT")): if index >= len(directories): continue entries = getattr(pe, attr, []) if len(entries) != descriptor_count(pe, directories[index], width): raise ValueError(f"Incomplete PE directory {index}: parser skipped descriptors") for entry in entries: name = dll_name(entry.dll) symbols = libraries.setdefault(name, set()) for symbol in entry.imports: if symbol.import_by_ordinal: symbols.add(symbol.ordinal) else: if not symbol.name or symbol.name == b"*invalid*": raise ValueError(f"Malformed imported symbol in {name}") symbols.add(symbol.name) forwarders = {} exports = getattr(pe, "DIRECTORY_ENTRY_EXPORT", None) if directories and directories[0].VirtualAddress and exports is None: raise ValueError("Unparsed PE export directory") if exports is not None: for symbol in exports.symbols: if symbol.forwarder is None: continue forwarder = symbol.forwarder library, separator, target = forwarder.rpartition(b".") if not library or not separator or not target: raise ValueError(f"Malformed forwarded export {forwarder!r}") name = dll_name(library if library.lower().endswith(b".dll") else library + b".dll") if target.startswith(b"#"): if not target[1:].isdigit() or not 0 < int(target[1:]) <= 65535: raise ValueError(f"Malformed forwarded ordinal {target!r}") target = int(target[1:]) forwarders[symbol.ordinal] = (name, target) if symbol.name is not None: forwarders[symbol.name] = (name, target) return Imports(libraries, forwarders) except (pefile.PEFormatError, ValueError, OSError) as error: raise ValueError(f"{path}: {error}") from error def resolve_dependencies(binary, dll_dirs=(), require_static_crt=False): """Return {Windows basename: source path}, with only imported DLLs selected.""" binary = Path(binary).resolve() directories = list(dict.fromkeys([binary.parent, *(Path(p).resolve() for p in dll_dirs)])) candidates = {} for directory in directories: if not directory.is_dir(): raise ValueError(f"DLL source is not a directory: {directory}") for path in sorted(directory.iterdir(), key=lambda p: p.name): candidates.setdefault(path.name.lower(), []).append(path) root = inspect_pe(binary) if require_static_crt: dynamic = sorted(name for name in root.libraries if dynamic_crt(name) or DEBUG_RUNTIME.fullmatch(name)) if dynamic: raise ValueError(f"{binary.name}: --require-static-crt rejects dynamic CRT imports: " + ", ".join(dynamic)) pending = deque((name, symbols, (binary.name, name)) for name, symbols in sorted(root.libraries.items())) selected, inspected, visited = {}, {}, {} while pending: name, symbols, chain = pending.popleft() try: if DEBUG_RUNTIME.fullmatch(name): raise ValueError(f"Debug VC runtime cannot be redistributed: {name}") if name in SYSTEM_DLLS or API_SET.fullmatch(name): continue if name not in inspected: paths = candidates.get(name, []) if not paths: raise ValueError(f"Missing {name}; supply its redistributable directory with --dll-dir. " f"Searched: {', '.join(map(str, directories))}") for path in paths: if path.is_symlink() or not path.is_file(): raise ValueError(f"DLL source must be a regular, non-symlink file: {path}") safe_basename(path.name) if len(paths) > 1: digests = set() for path in paths: with path.open("rb") as stream: digests.add(hashlib.file_digest(stream, "sha256").digest()) if len(digests) != 1: raise ValueError(f"Ambiguous differing sources for {name}: {', '.join(map(str, paths))}") selected[name] = paths[0] inspected[name] = inspect_pe(paths[0], dll=True) pending.extend((dependency, requested, (*chain, dependency)) for dependency, requested in sorted(inspected[name].libraries.items())) seen = visited.setdefault(name, set()) for symbol in symbols - seen: forwarded = inspected[name].forwarders.get(symbol) if forwarded: dependency, target = forwarded pending.append((dependency, {target}, (*chain, dependency))) seen.update(symbols) except (ValueError, OSError) as error: raise ValueError(f"{' -> '.join(chain)}: {error}") from error return dict(sorted(selected.items()))