Delphi Anti Cheat (enable any disabled button) - delphi

In my application there are some buttons that I've disabled for a reason.
But these buttons are easily enabled by TNTEnforcer.
Is there any easy way to prevent this?
Tried to pack with some packer / obfuscator, but still can be enabled.
What is TNTEnforcer

VCL controls are backed by Win32 controls and these are inherently insecure. You cannot restrict access to their properties and state. External programs can readily modify state, press buttons etc.
You might be tempted to run a timer that resets the UI state at a high frequency. This might make it a little harder for a cracker. But still not particularly hard, and at what cost to your program and code?
So, in my view, you should not attempt to stop external programs interfering with the UI state. Instead you can add checks and defences to the OnClick handlers and other code behind the UI. This is perfectly crackable too, but it does at least require a little more effect from the cracker.
You might write:
button.Enabled := False;
button.OnClick := nil;
when you disable the button. When you re-enable it you could write:
button.Enabled := True;
button.OnClick := MyOnClickHandler;
That's a rather crude way to do it. It might be preferable to push the checking down the call chain, into the OnClick handler itself, or even better, further down into your business logic. That way, no matter how the code reaches the business logic, if it needs to be blocked it will be.

Unless the attacker has intimate knowledge of the inner workings of the particular version of the VCL that your app is using so that it can directly manipulate the VCL's internal memory, the best it can do is use standard Win32 APIs to manipulate the publicly accessible HWNDs of your app, such as by using EnableWindow() followed by BM_CLICK.
So one simple defense would be to remove the attack vector that you want to protect - in this case, by replacing TButton with TSpeedButton. TButton is a TWinControl descendant, so it has an HWND. TSpeedButton is a TGraphicControl descendant, so it does not have an HWND, and thus is not accessible to external processes because it is a custom drawn control managed exclusively by the VCL, not the OS.

If your application uses the traditional component TButton (from StdCtrls.pas), the button is a Windows standard control. Anyone, who knows the control handle, can access it. The attacker TNTEnforcer can iterate windows and find the button handle. After that, the malware can enable your button and simulate mouse clicks.
Solution 1: As disabled buttons are not clickable, my first idea is to intercept CM_ENABLECHANGED (David mentioned WS_DISABLE) messages, so that the malware is not able to change the button enable-state. The solution is similar to David's but over complicated. As David mentioned, we can remove the OnClick handler temporarily, when we intend to disable a button.
Solution 2: Another idea is to protect button handle from being searched. You might convert your traditional Vcl-based application to a cross-platform FireMonkey based application. Because the FMX draws components itself, the TNTEnforcer cannot attack in the old way at all. I have never done that before. The convert effort can be high.

Related

How to get enabled property of a control?

In Delphi it is possible to get the process name and class name of any control which is clicked system wide via windows api.
process name:
GetWindowThreadProcessId(Hwnd, ProcessId)
by process ID one can get to the process name
class name:
SetLength(ClassName, 255);
SetLength(ClassName, GetClassName(Hwnd, pchar(ClassName), 255));
Is there an easy way similar to the ones mentioned above to get a control's enabled property? (without using UIAutomation)
If you have the window handle for a control, then the IsWindowEnabled function will tell you whether it is enabled.
Keep in mind that that is acting on the window at the API level, not the Delphi VCL level. In Delphi, there can be controls that do not have window handles (anything that descends from TGraphicControl, which includes TLabel and TSpeedButton), so IsWindowEnabled obviously can't tell you anything about those controls.
Delphi does not provide any facility for querying information about arbitrary Delphi controls from other processes. If you need something like that, then you'll have to arrange for the external process to respond to commands of your choosing. That is, you will need to be in control of both programs so that you can put code in them both to cooperate.
If GetWindowThreadProcessId and GetClassName are already telling you the information you want, then IsWindowEnabled will work just fine because they all have the same limitation regarding Delphi VCL controls.

