List of open files held by a process? [duplicate] - c#

How do I get the list of open file handles by process id in C#?
I'm interested in digging down and getting the file names as well.
Looking for the programmatic equivalent of what process explorer does.
Most likely this will require interop.
Considering adding a bounty on this, the implementation is nasty complicated.

Ouch this is going to be hard to do from managed code.
There is a sample on codeproject
Most of the stuff can be done in interop, but you need a driver to get the filename cause it lives in the kernel's address space. Process Explorer embeds the driver in its resources. Getting this all hooked up from C# and supporting 64bit as well as 32, is going to be a major headache.

You can also run the command line app, Handle, by Mark Rusinovich, and parse the output.

Have a look at this file :
http://vmccontroller.codeplex.com/SourceControl/changeset/view/47386#195318
And use:
DetectOpenFiles.GetOpenFilesEnumerator(processID);
Demo:
using System;
using System.Diagnostics;
namespace OpenFiles
{
class Program
{
static void Main(string[] args)
{
using (var openFiles = VmcController.Services.DetectOpenFiles.GetOpenFilesEnumerator(Process.GetCurrentProcess().Id))
{
while (openFiles.MoveNext())
{
Console.WriteLine(openFiles.Current);
}
}
Console.WriteLine();
Console.ReadKey();
}
}
}
It has dependency over assembly System.EnterpriseServices

You can P/INVOKE into the NtQuerySystemInformation function to query for all handles and then go from there. This Google groups discussion has details.

Take a look at wj32's Process Hacker version 1, which can do what you asked, and more.

Handle is great program, and the link to codeproject is good.
#Brian
The reason for the code is that handle.exe is NOT redistributable. Nor do they release their source.
It looks as if .Net will not easily do this since it appears that an embedded device drive is requried to access the information. This cannot be done in .net without an unmanged DLL. It's relatviely deep kernel code when compared to typical .net coding. I'm surprised that WMI does not expose this.

Perhaps using command line tool:
OpenedFilesView v1.50 - View opened/locked files in your system (sharing violation issues)
http://www.nirsoft.net/utils/opened_files_view.html

Related

C# Decompiling: Some of methods are empty

I have only exe+dlls. CEF shows me:
Portable .NET.
I try to use dnSpy to decompiling and see methods empty with attribute like this
// Token: 0x0600011D RID: 285 RVA: 0x00003098 File Offset: 0x00001498
[MethodImpl(MethodImplOptions.NoInlining)]
private static void hyzOMB8lk(string[] \u0020)
{
}
Is it possible to see the real method body?
As the matter of fact There is no tool which will give you 100% working source code, It's just like using Google Translator Korean To English and vice versa.
Making a working source code from binary requires a skill set of writing codes, understanding the behavior of application you trying to decompile (I would assume you've lost the source code and have exe file and trying to recover, don't do that to a property of someone without permission :) )
anyway you can try Dot Peek, .NET Reflector, IDA pro..
In your case you were not able to see the code in some methods so I would suggest you to take some time learning hooking the process finding the required offsets from the memory and check it's behavior, you can either disassemble those chunks of methods or just reproduce the functionality of those methods how it behaves ( that requires certain amount of skills in reverse engineering )
Hope I was able to deliver the concept as per my knowledge tried to keep it simple.

managed DLL MethodNotFoundException

