Skip to content

Instantly share code, notes, and snippets.

@matterpreter
Last active November 28, 2022 04:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save matterpreter/0e173ffcbe423c529a708c88128ee2a0 to your computer and use it in GitHub Desktop.
Save matterpreter/0e173ffcbe423c529a708c88128ee2a0 to your computer and use it in GitHub Desktop.
Search all PE files in a directory for ones which import a specific DLL
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using PeNet;
using PeNet.Header.Pe;
namespace FindTargetImports
{
class Program
{
public static readonly string Usage = "FindTargetImports.exe <search_root> <target_module.dll>";
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine(Usage);
return;
}
string directory = args[0];
string targetDll = args[1];
if (!Directory.Exists(directory))
{
Console.WriteLine("[-] Couldn't find the target directory");
return;
}
Console.WriteLine();
Stopwatch timer = Stopwatch.StartNew();
List<string> extensions = new List<string> { "exe", "dll", "sys" };
// Get all files in the target directory without recursing
IEnumerable<string> allFiles = Directory.EnumerateFiles(directory, "*.*", SearchOption.TopDirectoryOnly)
.Where(s => extensions.Contains(Path.GetExtension(s).TrimStart('.').ToLowerInvariant()));
// Thread-safe collection just in case
ConcurrentBag<string> matches = new ConcurrentBag<string>();
// Parallelize our search
Parallel.ForEach(allFiles, file =>
{
if (ParseImportedModulesForMatch(file, targetDll))
{
matches.Add(file);
}
});
// Print out final results
if (matches.Count > 0)
{
foreach (string match in matches.Distinct())
{
Console.WriteLine($"[+] {match} imports {args[1]}");
}
}
else
{
Console.WriteLine("[-] No results found");
}
timer.Stop();
Console.WriteLine($"\nCompleted execution in {timer.ElapsedMilliseconds}ms");
}
private static bool ParseImportedModulesForMatch(string filePath, string targetImport)
{
try
{
PeFile peHeader = new PeFile(File.ReadAllBytes(filePath));
ImportFunction[] imports = peHeader.ImportedFunctions;
foreach (ImportFunction import in imports)
{
if (import.DLL.ToLower() == targetImport)
{
return true;
}
}
}
catch { }
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment