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!
Related
Good day everyone,
I am writing a C# application that will allow users to dynamically set the database they want to connect to (I'll work a bit with the database data and such, but that's not important). The important part is that I'm allowing my users to connect to data-stores from OLEDB using the code below.
ADODB.Connection connection;
MSDASC.DataLinks instance = new MSDASC.DataLinksClass();
if( (connection = instance.PromptNew() as ADODB.Connection) == null ) return;
This will open the very same Dialog that windows opens for *.udl files, and that's exactly what I want.
However, I hit a interesting problem to which your brightness could come in handy: some customer WILL have to browse for x86 drivers, and the vast majority will certainly use x64.
I know you can open x86 UDL files with the following command-line:
"C:\Windows\syswow64\rundll32.exe" "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile "C:\myConnectionFile.udl"
When the default (64 bit) command is:
"C:\Program Files\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile "C:\myConnectionFile.udl"
In other words: windows' allowing users to create entries in both fashion. I would like to do the same in my app, using the API.
I have considered the option of creating a temp UDL file and opening from the command-line above, which made my conversation with my technical lead rather unpleasant, so that's not an option.
All suggestions are welcome. I will not dismiss unsafe coding nor the thought of building wrapper in C++ if we get to that (although my C++ is inconveniently rusty nowadays).
Thank you all in advance and happy coding...
Good day fellow developers,
After a tedious and lengthy research process I have around the answer I was looking for.
In order to use OLEDB providers for both 32 and 64 bit platform from one single C# 64bit app I'll need to create an Out-of-Process Wrapper to the 32bit call, and make the call over IPC (Internal Process Calls). Because the amount of functionalities I'm exposing is moderate, the hindrance was just re-creating some method calls on the wrapper.
This blog helped me put the parts together, and now I'm able to determine what type of OLEDB connection I'll allow my user create, and I'm also able to perform all operations I need regardless of the Provider Architecture.
I hope this will benefit other people who might be having the issue.
If time (and NDA) allows, I'll get the code here for people to copy and try it later.
These links were also very useful on my research
http://blog.mattmags.com/2007/06/30/accessing-32-bit-dlls-from-64-bit-code/
Registering the DLL Server for Surrogate Activation
https: // msdn.microsoft.com/en-us/library/windows/desktop/ms686606(v=vs.85).aspx)
Writing Serviced Component
https: // msdn.microsoft.com/en-us/library/3x7357ez(VS.80).aspx)
How to: Create Serviced Component
https: // msdn.microsoft.com/en-us/library/ty17dz7h(VS.80).aspx)
Create Out-Of-Process COM in C#/.Net?http: // stackoverflow.com/questions/446417/create-out-of-process-com-in-c-net
Thanks everyone
D
My company has created several COM objects and they were using them happily from .NET. But now, our client wants to change to Java. I thought it would be interesting to use JACOB or j-interop (I'm not sure which of them) for some tasks, but the resultant code is pretty unmanageable. So I want to write a tool that can read the TypeLib of the COM library and then generate Java wrapper classes for hidding all those unmanageable code.
I'm a newbie in the COM world, so I don't know how to obtain the information about interfaces, methods and parameters that describe a COM object. I read about something called TypeLib, but I don't know how to read it. How can I obtain information from it?
The official API is available here: Type Description Interfaces.
You can use it from C++ directly but I suggest you use .NET (C# in my sample) with an extra tool that Microsoft has written long time ago (mine is dated 1997), named TLBINF32.DLL. It's also a COM object but is Automation (VBScript, Javascript, VB/VBA) and .NET compatible.
You can find TLBINF32.DLL googling for it (this link seems to work today: tlbinf32.dll download, make sure you get the .ZIP file, not what they call the "fixer"...). Note it's a 32-bit DLL so your program must be compiled as 32-bit to be able to use it. I don't know of any 64-bit version but how to use it a with 64-bit client is described here: tlbinf32.dll in a 64bits .Net application
How to use this library is explained in detail here in this december 2000 MSDN magazine's article: Inspect COM Components Using the TypeLib Information Object Library. It's VB (not .NET) oriented, but it's quite easy to translate in .NET terms.
Here is a sample console app in C# that just dumps all type info from a type lib (here MSHTML.TLB):
class Program
{
static void Main(string[] args)
{
TypeLibInfo tli = new TypeLibInfo();
tli.ContainingFile = #"c:\windows\system32\mshtml.tlb";
foreach (TypeInfo ti in tli.TypeInfos)
{
Console.WriteLine(ti.Name);
// etc...
}
}
}
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.
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
Is there a way in managed code to list the Modem/Telephony devices installed on the system?
If .Net does not have a way, could you point me in a direction?
WMI will contain all the information you need in the Win32_POTSModem class. In C# or .Net, you can utilize the System.Management namespace to query WMI.
Within .Net, you can use MgmtclassGen.EXE from the platform SDK to generate a class object representing the WMI class.
The command line would be like this:
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\mgmtclassgen.exe Win32_POTSModem /L CS /P c:\POTSModem\Win32_POTSModem.cs
and then you can use that in your code:
using System;
using System.Collections.Generic;
using System.Management;
using ROOT.CIMV2.Win32;
public class MyClass
{
public static void Main()
{
foreach (POTSModem modem in POTSModem.GetInstances()) {
Console.WriteLine(modem.Description);
}
}
}
Output looks like this:
ThinkPad Modem - Internal Modem
Speed: 56000
You also might want to take a look at this article: CodeProject: How To: (Almost) Everything In WMI via C# - Part 3: Hardware.. The author has created a simple class wrapper around WMI objects similar to MgmtclassGen.exe, but its all done for you.
Just some thoughts for future generations.
#Christopher_G_Lewis provided very good solution.
But before using WMI we have to check that Windows Management Instrumentation (WMI, service name Winmgmt) is working (how to do it?). Of course, MS recommends don't touch this service, because it's part of system stuff, but people switch it off sometimes.
Moreover, sometimes it may be helpful to check WMI version before using it.
If you want to get modems list which are connected at the moment, you can check out this solution. It works slowly, but shows all connected modems and excludes Null modem cables.