I'm looking for a way to detect broken dependencies before or during app startup, but after compilation.
Suppose MyApplication has a code path that makes a call to Dependency.Foo(), which lives in dependency.dll.
Now suppose that I delete Foo() and deploy the updated dependency.dll without recompiling MyApplication.
MyApplication will start up and work fine until it hits a code path that wants to call Dependency.Foo(). Then it blows up with a MethodNotFoundException.
Is there a way I can detect the broken dependency and make MyApplication fail fast?
I'm thinking of something that would scan the dlls in the bin folder and validate the calls they make to other managed dlls. A coworker mentioned this is easy to do in the java world, but I have no idea what he was talking about...
This feels like a crazy suggestion, but you could look at using libcheck and ship a 'supported' store file for a given version of MyApplication. Then you can validate (not sure if this can be done at runtime) and compare current store with supported store and any API breaks can be reported.
Really, the solution is to control versions via automated builds and quality gateways when shipping the software.
But as #SimonC says, cecil can work too.
You could use reflection to determine if Dependency.Foo exists as MyApplication is loading.
Something along the lines of:
if (typeof(Dependency).GetMethod("Foo") == null)
{
//Fail fast, Dependency.Foo could not be found!
}
The same idea also works for fields and properties, or more generally, for any class member at all.
if (typeof(Dependency).GetMember("Bar").Length == 0)
{
//Fail fast, Dependency.Bar could not be found!
}
For more information:
System.Type on MSDN
If you are developing your own add-in architecture, you will have to follow the other answers. But if you plan to use something more reliable, please consider what Microsoft ships with .NET 4, called Managed Extensibility Framework,
http://msdn.microsoft.com/en-us/magazine/ee291628.aspx
It is a general approach to design add-in contracts and allows you to handle different versions of contracts safely.

Tunneling all connections of an application through a proxy

