DLL injection and ejection from .NET Framework 4.8 app - c#

I'm injecting DLL into the WPF process using an Injector from snoop or Reloaded.Injector.
Injected DLL is .net 4.8 class library.
The injection works, but ejection - does not. My library is still locked by the target process after ejection. Is it possible to unload it at all?
I've tried FreeLibrary and FreeLibraryAndExitThread with no success. Reloaded.Injector Eject() function returns true, but DLL is still locked.
var process = Process.GetProcessesByName("ModsOptimizer").FirstOrDefault();
_injector = new Injector(process);
_injectionDllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Injection.dll");
var address = _injector.Inject(_injectionDllPath);
_injector.CallFunction(_injectionDllPath, "Spam", default);
_injector.Eject(_injectionDllPath);

Related

Does SevenZipSharp work with .NETCore on Windows?

I have a .NETCore app which I am trying to add 7 zip functionality to.
Compiling gives this warning:
warning NU1701: Package 'SevenZipSharp 0.64.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework 'net5.0'. This package may not be fully compatible with your project.
So I presume the project is .NETCore v5.0. Can I run SevenZipSharp in this project?
Running the app gives an error at the call to CompressFiles: SevenZip.SevenZipLibraryException: 'Can not load 7-zip library or internal COM error! Message: failed to load library.'
public void ZipQOB(string sevenZipDllPath, string zippedQobPath, string unzippedQobFiles)//List<string> sourceFiles)
{
// throw exception if paths passed in are null, does 7zipsharp throw exceptions in this case?
try
{
if (System.IO.File.Exists(sevenZipDllPath) && System.IO.Directory.Exists(zippedQobPath))// && System.IO.Directory.Exists(unzippedQOBFiles))
{
string path = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "7z.dll");
//SevenZipCompressor.SetLibraryPath(sevenZipDllPath);
SevenZipCompressor.SetLibraryPath(path);
SevenZipCompressor sevenZipCompressor = new()
{
CompressionLevel = SevenZip.CompressionLevel.Ultra,
CompressionMethod = CompressionMethod.Lzma
};
string[] files = System.IO.Directory.GetFiles(unzippedQobFiles);
sevenZipCompressor.CompressFiles(zippedQobPath + #"\zip.QOB", files);
//System.IO.Path.ChangeExtension(zippedQobPath, ".QOB");
}
This question How do I use 7zip in a .NET Core app running on Linux? mentions a CLI wrapper ported from .NET Framework to .NET Core, but I can't find any details - is this something I would have to write and how?
I have already tried things suggested elsewhere, I altered the project build setting to:
Platform Target = AnyCPU,
ticked Prefer 32-bit
Should I just look at a different option as this page seems lists some stating .netcore compatible: https://github.com/topics/7zip?l=c%23
Many thanks for any help :)

How to instantiate a ComVisible class in a .NET Core assembly from .NET Framework application?

We have a software product that is currently released that is a .NET Framework 4.7.2 application (the "legacy" app). The legacy client-server implementation is built on System.Runtime.Remoting, which is not supported in .NET 5 and later, so the .NET 5 implementation is gRPC.
It is necessary to instantiate each of the two COM servers in turn because the legacy and the .NET 5 COM servers can only connect to the comm (not COM) server application that implements the same communications framework, which are System.Runtime.Remoting and gRPC, respectively.
The COM servers are used by third party applications to interface with the comm server application, so I am currently working on creating a static class that returns the interface from the COM server that can connect to the currently running instance of the comm server.
I have a .NET 5 WPF implementation of the product almost complete, but I've hit a roadblock in that, I am unable to register the .NET COM server.
I found these two articles:
Exposing .NET Core Components to COM
GitHub Issue
I have now been able to:
Create a Type Library
I found a comment from #SimonMourier suggesting copying the .NET 5 COM server code into a .NET Framework project and use RegAsm to export the type library to be used in the .NET 5 project. The type library was added to the .NET 5 COM server project folder and "" was added to an ItemGroup in the .csproj file per the first referenced article.
Register the .NET 5 COM server
This required using the "dotnet publish -r win-x64 -c Debug" command in the project folder from the Visual Studio Developer Command Line. I was then able to use regsvr32 to register the WinCalRemoting.comhost.dll in the "bin\Debug\net5.0\win-x64\publish" project directory.
Create an Instance of the COM Class
After registering the COM server, I am now able to create an instance of the COM class, but haven't been successful at getting the interface from it:
public static IWinCalClient LoadCompatibleRemotingClient(bool useClientEventWindow, string serverName, int serverPort, bool connectToServer = true)
{
UseClientEventWindow = useClientEventWindow;
WinCalServerName = serverName;
WinCalServerPort = serverPort;
ClassIdList = new Guid[]
{
LegacyWinCalClientClsId, // CAN'T GET INTERFACE FROM THIS COM SERVER
//WinCal5ClientClsId // THE .NET 5 COM SERVER WORKS
};
if (RemotingClassObject != null)
{
UnloadClient();
}
foreach (Guid clsId in ClassIdList)
{
try
{
RemotingClassObject = Activator.CreateInstance(Type.GetTypeFromCLSID(clsId, true));
}
catch (Exception e)
{
continue;
}
if (RemotingClassObject != null)
{
RemotingInterface = (IWinCalClient)RemotingClassObject;
if (RemotingInterface == null)
{
UnloadClient();
continue;
}
if (CanClientConnect(_RemotingInterface, connectToServer))
{
break;
}
}
if (Marshal.IsComObject(RemotingClassObject))
{
Marshal.FinalReleaseComObject(RemotingClassObject);
}
RemotingClassObject = null;
}
return RemotingInterface;
}
Update on the exception
After correcting the "bitness" of the test COM Client application that #SimonMourier clued me to, I am able to get the interface from the .NET 5 COM server. I have updated the code from the method.
HOWEVER, I'm now struggling with getting the interface from the .NET Framework COM server in the same way I get it from the .NET 5 COM server. I successfully register it using RegAsm.exe, but I get the following exception:
System.InvalidCastException: 'Unable to cast object of type 'CMI.WinCalRemoting.cWinCalClient' to type 'CMI.WinCalRemoting.IWinCalClient'.'.
I've done an exhaustive search to try to find out how to fix the .NET Framework COM project so that it can be used in the same way that the .NET 5 COM server is used so that it doesn't matter whether the COM client is a .NET Framework or a .NET Core assembly.
I added a .NET Framework COM server project to the shared directory below to replicate what I'm seeing. With the .NET Framework COM server.
I also switched the test application to be 32-bit to replicate how our sister application will be using the COM servers.
All of the projects are located here:
.NET 5 COM Interop
Unable to Add .NET Framework COM Type Library Reference
For a .NET Framework client assembly, I've attempted to add a reference to the .NET Framework COM server that was registered with regasm.exe, but that fails with the following message:

.Net Core Worker Service cannot find log4net.config when it runs as a windows service

I have these projects in my solution:
.Net Core 3.1 Worker Service
.Net Core 3.1 Class library - for configure the log4net
But my log4net.config file is inside my worker service project. When I'm debugging, it is logging to the file which is configured in the log4net.config.
But when I install the Worker Service as a Windows service, it doesn't log to the file.
And when I checked the log4net.config location it has these values:
When debugging: D:\myrepos\webapicore\Development\Message.Consumer\log4net.config
When running as a service: C:\WINDOWS\system32\log4net.config
So I believe, since the log4net.config is not available in C:\WINDOWS\system32\ it cannot do the logging.
UPDATE:
I'm using following code to retrieve the log4net.config
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
Any idea to solve this?
Thanks.
I have installed and configured log4net in a different class library.
So when I was getting the Assembly.GetEntryAssembly() it was actually not giving the assembly location of where log4net has been installed.
Therefore I changed the this code part:
var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
Into:
var dirname = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
XmlConfigurator.Configure(new FileInfo(string.Format("{0}{1}", dirname, #"\log4net.config")));
This worked for me.
This worked for me too with my .NET 5 WorkerService.
You could also use AppDomain.CurrentDomain.BaseDirectory, instead.
However, I then found out that you can simply create an AssemblyInfo.cs file (Add new item ...) and add
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
Just like before with .NET Framework 4.5, etc.

Unable to configure 'IApplicationBuilder UseOwin'

As stated in official document, I am trying to implement UseOwin in the Startup.cs.I am trying to use/port IAppBuilder (Microsoft.Owin.Builder.AppBuilder) inside IApplicationBuilder (Microsoft.AspNetCore.Builder.IApplicationBuilder). I had legacy code written using IAppBuilder running fine on .Net Framework 4.5.
I have seen couple of examples about using IAppBuilder in IAplicationBuilder e.g. example 1 example 2. These attempts were about .netcore 1.1 and not .net core 2.0. May be this is the reason i am unable to port.
Please share your thoughts whether i am trying to achieve something not possible at the moment in .net core 2.0 or there is some error in my code.
Note:
I am using dotnetcore 2.0 with Visual Studio 2017
Error
I am getting following error.
return owinAppBuilder.Build,
Task>>(); TypeLoadException: Could not load type
'System.Security.Cryptography.DpapiDataProtector' from assembly
'System.Security, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'.
My attempt
app.UseOwin(setup => setup(next =>
{
var owinAppBuilder = new AppBuilder();
var aspNetCoreLifetime =
(IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));
new AppProperties(owinAppBuilder.Properties)
{
OnAppDisposing = aspNetCoreLifetime?.ApplicationStopping ?? CancellationToken.None,
DefaultApp = next,
AppName = "test"
};
// Only required if CORS is used, configure it as you wish
var corsPolicy = new System.Web.Cors.CorsPolicy
{
AllowAnyHeader = true,
AllowAnyMethod = true,
AllowAnyOrigin = true,
SupportsCredentials = true
};
//corsPolicy.GetType()
// .GetProperty(nameof(corsPolicy.ExposedHeaders))
// .SetValue(corsPolicy, tusdotnet.Helpers.CorsHelper.GetExposedHeaders());
owinAppBuilder.UseCors(new Microsoft.Owin.Cors.CorsOptions
{
PolicyProvider = new CorsPolicyProvider
{
PolicyResolver = context => Task.FromResult(corsPolicy)
}
});
PublicClientId = "self";
OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new Microsoft.Owin.PathString("/Login"),
Provider = new MyServiceProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
AllowInsecureHttp = true,
RefreshTokenProvider = new MyRefreshTokenProvider(),
};
owinAppBuilder.UseOAuthBearerTokens(OAuthOptions);
//owinAppBuilder.UseTus(context => new DefaultTusConfiguration
//{
// // Excluded for brevity, use the same configuration as you would normally do
//});
return owinAppBuilder.Build<Func<IDictionary<string, object>, Task>>();
}));
Microsoft.Owin and related packages do not have targets for .NET Core, no for .NET Standard. All they have is dlls targeting full .NET. You can reference such libraries from your project targeting .NET Core, but they are not guaranteed to work, as you see yourself, because API (set of classes\methods\signatures) of full .NET and .NET Core are different. Visual Studio even will show a warning when you are doing that, for example:
Package 'Microsoft.Owin 3.1.0' was restored using
'.NETFramework,Version=v4.6.1' instead of the project target framework
'.NETCoreApp,Version=v2.0'. This package may not be fully compatible
with your project.
There is Microsoft.AspNetCore.Owin package and you can use OWIN middleware in .NET Core app as your first link describes, but almost all it provides is UseOwin extension method. There is no AppBuilder type there and so on, and there are no Microsoft.AspNetCore.Owin.Cors packages or similar. So you have to either implement all that yourself (no reason to, because you can use the same functionality provided by asp.net core framework) or wait for OWIN packages that target .NET Standard\Core and do that (didn't check, maybe they even exist already).
So, your code uses packages which are indeed not compatible with your target framework, as exception you have at runtime shows. So another answer (for some reason downvoted) is technically correct.
If you still want to use those packages reliably - you need to target full .NET Framework and not .NET Core. To do that, open your .csproj file and change
<TargetFramework>netcoreapp2.0</TargetFramework>
To some .NET framework version that supports .NET Standard 2.0, for example:
<TargetFramework>net47</TargetFramework>
Then go to nuget package manager and, if you have microsoft.aspnetcore.all package (or other packages targeting .NET Core) - uninstall it, you don't need it anyway. Then install Microsoft.AspNetCore package and all other asp.net core packages you need (if not installed already). Rebuild, run and it will work just fine.
That works because all (most?) AspNetCore packages target .NET Standard, not .NET Core, and you can use them in projects targeting full .NET Framework.
Note that by doing that you have asp.net Core project, but not on .NET Core, with all consequences that come from that (cannot run with dotnet run, on linux need to run with mono, and so on).
The Microsoft.Owin components will not work on dotnet core 2.0, they only work on .NET 4.5+

Castle.Windsor instantiating wrong version of SqlConnection with Dapper

We're having a weird problem when using Castle.Windsor to instantiate an SqlConnection using a typed factory:
The registration looks like this:
container.Register(Component.For<IDbConnectionFactory>().AsFactory().LifestyleTransient());
container.Register(Component.For<IDbConnection>().ImplementedBy<SqlConnection>()
.LifestyleTransient()
.DependsOn(Dependency.OnValue<string>
(ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString)));
And the IDbConnectionFactory:
public interface IDbConnectionFactory
{
IDbConnection Create();
void Release();
}
Now, when I try to access a new connection using this code:
using (var connection = _connectionFactory.Create())
{
}
I get an exception:
An unhandled exception of type
'Castle.MicroKernel.ComponentActivator.ComponentActivatorException' occurred
in Castle.Windsor.dll
Additional information: Error setting property SqlConnection.AccessToken in component
System.Data.SqlClient.SqlConnection. See inner exception for more information.
If you don't want Windsor to set this property you can do it by either decorating it
with DoNotWireAttribute or via registration API.
Alternatively consider making the setter non-public.
The problem with this Exception is that the type SqlConnection in System.Data for .NET 4.5.1 does not contain the property AccessToken whereas the one in .NET 4.6 does. In other words, if I try to manually do
var connection = new SqlConnection("connectionstring");
connection.AccessToken = "";
I get a build-error if the project is configured for .NET 4.5.1, but a runtime error on setting the AccessToken if it's configured for .NET 4.6.
Any idea why Castle.Windsor attempts to create a v4.6 SqlConnection instead of a .NET 4.5.1?
Workaround/Hack
I can get around the problem by telling Castle to ignore the property, but this seems like a hack. Doing this requires me to add it to the PropertiesIgnore in the registration:
container.Register(Component.For<IDbConnection>().ImplementedBy<SqlConnection>()
.PropertiesIgnore(info => info.Name.Equals("AccessToken"))
.LifestyleTransient()
.DependsOn(Dependency.OnValue<string>
(ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString)));
All .NET versions since 4.5 are in place updates
as you can see here.
This means that once you have installed .NET 4.6 you will always get the .NET 4.6 version of SqlConnection regardless of how you instantiate it.
When building your application in Visual Studio you build against a specific version of the .NET framework typically located in a folder under:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework
This means that when building msbuild can check that you are not using something which isn't available in the framework version you are targeting.
However when you run your 64 bit application it will use the assemblies typically located in C:\Windows\Microsoft.NET\Framework64\v4.0.30319
This is the same folder for all versions from .NET 4.0 through .NET 4.6, this is what in place upgrade means.
So when you execute your application on your developement environment that has .NET 4.6 installed, you will always get the .NET 4.6 version (at least unless you do something special to load other versions of the assemblies).
Castle Windsor will try to set properties with public setter and it will use reflection to find the properties which means that it will find the .NET 4.6 properties on a .NET 4.6 machine, even if you are building against 4.5.1.
The reason it fails when it tries to set the AccessToken is most likely because your connection string is not compatible with setting AccessToken.
If you check the source code of the AccessToken setter you will see that it will throw an exception if you try to set it for a incompatible connection string, even if you only try to set the AccessToken to the empty string.
As you don't need to inject any dependencies into the SqlConnection object you may as well create it simply using the new operator and then you avoid the problem caused by Windsors attempts to inject the properties of the connection.
Using this registration should work:
container.Register(Component.For<IDbConnection>().ImplementedBy<SqlConnection>()
.LifestyleTransient()
.UsingFactoryMethod(() => new SqlConnection
(ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString)));

Categories

Resources