How to programmatically detect VB.NET obfuscation? - vb.net

I am using ConfuserEx to obfuscate my program before release, I want the program to show a warning if it is being run without obfuscation. So as to reduce the chance of a non obfuscated executable being shipped.
So at runtime I want a function which returns true/false depending if obfuscation has been applied.

I can see two ways of doing it.
If the obfuscation process you use is part of the release build and therefore your release build has embedded instructions for the obfuscation part, you could do something like that.
AppValidator.Validate()
The validation will validate it is a release version or if not, that the application is run for allowed users (dev. team for instance).
I also added a way to validate by commandline calling Myapp.exe validate
However. this does not validated obfuscation per see, it validates the application is in Release mode.
Your obfuscator, if embedded with the release build, should fails if he cannot obfuscate release version or the premise for this validation is not good.
Public Class AppValidator
#If DEBUG Then
Private Shared ReadOnly IsDebugVersion As Boolean = True
#Else
private Shared ReadOnly IsDebugVersion As Boolean = False
#End If
Private Shared ReadOnly ISValidUser As Boolean = ValidateDevUser()
''' <summary>
''' Validate the user is authorized to run the program as
''' </summary>
''' <returns></returns>
Private Shared Function ValidateDevUser() As Boolean
Try
' Custom validation to determine if used in dev. environment such
'as validating username and domain name or checking agains Dev. Registry key
Catch ex As Exception
Return False
End Try
Return True
End Function
Public Shared Function Validate() As Boolean
Dim Args = Environment.GetCommandLineArgs
Dim ConsoleValidate As Boolean = Args.Count = 2 AndAlso String.Compare(Args(1), "validate") = 0
If IsDebugVersion Then
If ConsoleValidate Then
Console.WriteLine(Not IsDebugVersion)
Application.Current.Shutdown()
Return False
End If
If Not ValidateDevUser() Then
MessageBox.Show("Access Denied")
Application.Current.Shutdown()
Return False
End If
End If
Return True
End Function
End Class
The first solution is best if you can be sure that build will fails if release version produced and obfuscator steps fails.
If you cannot be sure of that, you can maybe take a look at
Obfuscation checker, from Red-gate, which is free and has a command-line and do exactly what you seek in a direct approach.

You could use something like ILSpy and have it run automatically after build with WM_COPYDATA API arguments, like so:
https://github.com/icsharpcode/ILSpy/blob/master/doc/Command%20Line.txt
Have it navigate to a type name that should be obfuscated; if it fails, you know obfuscation succeeded.

Related

Could not load file or assembly 32 bit assembly

I have been searching and trying for many hours. I am having 'System.BadImageFormatException' when running my WCF service hosted on IIS 10.0 from 64-bit client application.
- I tried to set Enable 32 bit applications = true .
- I checked that target CPU = Any CPU .
- I double checked on the applicationHost.config file on the <ApplicationPools> section and make sure that Enable 32 bit applications = true .
All these attempts with same result, the same error message:
Could not load file or assembly 'DBConnNET4, Version=1.0.34.0,
Culture=neutral, PublicKeyToken=60d47e8c3d6f39e7' or one of its
dependencies. An attempt was made to load a program with an incorrect
format.
When debugging, I am getting the exception inside class from the referenced library, exactly here:
Public Class BusinessObject
Private Function Invoke()
Dim obj As new BusinessObject()
obj.ctrlQueryRun()
End Function
Private Function ctrlQueryRun() As Short
Try
'*** the exception occurs at this line, GetAllItems() is function in the same class
If Me.GetAllItems() = cERROR Then Return cERROR
'' Some code Here
Catch ex As Exception
Return cERROR
End Try
Return cSUCCESS
End Function
End Class
All the solutions I found on the Internet were telling to do the previous attempts, any other suggestions? Is there any thing I forgot to check? Many thanks in advance for anyone helping or trying to help.

Run vb.net code directly from cmd or Visual Studio

