CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

Become a Marketplace Partner

jobs.internet.com

internet.commerce
Partners & Affiliates
















RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

Home >> Visual C++ / C++ >> Miscellaneous >> Samples


PasswordSpy - Retrieving lost passwords using Windows hooks
Rating:

Brian Friesen (view profile)
February 3, 2004


(continued)





Click here for larger image

Environment: VC5, VC6

Introduction

It was several years ago when I downloaded some sample code posted here on CodeGuru, a program called Eureka that was designed to "retrieve" forgotten passwords in Windows. It was not a password cracker; instead, it used a security hole in Windows to copy the password from another running program. I was intrigued by the program, so I decided to write my own version. Later, once Windows 2000 was released, I was disappointed to see that Microsoft had fixed the "bug" and so programs like these didn't work on Windows 2000 (and nowadays Windows XP). But after several failed attempts, I finally found a way to copy the password while running on any 32-bit Windows OS.

Use

PasswordSpy is a very simple program to use. You simply start the program that contains the forgotten password as well as PasswordSpy. Then, drag the magnifying glass from PasswordSpy over the "****" field and PasswordSpy will display the password. It should be noted that PasswordSpy is not intended for mischievous purposes. PasswordSpy has been tested on Win95/98/ME and WinNT/2K/XP.

Features

In addition to being a useful application, PasswordSpy demonstrates some useful and interesting code.

  • A single instance application. If the user starts a second copy of PasswordSpy, the first copy is brought to the foreground instead of starting a second copy.
  • "Always on top." With a single line of code, you can set or remove the "always on top" state from your application.
  • Inter Process Communication. PasswordSpy uses several forms of IPC, including the WM_COPYDATA message as well as memory-mapped files.
  • Setting windows hooks. To extract the password on Windows2000 and WindowsXP, you must set a hook into the remote process.

Code Details

By far, the most interesting aspect of PasswordSpy is the technique of setting a Windows hook with the SetWindowsHookEx API. With this function, you can install a hook into either the whole system or a specific process. There are a dozen different types of hooks to install; each type monitors for a specific set of events. When one of those events happens, your hook code gets called. PasswordSpy uses the WH_GETMESSAGE hook, which monitors for calls to GetMessage and PeekMessage. For more background info on hooks, please read the MSDN on SetWindowsHookEx.

I have found several examples of hooks on the Internet, in books, in the MSDN, and right here on CodeGuru. But, every example I saw had at least one bug in the code. Here, I'll address the problem as well as my solution.

The hardest part about using Windows hooks is properly storing the handle to the hook. Before you can set a hook, you need two things: 1) A DLL containing the hook function and 2) the ID of the thread you want to hook. Now, supposing Process A sets a hook into Process B. After hooking Process B, the hook handle is returned to Process A and the DLL is mapped into Process B's address space. When one of the hooked events in Process B happens, your hook code gets called from Process B. (It should be noted that your hook code gets called from the remote process! In your hook code, if you call GetCurrentProcessId, you get the PID of the hooked process, not your original program that set the hook.) From the hook code, you can do whatever you want, but before your hook code exits, you are supposed to call CallNextHookEx. If you fail to call this function, any other hooks that might be installed will fail to get the message. The problem is that CallNextHookEx requires the handle to the hook, but that handle was returned to Process A and we're currently in Process B. Thus, some sort of Inter Process Communication is needed to transfer the hook handle.

Most hook samples solve this problem by creating a "shared" section in the DLL.

#pragma data_seg("Shared")
HHOOK g_hHook = NULL;
#pragma data_seg()
#pragma comment(linker, "/section:Shared,rws")

In a nutshell, this creates a single variable that is shared by all loaded instances of that DLL. So, if five processes load this DLL, all five have access to that variable. But, there are a few problems with this method. For starters, some compilers may not support this option. Second, what if Microsoft decides to change how "shared" sections work in future versions of Windows? That would mean this technique would no longer work. Also, this method has no thread synchronization, and because you have multiple threads accessing this variable, thread synchronization is important.

To solve these problems, I used memory mapped files for the IPC, and a mutex for thread synchronization. I encapsulated all this code into a class I called CIPC. By using memory mapped files, I solve the problem of special compiler options because none are needed; it's done using nothing but Win32 API calls. Plus, MMFs are a supported way of sharing data between multiple processes, so Microsoft is not likely to change that in future versions of Windows. And, the mutex ensures that thread access is synchronized.

//***********************************************
// IPC.h
//***********************************************
#ifndef _IPC_H_
#define _IPC_H_

#define IPC_SHARED_MMF  _T("{34F673E0-878F-11D5-B98A-00B0D07B8C7C}")
#define IPC_MUTEX       _T("{34F673E1-878F-11D5-B98A-00B0D07B8C7C}")

// Class for Inter Process Communication using Memory Mapped Files
class CIPC
{
public:
  CIPC();
  virtual ~CIPC();

  bool CreateIPCMMF(void);
  bool OpenIPCMMF(void);
  void CloseIPCMMF(void);

  bool IsOpen(void) const {return (m_hFileMap != NULL);}

  bool ReadIPCMMF(LPBYTE pBuf, DWORD &dwBufSize);
  bool WriteIPCMMF(const LPBYTE pBuf,
                   const DWORD dwBufSize);

  bool Lock(void);
  void Unlock(void);

protected:
  HANDLE m_hFileMap;
  HANDLE m_hMutex;
};

#endif


//***********************************************
// IPC.cpp
//***********************************************
#include "IPC.h"

//***********************************************
CIPC::CIPC() : m_hFileMap(NULL), m_hMutex(NULL)
{
}

//***********************************************
CIPC::~CIPC()
{
    CloseIPCMMF();
    Unlock();
}