Firemonkey - Message Handling

I'm currently trying to develop a project based upon Firemonkey. I'm using Firemonkey for it's UI features as the project consists of many smaller applications, each with a 3D aspect to it. I'm currently only developing/deploying to Windows with the FMX framework, but may go cross-platform at a later date.
I've gotten around most issues I've come across by building a VCL Windows application in the background to perform a very specific action, and then building an FMX frontend. However, this is only suitable when you only want to execute the application to perform that action it's designed to do, and thus can execute the application with parameters. In one of the applications, i've come upon the need to use messages (or something similar). For example, in my FMX application, if i click "button1", i want it to send a message to the background VCL application to perform "action1", rather than execute it with parameters.
A good example could be using the VCL TMediaPlayer in the background application, with the front-end FMX application being used to display the information and provide control of play, pause, etc. Such that it essentially becomes an FMX UI with VCL ability.
I've so far been unable to find anything on how messages (e.g. in VCL, they'd be done with "SendMessage" or "PostMessage" or something similar) are handled with Firemonkey, either through the local help file, or through extensive Googling. Everything i've turned up has been related to email (presumably because of the word "Message" in most of my search terms).
Can anyone point me in the right direction on how messages would be handled with Firemonkey/FMX?
Regards,
Scott Pritchard
My understanding is that Firemonkey is not based on traditional windows, so sending window messages to Firemonkey controls is not usually an option. Although some controls do use windows (most notibly, TCommonCustomForm), so you can use the FmxHandleToHWND() function in the FMX.Platform.Win unit to extract an HWND from a TFmxHandle when needed. I have no clue how to receive and custom process window messages in FMX controls, if that is even possible.
Firemonkey under Windows has access to the Win32 API, so there should be nothing stopping you from sending window messages to other windowed controls, such as your VCL UI. Include the Winapi.Windows unit in your uses clause to access Win32 API functions, just like you would in a VCL application.
UPDATE: because FireMonkey does not expose access to messages that are sent to a Form's window, you have to manually subclass the window in order to receive messages before FireMonkey sees them. You can override the Form's CreateHandle() method, call the inherited method first to create the window, then use FmxHandleToHWND() to get the HWND that you can subclass. Be sure to also override the DestroyHandle() method to remove the subclass before then calling inherited to release the HWND.
Currently, FireMonkey doesn't have a message handler that you can use to send and post messages.
There is a possibility of hooking things up using listeners like FireMonkey works internally, but none of it is documented.
So, instead, here's what I've done:
I created my own custom "message" class. I create instances of the class and add them to a thread-safe list from any thread I need to. On the main thread, I have a timer that checks the list and processes the "messages".

How does Delphi's KeyPreview work?

A colleague and myself were debating over which way was less of a burden on the system resources. (Note: this is not the question I want an answer to. Rather the title and the line below in bold is the question I seek an answer for.)
1. Using KeyPreview to get the keypresses on a form.
or
2. Using defining an OnMessage procedure and handling it there.
At first glance it seems KeyPreview would be less of a system burden since defining an OnMessage procedure results in our program checking every message that comes in. Note messages we don't care about would cause it to jump out by the first if statement. That is at worst we would have an if statement executed for every message.
But we're wondering how Delphi deals with the KeyPreview property... We wonder if Delphi internally defines its own OnMessage and looks at the messages to then trigger the events that are related to keypresses.
If this is the case then would both approaches be about the same?
As others have already said - there is probably no noticeable difference.
I just wanted to point out an exellent article by Peter Below on that topic: A Key's Odyssey archive
This article describes the key message processing as implemented in Delphi 2007 for Win32 VCL forms applications. A few things have changed in this area compared with Delphi 7, but these are mostly additions that I will highlight when we get to them. Most of this code has survived basically unchanged since the times of Delphi 1, a tribute to the robustness of the design. If you are in a hurry or not interested in all the details you can refer to the outline in the summary for a condensed overview.
The KeyPreview functioning:
The KeyPreview property of the current active form is checked for the KeyUp-, KeyDown- and KeyPress- event handlers of the current active control. I.e.: a key press in any control results in the check of the form's KeyPreview property.
If that property is True, the event handler in question invokes the event handler of the form prior to that of itself. If the form's event handler does not change the key value to 0 (or #0, depending on KeyPress or KeyDown/KeyUp), then the active control's event handler takes back over, otherwise the event is considered handled.
Compared to Application.OnMessage:
So setting the key value to 0/#0 in a form's event handler is synonymous to setting the Handled parameter of Application.OnMessage. In this, there is virtually no difference. But since OnMessage is called very early in the dispatching process, there is a theoretical gain in performance because the message is not being dispatched any further. When you leave Handled to False, there is no difference at all, because the KeyPreview property is always checked, whether it is set or not.
The main difference that is left is that you have to set the KeyPreview of áll Forms to True, ánd implement and maintain for each of all forms the appropriate event handlers. Compare this to having just one event handler for Application.OnMessage. That is: assuming you could do with just one routine for all of your forms.
The best answer would be, measure it. Most likely neither one is going to place any noticeable "burden" on the system, and if you don't notice it when you're specifically looking for it, then your users won't either. So just go with whichever one's easier to understand in case you need to come back to that code sometime in the future.
The bottom line here is that you can't generate input quick enough to make the computer even notice. The computer would not be troubled if you produced input messages at rates hundreds or even thousands greater than you typically do.
You won't be able to measure the difference between handling something in OnMessage and using KeyPreview.
So the decision as to which to use comes down to which is most convenient. If you need handling to happen at an application wide level, and you don't have a common base class for all your forms, then you use OnMessage. If you want different behaviour for different forms then you need to use KeyPreview.
Personally I strongly recommend refactoring so that all forms in your projects derive from a common base (a subclass of TForm). This allows you much more flexibility. Done this way you can, for example, use the KeyPreview mechanism to apply intervention points for all forms in your applications.
As for how KeyPreview is implemented, the input messages get redirected in KeyDown, KeyPress etc. in TControl. To learn more read the source code.

Delphi, how to make independent windows

I have an application that uses tabs like the Chrome browser. Now I want to be able to open more forms and not be limited to only one form. These forms should act the same but if I close main form all forms are closed. How can I make all forms be equal, so no matter which form I close it only closes that form and not exit application before all forms are closed? Any ideas?
Image of my explorer
Kind Regards
Roy M Klever
It's not too hard to do this, though it starts getting complicated quickly depending on how complete you want it to be. Getting multiple modal dialogs to work independently is a ton of effort.
To start, you need to avoid Application.MainForm entirely. Always use Form := TMyForm.Create(Application) instead of Application.CreateForm(TMyForm, Form). The later sets MainForm and you never want that to happen.
To make things shut down properly you'll need to do something like this in your form's OnClose event handler:
if Screen.FormCount = 1 then
Application.Terminate;
CloseAction := caFree;
Application.Run relies on MainForm being assigned, so in your DPR replace that line with this loop:
repeat
try
Application.HandleMessage;
except
Application.HandleException(Application);
end;
until Application.Terminated;
There are a couple of ways to handle the taskbar entry.
Single taskbar entry: Set Application.MainFormOnTaskbar := False; and the hidden TApplication handle will be used. Clicking on the taskbar entry will bring all of the windows to the front. You'll need to override Application.OnMessage or add a TApplicationEvents component, and watch for WM_CLOSE with the Msg.Handle = Application.Handle`. In that case the user has right-clicked on the taskbar and selected Close, so you should close all the windows.
Multiple taskbar entries: Set Application.MainFormOntaskbar := True. Override your form's CreateParams method and set Params.WndParent := 0;. Each taskbar entry will control that form.
There are probably a few other gotchas, but that's the basics.
As I said, making ShowModal and TOpenDialog/TSaveDialog working independently, so it only affects its parent form and so multiple dialogs can be open at once, is a ton of work, and I can't really recommend it. If you're a masochist, here's the general steps:
Replace TCustomForm.ShowModal with a custom version. Among other things, that routine disables all the other windows in the application, so you need to replace the DisableTaskWindows/EnableTaskWindows calls with EnableWindow(Owner.Handle, False/True) to just disable the parent form. At this point you can open multiple dialogs, but they can only be closed in last-in, first-out order, because the calls end up being recursive. If that's fine, stop here.
There are two ways to work around that:
Rather than making ShowModal blocking, have StartModal and EndModal routines that have the first bit and last bit of ShowModal's code and call an OnShowModalDone event when the dialog is closed. This is kind of a pain to use, but is relatively easy to code and easy to make stable.
Use the Windows fiber routines to swap out the stack and start a new message loop. This approach is easy to use, because ShowModal is blocking, so you call it like normal. This is the approach we used in Beyond Compare. Don't do it. It's complicated to write, there will be stability issues for non-trivial applications because of incompatibilities with third party code (Windows global message hooks, TWebBrowser, .NET in shell extensions loaded by the browse dialog, etc), and if it's a cross-platform project, the Unix ucontext functions aren't safe to use either.
The common dialogs (TOpenDialog, TColorDialog, etc), have similar restrictions. To make them only disable the parent form you need to override TCommonDialog.TaskModalDialog and replace the DisableTaskWindows/EnableTaskWindows calls there too. They can't be made asynchronous like the regular Delphi dialogs above though, since they're blocking functions provided by Windows (GetOpenFileName, ChooseColor, etc). The only way to allow those to close in any order is to have each dialog run in a dedicated thread. Windows can handle most of the synchronization to do that, as long as you're careful about accessing the VCL objects, but it basically involves rewriting large portions of Dialogs.pas.
If you really want that,
1) use a small, maybe hidden, MainForm and launch just the first childform at startup.
2) launch separate applications instead of Windows in the same process. This is what later Office version use.
Here is a similar StackOverflow question:
Multiple app windows activation not working correctly
In my case I don't try to avoid the MainForm like Craig describes. Instead, I hide the main window and all of my real windows are other non-modal forms. I have been happy with how my application works, but Craig's approach may be simpler.
See my answer on the above question to see code samples for my approach and a few links with good background information.
The first form created in a Delphi application is treated as the main form and the application terminates when this form gets closed. The obvious solution is to have a first form that is not one that gets closed by the user but rather one that is not visible to the user and gets closed only when all other forms have been closed.
I have not tried this, but it should work.
This is too late to be an answer but I bumped into the same problem. The solution I opted for is to extract Application.ExeName and pass it to a function like createProcess or even shellExecute. So, now I have independent applications at the OS Level. I also needed different taskbar buttons for the different instances.

Delphi: What is Application.Handle?

What is TApplication.Handle?
Where does it come from?
Why does it exist?
And most importantly: why do all forms have it as their parent window handle?
The Delphi help says:
TApplication.Handle
Provides access to the window handle
of the main form (window) of the
application.
property Handle: HWND;
Description
Use Handle when calling Windows API
functions that require a parent window
handle. For example, a DLL that
displays its own top-level pop-up
windows needs a parent window to
display its windows in the
application. Using the Handle property
makes such windows part of the
application, so that they are
minimized, restored, enabled and
disabled with the application.
If I focus on the words "the window handle of the main form of the application", and I take that to mean the window handle of the main form of the application, then I can compare:
"the window handle of the main form of the application", with
the window handle of the MainForm of the Application
but they are not the same:
Application.MainForm.Handle: 11473728
Application.Handle: 11079574
So what is Application.Handle?
Where does it come from?
What Windows® window handle is it?
If it is the Windows® window handle of the Application's MainForm, then why don't they match?
If it's not the window handle of the Application's MainForm, then what is it?
More importantly: Why is it the ultimate parent owner of every form?
And most important: Why does everything go haywire if i try to have a form be unparented unowned (so i it can appear on the TaskBar), or try to use something like IProgressDialog?
Really what I'm asking is: What is the design rationale that makes Application.Handle exist? If I can understand the why, the how should become obvious.
Understanding through a game of twenty questions:
In talking about the solution of making a window appear on the taskbar by making its owner null, Peter Below in 2000 said:
This can cause some problems with modal forms shown from
secondary forms.
If the user switches away from the app while a modal
form is up, and then back to the form that showed it, the modal form may
hide beneath the form. It is possible to deal with this by making sure
the modal form is parented [sic; he meant owned] to the form that showed it (using
params.WndParent as above)
But this is not possible with the standard
dialogs from the Dialogs unit and exceptions, which need more effort to
get them to work right (basically handling Application.OnActivate,
looking for modal forms parented to Application via GetLastActivePopup
and bringing them to the top of the Z-order via SetWindowPos).
Why does a modal form end up stuck behind other forms?
What mechanism normally brings a modal form to the front, and why is it not functional here?
Windows® is responsible for showing windows stacked. What has gone wrong that Windows® isn't showing the right windows?
He also talked about using the new Windows extended style that forces a window to appear on the taskbar (when the normal rules of making it un-owned is insufficient, impractical, or undesirable), by adding the WS_EX_APPWINDOW extended style:
procedure TForm2.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams( params );
Params.ExStyle := Params.ExStyle or WS_EX_APPWINDOW;
end;
But then he cautions:
If you click on a secondary forms taskbar button while another app is
active this will still bring all the applications forms to front. If you
do not want that there is option
Who is bringing all the forms to the front when the form's owner is still Application.Handle. Is Application doing this? Why is it doing this? Rather than doing this, shouldn't it not be doing this? What is the downside of not doing this; I see the downside of doing it (system menu's don't work property, taskbar button thumbnails are inaccurate, Windows® shell cannot minimize windows.
In another post dealing with the Application, Mike Edenfield says that the parent window sends other window's their minimize, maximize and restore messages:
This will add the taskbar button for your form, but there are a few other minor details to
handle. Most obviously, your form still receives minimize/maximize that get sent to the parent
form (the main form of the application). In order to avoid this, you can install a message
handler for WM_SYSCOMMAND by adding a line such as:
procedure WMSysCommand(var Msg: TMessage); WM_SYSCOMMAND;
procedure TParentForm.WMSysCommand(var Msg: TMessage);
begin
if Msg.wParam = SC_MINIMIZE then
begin
// Send child windows message, don't
// send to windows with a taskbar button.
end;
end;
Note that this handler goes in the PARENT form of the one you want to behave independently of > the rest of the application, so as to avoid passing on the minimize message. You can add similar > code for SC_MAXIMIZE, SC_RESTORE, etc.
How is it that minimize/maximize/restore messages for my Windows® windows are not going to my window? Is this because messages destined for a window are sent, by Windows® to the window's owner? And in this case all the forms in a Delphi application are "owned" by Application? Does that not mean that making the owner null:
procedure TForm2.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.WndParent := 0; //NULL
end;
will remove Application and it's window Handle from interfering with my form, and Windows should once again send me my minimize/maximize/restore messages?
Perhaps if we compared and contrasted now a "normal" Windows application does things, with how Borland initially designed Delphi applications to do things - with respect to this Application object and it's main loop.
what solution was the Application object solving?
What change was made with later versions of Delphi so that these same issues don't exist?
Did the change in later versions of Delphi not introduce other problems, that the initial Application design tried so hard to solve?
How can those newer applications still function without Application interfering with them?
Obviously Borland realized the flaw in their initial design. What was their initial design, what problem was it solving, what is the flaw, what was the re-design, and how does it solve the problem?
The reason for the application window has a bit of a sordid history. When developing Delphi 1, we knew we wanted to use "SDI" (windows scattered all over the desktop) ui model for the IDE. We also knew that Windows sucked (and still does) at that model. However we also noticed that Visual Basic at that time employed that model and it seemed to work well. Upon further examination, we found that VB used a special "hidden" parking window which was used as the "owner" (Windows blurs the notion of parent and owner at times, but the distinction is similar to VCL) for all the other visible windows.
This is how we solved the "problem" where the windows containing the main menu was rarely ever focused so processing Alt-F for the File menu simply wouldn't work. By using this central parking window as an intermediary, we could more easily keep track of and route messages to the appropriate windows.
This arrangement also solved another issue where normally multiple top level windows were entirely independent. By making the application handle the "owner" of all these windows, they would all behave in concert. For instance, you may have noticed that when you select any of the application windows, all the application windows move to the front and retain their z-order relative to each other. This would also make the application minimize and restore as a functional grouping.
That is a consequence of using this model. We could have manually done all this work to keep things straight, but the design philosophy was to not re-invent Windows, but to leverage it where we could. That is also why a TButton or a TEdit is really a Windows "User" BUTTON and EDIT window class and style, respectively.
As Windows evolved, that "SDI" model began to fall out of favor. In fact Windows itself began to become "hostile" to that style of application. Starting with Windows Vista and continuing to 7, the user shell doesn't seem to work well with an application using a parking window. So, we set out to shuffle things around in VCL to eliminate the parking window and move its function into the main form. This presented several "chicken and egg" problems whereby we need to have the parking window available early enough in the application initialization so that other windows can "attach" to it, but the main form itself may not be constructed soon enough. TApplication has to jump through a few hoops to get this to work, and there have been a few subtle edge cases that have caused issue, but most of the problems have been worked out. However, for any application you move forward, it will remain using the older parking window model.
All VCL apps have a "hidden" top level window called Application. This is created automatically on application startup. Amongst other things it is the main windows message handler for VCL - hence Application.ProcessMessages.
Having the apps top level window hidden does cause some strange things, noticeably the incomplete system menu that shows in the task bar, and incorrect thumb nail windows in Vista. Later versions of Delphi correct this.
However, not all windows must have it as a parent, Windows just tends to work better if it is.
However, any form created with Application.CreateForm will have it as the parent, and it will also be owned by the Application object. As they are owned, they will be freed once Application is freed. This happen behind the scenes in Forms.DoneApplication
From looking at the source in forms.pas (Delphi 2009), it appears that they create a "master" window in win32 GUI apps to allow calls to
TApplication.Minimize
TApplication.Restore
etc
It appears that messages passed to the Application.Handle are forwarded as appropriate to the MainForm, if it exists. This would allow the app to respond to minimize, etc if the main window has not been created. By modifying the project source you can create a Delphi app without a main window.
In this case, the TApplication methods will still work, even if you haven't created a main window. Not sure if I'm grasping all of the purposes, but I don't have time to go through all of the TApplication code.
Per your questions:
Where does it come from? It is the handle of a window created in TApplication.Create
What windows handle is it? a fake window that every GUI Delphi app requires as part of the TApplication abstraction
Is it the windows handle of the application's main form No
If its not the handle of application's main form then what is it? See above
more importantly: why is it the ultimate parent of every form? assuming you're right that its the ultimate parent, i assume that it is so because it makes it easy to find all of forms in your application (enumerating the children of this "master" form).
and most important: why does everything go haywire if i try to have a form be unparented I think because the hidden "master" form is getting system messages that it should pass on to its children and/or the main form, but can't find the unparented form.
Anyway, that's my take on it. You can probably learn more by looking at the TApplication declaration and code in forms.pas. The bottom line from what i see is it is a convenient abstraction.

Resources