Advertisement

04.05.2008 at 05:02PM PDT, ID: 23298918
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

Get Filename from Handle, DLL issue.....Again(Sorry ciuly =P)

Tags: Delphi, Pascal
Ok, I'm back at square one.

I have a dll.
It is injected into an exe application.
It hooks ReadProcessMemory, WriteProcessMemory, and OpenProcess.
When each of the call backs is called it logs the API call and modifies it if necessary.
In the program that injects the dll into the exe, there is a verbose option you can select.
One of the attributes of the verbose option is to specify the file name of that handle that is passes along with the called API's.
This error was surmised to be caused by incorrect Access by OpenProcess. I did a hook on that and forced the correct Access.

The problem is still standing, so I put a debug log in the dll. I'll attach the log with and without verbose enabled.(Please note that the log isn't cut off in the enabled version. Thats just where it ended.)

Now IsVerbose right now only does one thing. It is a boolean value that is set when the dll is attached.
The code snippet below is the part that gets called when IsVerbose is enabled. The only thing different from when it is not enabled is: "'[' + GetNameFromHandle(Handle) + '] ' + ".

In the second part of the snippet I have included the GetNameFromHandle function. You should note that in the log where IsVerbose is enabled, and the only time GetNameFromHandle is called, you only get one of the debug logs: "4/5/2008 4:50:55 PM: GetNameFromHandle called. Handle=1900".

My guess would be that the problem lies here:

  Try
    Buffer := AllocMem(MAX_PATH + 1);
    Try
      If ((GetModuleFileNameEx(Handle,0,Buffer,MAX_PATH) = 0) And (GetLastError > 0)) Or ((GetModuleBaseName(Handle,0,Buffer,MAX_PATH) = 0) And (GetLastError > 0)) Then

My question to all the experts here is why?
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
//////////////////////////////////////////////////////////////////////
    If IsVerbose Then
      begin
      pBuffer := '[' + GetNameFromHandle(Handle) + '] ' + 'Write Memory(0x' + IntToHex(Integer(BaseAddress),8) + '): ' + BufferToHex(PChar(Copy(tBuffer,1,cbWrite))) + ' | ByteCount: ' + IntToStr(cbWrite);
      {$IFDEF Debug}
      Log('pBuffer: ' + pBuffer);
      {$ENDIF}
    end
/////////////////////////////////////////////////////////////////////
 
function GetNameFromHandle(Handle : THandle): String;
var
  Buffer : PChar;
begin
  Result:='';
  {$IFDEF Debug}
  Log('GetNameFromHandle called. Handle=' + IntToStr(Handle));
  {$ENDIF}
  If Handle = 0 Then
    begin
    Exit;
  end;
  Try
    Buffer := AllocMem(MAX_PATH + 1);
    Try
      If ((GetModuleFileNameEx(Handle,0,Buffer,MAX_PATH) = 0) And (GetLastError > 0)) Or ((GetModuleBaseName(Handle,0,Buffer,MAX_PATH) = 0) And (GetLastError > 0)) Then
        begin
        Result := '';
        {$IFDEF Debug}
        Log('Error at GetNameFromHandle. Error Code=' + IntToStr(GetLastError));
        {$ENDIF}
      end
      Else
        begin
        Result := Buffer;
        {$IFDEF Debug}
        Log('End of GetNameFromHandle. Result=' + Buffer);
        {$ENDIF}
      end;
    Finally
      FreeMem(Buffer);
    end;
  Finally
  end;
  {$IFDEF Debug}
  Log('End of GetNameFromHandle');
  {$ENDIF}
end;
Attachments:
 
Log with verbose enabled.
 
 
Log with verbose disabled.
 
Start your free trial to view this solution
Question Stats
Zone: Programming
Question Asked By: ThievingSix
Solution Provided By: ciuly
Participating Experts: 2
Solution Grade: A
Views: 5
Translate:
Loading Advertisement...
04.07.2008 at 03:02AM PDT, ID: 21295458

Rank: Master

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.07.2008 at 09:35AM PDT, ID: 21298468

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.08.2008 at 01:03AM PDT, ID: 21303272

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.08.2008 at 01:06AM PDT, ID: 21303288

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.08.2008 at 01:08AM PDT, ID: 21303298

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
05.05.2008 at 03:25AM PDT, ID: 21498983

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
05.05.2008 at 10:56AM PDT, ID: 21501705

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
05.05.2008 at 11:55AM PDT, ID: 21502140

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
05.05.2008 at 01:30PM PDT, ID: 21502735

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
05.06.2008 at 06:26AM PDT, ID: 21507064

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
05.16.2008 at 07:07PM PDT, ID: 21587731

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
05.17.2008 at 12:41AM PDT, ID: 21588307

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
 
Loading Advertisement...
Microsoft
  • Internet Protocols
  • Applications
  • Development
  • OS
  • Hardware
  • Windows Security
Apple
  • Operating Systems
  • Hardware
  • Programming
  • Networking
  • Software
Internet
  • Search Engines
  • File Sharing
  • WebTrends / Stats
  • Spy / Ad Blockers
  • Web Browsers
  • New Net Users
  • Web Development
  • Chat / IM
  • Anti Spam
  • Web Servers
  • Anti-Virus
  • Email Clients
Gamers
  • Tips
  • Online / MMORPG
  • Puzzle
  • Emulators
  • Action / Adventure
  • Role Playing
  • Consoles
  • Game Programming
  • Strategy
  • Sports
  • Misc
  • Computer Games
Digital Living
  • Hardware
  • Automotive
  • New Net Users
  • New Users
  • Software
  • Digital Music
  • Gaming World
  • Home Security
  • Apple
  • Networking Hardware
Virus & Spyware
  • Vulnerabilities
  • IDS
  • Encryption
  • Anti-Virus
  • Operating Systems Security
  • Software Firewalls
  • WebApplications
  • Cell Phones
  • Operating Systems
  • Internet
  • Hardware Firewalls
Hardware
  • Displays / Monitors
  • Handhelds / PDAs
  • Components
  • Peripherals
  • Laptops/Notebooks
  • Servers
  • Misc
  • Apple
  • Embedded Hardware
  • Networking Hardware
  • Storage
  • Desktops
  • New Users
Software
  • System Utilities
  • Industry Specific
  • Network Management
  • Photos / Graphics
  • Page Layout
  • VMware
  • Misc
  • Web Development
  • OS
  • CYGWIN
  • Voice Recognition
  • Virtualization
  • Message Queue
  • Quality Assurance
  • Security
  • Firewalls
  • MultiMedia Applications
  • Development
  • Database
  • Office / Productivity
  • Business Management
  • OS/2 Apps
  • Server Software
  • Internet / Email
ITPro
  • OS
  • Storage
  • Encryption
  • Operating Systems Security
  • Apple Hardware
  • Laptops & Notebooks
  • Servers
  • Networking Hardware
  • Peripherals
  • Devices
  • Displays / Monitors
  • WebTrends / Stats
  • Search Engines
  • Firewalls
  • Web Computing
  • WebApplications
  • IDS
  • Vulnerabilities
  • Email Clients
  • File Sharing
  • Spy / Ad Blockers
  • Web Browsers
  • Web Servers
  • Networking
  • Anti-Virus
  • Consulting
  • Chat / IM
  • Anti Spam
Developer
  • Web Servers
  • Web Browsers
  • Game Programming
  • Dev Tools
  • Industry Specific
  • Office / Productivity
  • Database
  • CYGWIN
  • Web Development
  • Search Engines
  • File Sharing
  • WebTrends / Stats
  • Programming
  • Content Management
  • Application Servers
  • Protocols
Storage
  • Removable Backup Media
  • Storage Technology
  • Servers
  • Grid
  • Remote Access
  • Backup / Restore
  • Misc
  • Hard Drives
OS
  • Miscellaneous
  • Security
  • Development
  • Linux
  • VMware
  • MainFrame OS
  • Unix
  • Apple
  • OS / 2
  • AS / 400
  • BeOS
  • Microsoft
  • VMS / OpenVMS
Database
  • Oracle
  • Miscellaneous
  • MySQL
  • Software
  • Sybase
  • Contact Management
  • PostgreSQL
  • Data Manipulation
  • Clarion
  • InterSystems Cache
  • Siebel
  • MUMPS
  • OLAP
  • SQLBase
  • SAS
  • GIS & GPS
  • 4GL
  • Berkeley DB
  • DB2
  • Informix
  • Interbase / Firebird
  • FoxPro
  • Reporting
  • LDAP
  • Filemaker Pro
  • MS SQL Server
  • dBase
  • MS Access
Security
  • Misc
  • Web Browsers
  • Software Firewalls
  • Operating Systems Security
  • File Sharing
  • Spy / Ad Blockers
  • Vulnerabilities
  • WebApplications
  • IDS
  • Anti-Virus
  • Encryption
  • Anti Spam
  • Email Clients
  • VPN
  • Chat / IM
Programming
  • Editors IDEs
  • Installation
  • Handhelds / PDAs
  • Multimedia Programming
  • System / Kernel
  • Automation
  • Algorithms
  • Game
  • Signal Processing
  • Project Management
  • Open Source
  • Database
  • Misc
  • Languages
  • Processor Platforms
  • Theory
Web Development
  • Scripting
  • Blogs
  • Web Servers
  • Software
  • Search Engines
  • Web Graphics
  • Web Services
  • Images
  • Internet Marketing
  • Images and Photos
  • Components
  • Document Imaging
  • Web Languages/Standards
  • Illustration
  • WebApplications
  • Fonts
  • WebTrends / Stats
  • Authoring
  • Digital Camera Software
  • Miscellaneous
Networking
  • Protocols
  • Apple Networking
  • Network Management
  • Message Queue
  • Application Servers
  • Content Management
  • File Servers
  • Email Servers
  • Misc
  • Java Editors & IDEs
  • Wireless
  • Networking Hardware
  • Backup / Restore
  • System Utilities
  • ISPs & Hosting
  • Web Servers
  • Storage Technology
  • Removable Backup Media
  • Servers
  • Web Computing
  • Broadband
  • Grid
  • OS / 2
  • Novell Netware
  • Unix Networking
  • Windows Networking
  • Security
  • Telecommunications
  • Operating Systems
  • Linux Networking
Other
  • Lounge
  • Business Travel
  • Community Support
  • New Net Users
  • Philosophy / Religion
  • Math / Science
  • Miscellaneous
  • URLs
  • Expert Lounge
  • Politics
  • Puzzles / Riddles
  • Automotive
Community Support
  • Suggestions
  • New to EE
  • New Topics
  • CleanUp
  • Announcements
  • General
  • Feedback
  • Input
  • EE Bugs
 
04.07.2008 at 03:02AM PDT, ID: 21295458

Rank: Master

It might help to log any exceptions ...
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
    ...
    Finally
      FreeMem(Buffer);
    end;
  Except
    {$IFDEF Debug}
    ON e: Exception do 
      Log('GetNameFromHandle Error : ' + E.Message);
    {$ENDIF}
  end;
  {$IFDEF Debug}
  Log('End of GetNameFromHandle');
  {$ENDIF}
  ...
Open in New Window
 
04.07.2008 at 09:35AM PDT, ID: 21298468
None Logged.
 
04.08.2008 at 01:03AM PDT, ID: 21303272

Rank: Sage

sorry ThievingSix, I'm a little too busy at the time. can you post a test project (everything we need to just run and see what happens. if the target exe is some 3rd party, then try top create a demo one which will have the same behaviour)

I'll then try to look at it when I get some free time.

thanks
 
04.08.2008 at 01:06AM PDT, ID: 21303288
Here's my project folder for this: (rename to .zip).
 
Rename to .zip
 
 
04.08.2008 at 01:08AM PDT, ID: 21303298
You can test it on any app such as:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
procedure TForm1.Button1Click(Sender: TObject);
var
  PID : Cardinal;
  Written : Cardinal;
  Buffer : Char;
begin
  GetWindowThreadProcessID(FindWindow(nil,'Calculator'),PID);
  Buffer := #13;
  WriteProcessMemory(OpenProcess(PROCESS_ALL_ACCESS,False,PID),Pointer($400000),@Buffer,1,Written);
end;
Open in New Window
 
05.05.2008 at 03:25AM PDT, ID: 21498983

Rank: Sage

I can't compile your project. missing some units.
also note that you don't need to include in the attached zip the exe/dcu/dll and the release zip file as they can be regenerated. saves probably around 500kb :)

in order to send me all the needed files, copy the project to some otehr directory and try to compile. then add necessary files as needed.

also, jsut for the future: if a project does not explicitly own a file, don't include it in the project (like afxCodeHook, Win32Hook, DisAsm32 etc.) instead, use the projects search directory settign and place appropriate paths there.
this will make your project shareable in the sense that even if I have DisAsm32 for example, in my case it could be somewhere else ;)

I'll wait for a compilable project zip :)

----

as a side note, do you have some time for this question: http://www.experts-exchange.com/Programming/Editors_IDEs/Delphi/Q_23199257.html

I wanted to make a demo for the guy but my experience with hooks is limited to madhis madcodehook and he no longer distributes it freely. If you don't have time, just let me know of an official download location for the hooking stuff you are using in case they are freely available.

thanks
 
05.05.2008 at 10:56AM PDT, ID: 21501705
I guess I didn't really look at the project headers at the things you might need ;P

Anyway, here should be everything.

Also for your second question, I'll have more time for a demo app tonight. If you need ana answer sooner:

Since you found that old madshi's collection that still had it, I have been using it recently. As for other alternatives, afxcodehook in this project works well it just takes more work to do the same thing than madshi's.

Also PAQ's here have had promising hooking functions although I have never used them:
http://www.experts-exchange.com/Programming/Languages/Pascal/Delphi/Q_22525097.html?sfQueryTermInfo=1+hack+protect
http://www.experts-exchange.com/Programming/Languages/Pascal/Delphi/Q_22086907.html?sfQueryTermInfo=1+file+from+process+unlink

Since I am quite interested in his question and have always wanted to do it myself I have a reason to look at it more seriously now.
 
05.05.2008 at 11:55AM PDT, ID: 21502140

Rank: Sage

>>Anyway, here should be everything.

by "here" you mean you forgot to upload? or am I missing something?

about the other issue. thanks for the links. thing is that I've upgraded my madshi collection and I no longer have the hooking stuff (well, there's some bak directories with the backup but I don't think it would be a good idea to mix old hooking with new madbasic).
anyway, I'll see if I can somehow configure my system to use 2 versions of madcomponents, but until then, I was thinking to pass this problem to somebody who has some experience in the hooking business and maybe more free time then I do ;)

and if you say you are using the old version of madexcept, it would be an idea to use that for the demo for the guy. whichever is more comfortable for you. I just hate leaving people waiting for me so long.
 
05.05.2008 at 01:30PM PDT, ID: 21502735
Sorry, I forgot to upload, slipping today..
 
It's in rar format because of the new upload block.
 
 
05.06.2008 at 06:26AM PDT, ID: 21507064

Rank: Sage

the key of a good log-based debug is a good logging function. your logging function is bad as it doesn't flush itself so there are messages that you may loose in case of problems. and problems are the reason of the log-debug in the first place :)
find attached an "improved" version of your logging code.

I made a test project as you suggested. started calculator, started the test project, ticked the verbose, selected test project from list, clicked the button (contained your code, well, a little improved as I was closing the process handle which you were not :P), and looked in the log file and saw:


06.05.2008 16:18:30: Log started at 06.05.2008 16:18:30
06.05.2008 16:18:30: SharedMem created
06.05.2008 16:18:30: GlobalHandle: 1379874
06.05.2008 16:18:30: IsVerbose: True
06.05.2008 16:18:30: AllowWrite: True
06.05.2008 16:18:30: CRHook created
06.05.2008 16:18:30: WriteMemoryBoolean: True
06.05.2008 16:18:30: ReadMemoryBoolean: True
06.05.2008 16:18:30: OpenProcessBoolean: True
06.05.2008 16:18:32: OpenProcessCallBack called. Access=2035711 Inherit=False ProcessID=3148
06.05.2008 16:18:32: Result of OpenProcessNextHook: 84
06.05.2008 16:18:32: WriteProcessMemoryCallBack called. Handle=84 BaseAddress=00400000
06.05.2008 16:18:32: GetNameFromHandle called. Handle=84
06.05.2008 16:18:32: ReadProcessMemoryCallBack called. Handle=84 BaseAddress=7FFDD008
06.05.2008 16:18:32: Result of ReadProcessMemoryNextHook=True
06.05.2008 16:18:32: ReadProcessMemoryCallBack called. Handle=84 BaseAddress=7FFDD00C

**** lot of repeats, about 500KB of them ****

06.05.2008 16:18:35: ReadProcessMemoryCallBack called. Handle=84 BaseAddress=7FFDD008
06.05.2008 16:18:35: Result of ReadProcessMemoryNextHook=True
06.05.2008 16:18:35: ReadProcessMemoryCallBack called. Handle=84 BaseAddress=7FFDD00C
06.05.2008 16:18:35: GetNameFromHandle called. Handle=84
06.05.2008 16:18:35: ReadProcessMemoryCallBack called. Handle=84 BaseAddress=7FFDD008
06.05.2008 16:18:35: Result of ReadProcessMemoryNextHook=True
06.05.2008 16:18:35: ReadProcessMemoryCallBack called. Handle=84 BaseAddress=7FFDD00C
06.05.2008 16:18:35: GetNameFromHandle called. Handle=84
06.05.2008 16:18:35: GetNameFromHandle Error : Stack overflow
06.05.2008 16:18:35: End of GetNameFromHandle
06.05.2008 16:18:35: pBuffer: [] Read Memory(0x7FFDD00C): 75 1D 36 BA | ByteCount: 4
06.05.2008 16:18:35: Result of ReadProcessMemoryNextHook=True
06.05.2008 16:18:35: ReadProcessMemoryCallBack called. Handle=84 BaseAddress=001A1EA4
06.05.2008 16:18:35: GetNameFromHandle called. Handle=84
06.05.2008 16:18:35: ReadProcessMemoryCallBack called. Handle=84 BaseAddress=7FFDD008
06.05.2008 16:18:35: Result of ReadProcessMemoryNextHook=True
06.05.2008 16:18:35: ReadProcessMemoryCallBack called. Handle=84 BaseAddress=7FFDD00C

*** some more repeats but not as far as many and sudden "death" ***



the key line is:

06.05.2008 16:18:35: GetNameFromHandle Error : Stack overflow

I don't have time to investigate the application to see exactly where and why the infinite cycle is happening, but I gave you a starting point ;)

I suspect somehwere (maybe one of the used apis), GetNameFromHandle calls some function that calls ReadProcessMemory (which is hooked and) which in turn calls again GetNameFromHandle and thus the cycle. as I said I don't have time to investigate this further but I think I nailed it down :)

let me know how it goes.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
procedure Log(Text: String);
begin
  AssignFile(sLog,'C:\Spy.dll.log');
  if fileexists('C:\Spy.dll.log') then
    append(slog)
  else
    ReWrite(sLog);
  try
    Writeln(sLog,DateTimeToStr(Now) + ': ' + Text);
  finally
    closefile(slog);
  end;
end;
 
procedure OpenLog;
begin
  Log('Log started at ' + DateTimeToStr(Now));
end;
 
procedure CloseLog;
begin
  log('Log ended at ' + DateTimeToStr(Now));
end;
Open in New Window
Accepted Solution
 
05.16.2008 at 07:07PM PDT, ID: 21587731
I ended up unhooking the hooks before the GetFileNameFromHandle() then rehooking. Thanks for all your assistance!
 
05.17.2008 at 12:41AM PDT, ID: 21588307

Rank: Sage

you're welcome
 
 
20080236-EE-VQP-29 / EE_QW_2_20070628