//***********************************************
bool CIPC::CreateIPCMMF(void)
{
  bool bCreated = false;

  try
  {
     if(m_hFileMap != NULL)
        return false;    // Already created

     // Create an in-memory 4KB memory mapped
     // file to share data
     m_hFileMap = CreateFileMapping((HANDLE)0xFFFFFFFF,
         NULL,
         PAGE_READWRITE,
         0,
         4096,
         IPC_SHARED_MMF);
     if(m_hFileMap != NULL)
        bCreated = true;
  }
  catch(...) {}

  return bCreated;
}

//***********************************************
bool CIPC::OpenIPCMMF(void)
{
    bool bOpened = false;

    try
    {
        if(m_hFileMap != NULL)
            return true;    // Already opened

        m_hFileMap =
          OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE,
            FALSE,
            IPC_SHARED_MMF);
        if(m_hFileMap != NULL)
            bOpened = true;
    }
    catch(...) {}

    return bOpened;
}

//***********************************************
void CIPC::CloseIPCMMF(void)
{
    try
    {
        if(m_hFileMap != NULL)
            CloseHandle(m_hFileMap), m_hFileMap = NULL;
    }
    catch(...) {}
}

//***********************************************
bool CIPC::ReadIPCMMF(LPBYTE pBuf, DWORD &dwBufSize)
{
  _ASSERTE(pBuf);

  bool bSuccess = true;

  try
  {
     if(m_hFileMap == NULL)
         return false;

     DWORD dwBaseMMF = (DWORD)MapViewOfFile(m_hFileMap,
                FILE_MAP_READ | FILE_MAP_WRITE,
         0, 0, 0);
     _ASSERTE(dwBaseMMF);

     // The first DWORD in the MMF contains the size of the data
     DWORD dwSizeofInBuf = dwBufSize;
     CopyMemory(&dwBufSize, (LPVOID)dwBaseMMF, sizeof(DWORD));

     if(dwSizeofInBuf != 0)
     {
         if(dwBufSize > dwSizeofInBuf)
             bSuccess = false;
         else
              CopyMemory(pBuf,
                  (LPVOID)(dwBaseMMF + sizeof(DWORD)),
                  dwBufSize);
     }

     UnmapViewOfFile((LPVOID)dwBaseMMF);
  }
  catch(...) {}

  return bSuccess;
}

//***********************************************
bool CIPC::WriteIPCMMF(const LPBYTE pBuf, const DWORD dwBufSize)
{
    _ASSERTE(pBuf);

    bool bSuccess = true;

    try
    {
        if(m_hFileMap == NULL)
            return false;

        DWORD dwBaseMMF = (DWORD)MapViewOfFile(m_hFileMap,
            FILE_MAP_READ | FILE_MAP_WRITE,
            0, 0, 0);
        _ASSERTE(dwBaseMMF);

        // The first DWORD in the MMF contains the size of the data
        CopyMemory((LPVOID)dwBaseMMF, &dwBufSize, sizeof(DWORD));
        CopyMemory((LPVOID)(dwBaseMMF + sizeof(DWORD)),
                            pBuf,
                            dwBufSize);

        UnmapViewOfFile((LPVOID)dwBaseMMF);
    }
    catch(...) {}

    return bSuccess;
}

//***********************************************
bool CIPC::Lock(void)
{
    bool bLocked = false;

    try
    {
        // First get the handle to the mutex
        m_hMutex = CreateMutex(NULL, FALSE, IPC_MUTEX);
        if(m_hMutex != NULL)
        {
            // Wait to get the lock on the mutex
            if(WaitForSingleObject(m_hMutex, INFINITE) ==
                                   WAIT_OBJECT_0)
                bLocked = true;
        }
    }
    catch(...) {}

    return bLocked;
}

//***********************************************
void CIPC::Unlock(void)
{
    try
    {
        if(m_hMutex != NULL)
        {
            ReleaseMutex(m_hMutex);
            CloseHandle(m_hMutex);
            m_hMutex = NULL;
        }
    }
    catch(...) {}
}

Countering PasswordSpy

Now that you know how to programmatically "copy" the password from another application, the next logical question is: "How do you prevent PasswordSpy from copying passwords from applications you write?" If your application stores and displays passwords, and especially if you are concerned about security, you probably want to protect your application from programs such as PasswordSpy.

Because PasswordSpy can copy passwords out of other programs, the solution to protecting your own programs is to never display the real password in the first place. The best solution is to display a bogus password in the password control. That way, if someone uses PasswordSpy to retrieve the password, all they get back is a bogus password, not the real thing. Included in the download is a program called AntiPwdSpy. This program shows how to protect your password controls from being "spied." The AntiPwdSpy program behaves exactly the same as the Windows NT Services dialog and the Windows NT User Manager.

There are other ways to counter programs such as PasswordSpy. One way is to intercept the WM_GETTEXT message. This works, but using the bogus password method has other benefits. By replacing the real password with a bogus one, it is not possible to determine the length of a password by looking at the password control. If a program displays the text "***" in a password control, right away you know that password is only three characters in length. This greatly compromises the security of that password by revealing the password's length. But, if that password control displayed "**************", as is done in most Microsoft programs, you do not know anything about the password.

References

I must give credit where credit is due. The following two projects found here on CodeGuru helped me write this program.

Downloads

Download demo project - 25 Kb
Download source - 27 Kb

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed







RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
thank you - Sanhan (03/12/2004)
Read This Small Poem For Windows Family. - King (03/11/2004)
What is the real purpose of these kinds of programs? - Legacy CodeGuru (02/04/2004)
PwdSpy, NAV, and Power Spider - Legacy CodeGuru (01/30/2004)
VIRUS - Legacy CodeGuru (01/09/2004)

View All Comments
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES