Ejemplo n.º 1
0
        public static PEInfo Scan(string filename)
        {
            filename = filename.GetFullPath();

            if (!File.Exists(filename)) {
                throw new FileNotFoundException("Unable to find file", filename);
            }

            lock (_cache) {
                var MD5 = filename.GetFileMD5();

                if (!_cache.ContainsKey(filename)) {
                    var result = new PEInfo(filename) {MD5 = MD5};
                    _cache.Add(filename, result);
                    return result;
                }

                var cachedResult = _cache[filename];
                if( cachedResult.MD5 != MD5 ) {
                    // MD5 doesn't match.
                    // replace the old one with the current one
                    _cache.Remove(filename);

                    var result = new PEInfo(filename) {MD5 = MD5};
                    _cache.Add(filename, result);
                    return result;

                }
                return cachedResult;
            }
        }
Ejemplo n.º 2
0
        public static bool DetourCreateProcessWithDll(IntPtr applicationName, IntPtr commandLine, IntPtr lpProcessAttributes,
            IntPtr lpThreadAttributes, String detoursDllName, String detouredDllName, String hostAssemblyName,
            Int32 inheritHandles, UInt32 creationFlags, IntPtr lpEnvironment, IntPtr lpCurrentDirectory, IntPtr lpStartupInfo,
            IntPtr lpProcessInformation, out bool bounced)
        {
            String local_applicationName = Marshal.PtrToStringUni(applicationName);
            String local_commandLine = Marshal.PtrToStringUni(commandLine);

            //
            // Before we go any further, let's make sure this is a binary-compatible target; bounce otherwise.
            // (we'll need to fix up the application name/command line vars too)
            //
            var targetExecutable = (!string.IsNullOrEmpty(local_applicationName)) ? local_applicationName : Helpers.ExtractTargetPath(local_commandLine);
            var pe = new PEInfo(targetExecutable);

            //
            // If we're not binary compatible, store some state information and pull a MITM bounce
            //

            if (Environment.Is64BitProcess && local_commandLine.ToLowerInvariant().Contains("sysnative"))
            {
                local_commandLine = local_commandLine.ToLowerInvariant().Replace("sysnative", "system32");
            }

            if ((Environment.Is64BitProcess == pe.Is32Bit) || ((!Environment.Is64BitProcess) && pe.IsAny)) {

                //
                // Document the process' state, so we can retrieve it later (intact)
                //
                #warning Need to check structure byte count and re-marshal if extended (e.g. STARTUPINFOEXW)
                STARTUPINFOW si = (STARTUPINFOW)Marshal.PtrToStructure(lpStartupInfo, typeof(STARTUPINFOW));
                PROCESS_INFORMATION pi = (PROCESS_INFORMATION)Marshal.PtrToStructure(
                    lpProcessInformation, typeof(PROCESS_INFORMATION));

                string lpTitle = si.lpTitle == IntPtr.Zero ? null : Marshal.PtrToStringUni(si.lpTitle);
                string lpDesktop = si.lpDesktop == IntPtr.Zero ? null : Marshal.PtrToStringUni(si.lpDesktop);

                si.lpDesktop = IntPtr.Zero;
                si.lpTitle = IntPtr.Zero;

                Debug.Assert(si.lpReserved == IntPtr.Zero , "Reserved parameter in StartupInfoW is not null (Contrary to docs)");
                Debug.Assert(si.lpReserved2 == IntPtr.Zero, "Reserved2 parameter in StartupInfoW is not null (Contrary to docs)");

                var scribe = (IScribe)Activator.GetObject(typeof(IScribe), "ipc://CoAppTraceIpc/Scribe");
                var ticket = scribe.DocumentState(local_applicationName, local_commandLine, pi, si, lpDesktop, lpTitle, Process.GetCurrentProcess().Id, pe.IsConsole);

                var result = Kernel32.CreateProcessW(Constants.CoAppTraceExeOpposite, @"""{0}"" --bounce={1}".format(Constants.CoAppTraceExeOpposite, ticket), lpProcessAttributes,
                    lpThreadAttributes, inheritHandles != 0, (int)creationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo,
                    lpProcessInformation);

                bounced = true;

                return result;
            }
            else
            {
                var args = new object[] {
                    applicationName, commandLine, lpProcessAttributes, lpThreadAttributes, detoursDllName, detouredDllName,
                    hostAssemblyName, inheritHandles, creationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo,
                    lpProcessInformation
                };

                var result = DetourCreateProcessWithDllMethod.Invoke(null, args);

                bounced = false;
                return (bool)result;
            }
        }
        private PeBinary(string filename) {
            _filename = filename;
            _info = PEInfo.Scan(filename);
            _loading = Task.Factory.StartNew(() => {
                using (var ri = new ResourceInfo()) {
                    // lets pull out the relevant resources first.
                    ri.Load(_filename);
                    try {
                        var versionKey = ri.Resources.Keys.Where(each => each.ResourceType == ResourceTypes.RT_VERSION).FirstOrDefault();
                        var versionResource = ri.Resources[versionKey].First() as VersionResource;
                        var versionStringTable = (versionResource["StringFileInfo"] as StringFileInfo).Strings.Values.First();

                        _comments = TryGetVersionString(versionStringTable, "Comments");
                        _companyName = TryGetVersionString(versionStringTable, "CompanyName");
                        _productName = TryGetVersionString(versionStringTable, "ProductName");
                        _assemblyVersion = TryGetVersionString(versionStringTable, "Assembly Version");
                        _fileVersion = TryGetVersionString(versionStringTable, "FileVersion");
                        _internalName = TryGetVersionString(versionStringTable, "InternalName");
                        _originalFilename = TryGetVersionString(versionStringTable, "OriginalFilename");
                        _legalCopyright = TryGetVersionString(versionStringTable, "LegalCopyright");
                        _legalTrademarks = TryGetVersionString(versionStringTable, "LegalTrademarks");
                        _fileDescription = TryGetVersionString(versionStringTable, "FileDescription");
                        _bugTracker = TryGetVersionString(versionStringTable, "BugTracker");
                    } catch {
                        // skip it if this fails.
                    }
                }

                if (IsManaged) {
                    // we can read in the binary using CCI
                    try {
                        if (MutableAssembly != null) {
                            // we should see if we can get assembly attributes, since sometimes they can be set, but not the native ones.
                            foreach (var a in MutableAssembly.ContainingAssembly.AssemblyAttributes) {
                                var attributeArgument = (a.Arguments.FirstOrDefault() as MetadataConstant);
                                if (attributeArgument != null) {
                                    var attributeName = a.Type.ToString();
                                    var attributeValue = attributeArgument.Value.ToString();
                                    if (!string.IsNullOrEmpty(attributeValue)) {
                                        switch (attributeName) {
                                            case "System.Reflection.AssemblyTitleAttribute":
                                                if (string.IsNullOrEmpty(AssemblyTitle)) {
                                                    AssemblyTitle = attributeValue;
                                                }
                                                break;
                                            case "System.Reflection.AssemblyCompanyAttribute":
                                                if (string.IsNullOrEmpty(AssemblyCompany)) {
                                                    AssemblyCompany = attributeValue;
                                                }
                                                break;
                                            case "System.Reflection.AssemblyProductAttribute":
                                                if (string.IsNullOrEmpty(AssemblyProduct)) {
                                                    AssemblyProduct = attributeValue;
                                                }
                                                break;
                                            case "System.Reflection.AssemblyVersionAttribute":
                                                if (string.IsNullOrEmpty(AssemblyVersion)) {
                                                    AssemblyVersion = attributeValue;
                                                }
                                                break;
                                            case "System.Reflection.AssemblyFileVersionAttribute":
                                                if (string.IsNullOrEmpty(AssemblyFileVersion)) {
                                                    AssemblyFileVersion = attributeValue;
                                                }
                                                if (string.IsNullOrEmpty(_productVersion)) {
                                                    _productVersion = attributeValue;
                                                }
                                                break;
                                            case "System.Reflection.AssemblyCopyrightAttribute":
                                                if (string.IsNullOrEmpty(AssemblyCopyright)) {
                                                    AssemblyCopyright = attributeValue;
                                                }
                                                break;
                                            case "System.Reflection.AssemblyTrademarkAttribute":
                                                if (string.IsNullOrEmpty(AssemblyTrademark)) {
                                                    AssemblyTrademark = attributeValue;
                                                }
                                                break;
                                            case "System.Reflection.AssemblyDescriptionAttribute":
                                                if (string.IsNullOrEmpty(AssemblyDescription)) {
                                                    AssemblyDescription = attributeValue;
                                                }
                                                break;
                                            case "BugTrackerAttribute":
                                                if (string.IsNullOrEmpty(BugTracker)) {
                                                    BugTracker = attributeValue;
                                                }
                                                break;
                                        }
                                    }
                                }
                            }
                        }
                        _pendingChanges = false;
                    } catch {
                    }
                }
                }); 

            _loading.ContinueWith((antecedent) => {
                // check each of the assembly references, 
                if (IsManaged) {
                    foreach (var ar in MutableAssembly.AssemblyReferences) {
                        if (!ar.PublicKeyToken.Any()) {
                            // dependent assembly isn't signed. 
                            // look for it.
                            var dep = FindAssembly(ar.Name.Value, ar.Version.ToString());
                            if (dep == null) {
                                Console.WriteLine("WARNING: Unsigned Dependent Assembly {0}-{1} not found.", ar.Name.Value, ar.Version.ToString());
                            }
                        }
                    }
                }
            });
        }