I'm starting to code with vb.net and i need to run the code directly, like it happens with java: in the cmd i can run the class files. Is there any similar possibility with vb.net, preferably directly from the visual studio hub?
Thanks!
You can use the Immediate Window for that. It offers many different ways to interact with your code. To use it, start your application in debug mode from Visual Studio and press CTRL + ALT + I.
To execute a shared method you can type in the Immediate Window:
className.methodName()
(example)
MainFunctions.DoStuff()
DoMoreStuff()
Where className is optional if you're currently already inside the class (for example if you've hit a breakpoint in it).
If you want to execute an instance (non-shared) method you can either use the method above (without className, but you must currently be inside the class by hitting a breakpoint, for example), or you create a new instance of the class and execute the method:
Public Class MiscFunctions
Public Sub PrintHelloWorld()
Debug.WriteLine("Hello World!")
End Sub
End Class
(Immediate Window)
New MiscFunctions().PrintHelloWorld()
Hello World!
Dim m As New MiscFunctions
m.PrintHelloWorld()
Hello World!
You can also print the value of a variable or the return value of a function by typing:
? variableOrFunctionNameHere
(example)
? ImageCount
4
The same rules for executing methods applies to evaluating functions too:
Public Class MiscFunctions
Public Shared Function IsEven(ByVal Num As Integer) As Boolean
Return Num Mod 2 = 0
End Function
Public Function Sum(ByVal a As Integer, ByVal b As Integer) As Integer 'Non-shared method.
Return a + b
End Function
End Class
(Immediate Window)
? MiscFunctions.IsEven(3)
False
? MiscFunctions.IsEven(8)
True
? New MiscFunctions().Sum(3, 9)
12
You can also dynamically evaluate expressions:
? ImageCount + 1 = 5 'Here, ImageCount is 4
True
? 2 * 4
8
if you are looking for more then the Immediate Window. Look into Microsoft CodeDom. I have used it to compile C#, VB.net, C++, and Visual J#.
https://msdn.microsoft.com/en-us/library/y2k85ax6(v=vs.110).aspx

How to open a form within non-GUI code in VB.NET

I write a program in Visual Basic, which doesn't need - and doesn't have - a GUI unless a certain event happens, in which the user needs to be involved (and a MsgBox wouldn't suffice).
Now I want to call a form (which I have already created in the project) from my code. So I want to call
Public Class MyForm
{...} 'In my case empty
End Class
from within
Module MyMain
{...} 'do unrelated stuff
'Call MyForm somehow
{...} 'proceed stuff, knowing users input
End Module
I see the form for a very brief moment, but I can't get my program to halt and wait for me, while I am in the form.
The code in my desperation is:
Module MyMain
{...} 'do unrelated stuff
Dim wifo As New MyForm()
wifo.Show()
wifo.Visible = True
wifo.Activate()
wifo.Focus()
{...} 'proceed stuff, knowing users input
End Module
How does one do it?
If I understand you correctly, you want the Form.ShowDialog() method...
https://msdn.microsoft.com/en-us/library/c7ykbedk(v=vs.110).aspx

Key input functions for a VB class file

I am working on a little framework and I want to have a class file that contains functions I can run to check if a certain key has been pressed so other events can be run. The only code I have found online for similar things are written into the form itself and use something like "Handles Me.KeyPress". However, this handle function can't be used in a class file.
Public Function OnKeyPress(KeyToCheck As Keys)
If KeyPressed = KeyToCheck then
return true
else
return false
End If
End Function
I have tried:
Public Function OnKeyPress(KeyToCheck As Keys)Handles Formname.Keypress
If KeyPressed = KeyToCheck then
return true
else
return false
End If
End Function
However, this does not work. Any suggestions or work arounds would be greatly appreciated.
To get keyboard input, you need to have a window. All input goes to a window, and that window can then check for key presses that are sent to it.
To get global information, you'd need to install a hook, but those should generally be avoided.

Can I dynamically call a local function?

I have a module that looks like this. I've simplified it greatly so as not to clutter up my question (my local functions are more complex than this). Here is my code:
decision = {}
function win(win_arg) return win_arg end
function lose(lose_arg) return lose_arg end
local function draw(draw_arg) return draw_arg end
function decision.get_decision(func, arg)
return func(arg)
end
return decision
I am calling my module with the code below.
my = require "my-lua-script"
print(my.get_decision(lose, "I lose."))
print(my.get_decision(win, "I win."))
I want 'get_decision' to be a public method. I want win, lose and draw to be private, but I want to call them dynamically from get_decision. If I understand correctly, win and lose are in the global namespace right now? If I put a local in front of these two methods (like draw) then my code doesn't work.
Is there a way to accomplish what I am after?
Of course.
my-script.lua
-- This is the local side of the module.
local outcomes = {}
function outcomes.win(arg) return arg end
function outcomes.lose(arg) return arg end
function outcomes.draw(arg) return arg end
-- This is the exposed side of the module.
local M = {}
function M.get_decision(outcome, arg)
return outcomes[outcome](arg)
end
return M
main.lua
local my = require'my-script'
print(my.get_decision('win', 'I win.'))
print(my.get_decision('lose', 'I lose.'))
You simply use a string to indicate which function you'd like to access, and use that string to index a table of functions from within get_decision against outcomes. This will keep the functions hidden behind get_decision.