Similar to freecap.
I am looking to develop a solution that works just on certain software and runs invisibly to the end-user. I would like to bundle the tunneler with a software package (of which I don't have access to the source code).
I have heard the only way to do this is similar to what freecap does. Using DLL injection and then hook onto WinSock API. I am just wondering if there was an easier method besides DLL injection via .NET or C++. I can convert most C++ into C#, so that's why I am open to that set.
If not, I would appreciate any advice or links you can provide about going about DLL injection and hooking into the WinSock API. Perhaps an opensource project similar to freecap.
Or, if you know of an application that I can launch via command line say freecap.exe --start myprogram.exe This way freecap would run invisibly to the end user.
API hooking is basically the only way to do this. There are a variety of approaches you could use to hook into WinSock and get your code running and DLL injection (via replacing entries in a process' Import Address Table) is the most straightforward of these.
A dynamically-linked process' IAT stores the memory locations of libraries which contain functions it needs during it's execution. This technique works by modifying entries in this table to point to another library (one containing your code). There are other ways to insert your code into another process, but this is the most stable if you just want to affect the behaviour of a single process on your system.
If you want to avoid doing most of the implementation work yourself and just concentrate on getting something running, I would suggest using EasyHook.
EasyHook is licensed under the GNU Lesser General Public License or LGPL.
From the website:
EasyHook starts where Microsoft Detours ends.
This project supports extending (hooking) unmanaged code (APIs) with pure managed ones, from within
a fully managed environment like C# using Windows 2000 SP4 and later, including Windows XP x64,
Windows Vista x64 and Windows Server 2008 x64. Also 32- and 64-bit kernel mode hooking is supported
as well as an unmanaged user-mode API which allows you to hook targets without requiring a NET
Framework on the customers PC. An experimental stealth injection hides hooking from most of the
current AV software.
As the above says, this project should allow you to greatly simplify the hooking process, and allows you to do so while working in C#.
From the documentation, here's the authors example of injecting a simple Filemon (now Process Monitor)-type utility into a target process:
// Copyright © 2008 Christoph Husse
using System;
using System.Collections.Generic;
using System.Runtime.Remoting;
using System.Text;
using EasyHook;
namespace FileMon
{
public class FileMonInterface : MarshalByRefObject
{
public void IsInstalled(Int32 InClientPID)
{
Console.WriteLine("FileMon has been installed in target {0}.\r\n", InClientPID);
}
public void OnCreateFile(Int32 InClientPID, String[] InFileNames)
{
for (int i = 0; i < InFileNames.Length; i++)
{
Console.WriteLine(InFileNames[i]);
}
}
public void ReportException(Exception InInfo)
{
Console.WriteLine("The target process has reported an error:\r\n"+ InInfo.ToString());
}
}
class Program
{
static String ChannelName = null;
static void Main(string[] args)
{
try
{
Config.Register(
"A FileMon like demo application.",
"FileMon.exe",
"FileMonInject.dll");
RemoteHooking.IpcCreateServer<FileMonInterface>(ref ChannelName, WellKnownObjectMode.SingleCall);
RemoteHooking.Inject(
Int32.Parse(args[0]),
"FileMonInject.dll",
"FileMonInject.dll",
ChannelName);
Console.ReadLine();
}
catch (Exception ExtInfo)
{
Console.WriteLine("There was an error while connecting to target:\r\n{0}", ExtInfo.ToString());
}
}
}
}
I hope this is helpful. Good luck!

Assembler library for .NET, assembling runtime-variable strings into machine code for injection

Is there such a thing as an x86 assembler that I can call through C#? I want to be able to pass x86 instructions as a string and get a byte array back. If one doesn't exist, how can I make my own?
To be clear - I don't want to call assembly code from C# - I just want to be able to assemble code from instructions and get the machine code in a byte array.
I'll be injecting this code (which will be generated on the fly) to inject into another process altogether.
As part of some early prototyping I did on a personal project, I wrote quite a bit of code to do something like this. It doesn't take strings -- x86 opcodes are methods on an X86Writer class. Its not documented at all, and has nowhere near complete coverage, but if it would be of interest, I would be willing to open-source it under the New BSD license.
UPDATE:
Ok, I've created that project -- Managed.X86
See this project:
https://github.com/ZenLulz/MemorySharp
This project wraps the FASM assembler, which is written in assembly and as a compiled as Microsoft coff object, wrapped by a C++ project, and then again wrapped in C#. This can do exactly what you want: given a string of x86/x64 assembly, this will produce the bytes needed.
If you require the opposite, there is a port of the Udis86 disassembler, fully ported to C#, here:
https://github.com/spazzarama/SharpDisasm
This will convert an array of bytes into the instruction strings for x86/x64
Take a look at Phoenix from Microsoft Research.
Cosmos also has some interesting support for generating x86 code:
http://www.gocosmos.org/blog/20080428.en.aspx
Not directly from C# you can't. However, you could potentially write your own wrapper class that uses an external assembler to compile code. So, you would potentially write the assembly out to a file, use the .NET Framework to spin up a new process that executes the assembler program, and then use System.IO to open up the generated file by the assembler to pull out the byte stream.
However, even if you do all that, I would be highly surprised if you don't then run into security issues. Injecting executable code into a completely different process is becoming less and less possible with each new OS. With Vista, I believe you would definitely get denied. And even in XP, I think you would get an access denied exception when trying to write into memory of another process.
Of course, that raises the question of why you are needing to do this. Surely there's got to be a better way :).
Take a look at this: CodeProject: Using unmanaged code and assembly in C#.
I think you would be best off writing a native Win32 dll. You can then write a function in assembler that is exported from the dll. You can then use C# to dynamically link to the dll.
This is not quite the same as passing in a string and returning a byte array. To do this you would need an x86 assembler component, or a wrapper around masm.exe.
i don't know if this is how it works but you could just shellexecute an external compiler then loading the object generated in your byte array.

How to use win32api from IronPython

Writing some test scripts in IronPython, I want to verify whether a window is displayed or not. I have the pid of the main app's process, and want to get a list of window titles that are related to the pid.
I was trying to avoid using win32api calls, such as FindWindowEx, since (to my knowledge) you cannot access win32api directly from IronPython. Is there a way to do this using built-in .net classes? Most of the stuff I have come across recommends using win32api, such as below.
.NET (C#): Getting child windows when you only have a process handle or PID?
UPDATE: I found a work-around to what I was trying to do. Answer below.
As of IronPython 2.6 the ctypes module is supported. This module provides C compatible data types, and allows calling functions in DLLs. Quick example:
import ctypes
buffer = ctypes.create_string_buffer(100)
ctypes.windll.kernel32.GetWindowsDirectoryA(buffer, len(buffer))
print buffer.value
The article below shows how to access the win32api indirectly from IronPython. It uses CSharpCodeProvider CompileAssemblyFromSource method to compile an assembly in memory from the supplied C# source code string. IronPython can then import the assembly.
Dynamically compiling C# from IronPython
It's like asking if you can swim without going in to the water. If you need information from windows, the only option is to use the win32api. There are lots of examples to find on how to do so.
If you don't like this answer, just leave a comment in your question and I will remove this answer, so your question will remain in the unanswered questions list.

Categories