Several ways to monitor file copy operations in Windows systems

Source: Internet
Author: User
Tags flock

Http://blog.sina.com.cn/s/blog_4596beaa0100lp4y.html

1. Icopyhook

Role: Monitor folder and printer movement, delete, rename, copy operations. You can get the source and destination file names. You can control the deny operation.

Disadvantage: The file cannot be controlled. Valid only for Shell file operations, invalid for native API MoveFile, CopyFile, and so on.

Usage: Derive a COM object from Icopyhook, overload Copycallbacka and COPYCALLBACKW, and then register COM with the Hkrc\directory\shellex\copyhookhandlers\

2. Notification of file changes

Role: Monitor a folder for file modification (write, delete, rename), and can register to a window to process notifications.

Cons: Only notifications, no actions can be rejected. Cannot distinguish whether a file copy operation or a move operation, cannot get the source file name. Valid only for Shell file operations, invalid for native API MoveFile, CopyFile, and so on.

Usage: Shchangenotifyregister Register a window to receive file changes with; Or findfirstchangenotification is treated in a way that combines findnextchangenotification.

3.IShellExtInit

Role: Each shell extension object creation will trigger the ishellexinit::initialize call, in the shell, the user's copy and paste operation of the file, will eventually be parsed into a file object drag and drop, and then trigger the drag of the target object's shell extension object call . So registering a ishellextinit on a folder and a character object allows you to monitor events that are dragged to the folder object. That is, you can monitor the operation of a file copy or move to a folder. The source file name can also be obtained from the ishellexitinit::initialize.

Cons: As with notifications, file operations cannot be denied. Valid only for Shell file operations, invalid for native API MoveFile, CopyFile, and so on.

Usage: Derive a COM object from Ishellextinit, overload initialize, the first parameter from initialize is the target directory name, the second parameter can get all the source file name, and the third parameter is a registry object handle.

Here is a sample treatment:

HRESULT Stdmethodcalltype ckcopyhook::initialize (

__in_opt Pcidlist_absolute Pidlfolder,

__in_opt IDataObject *pdtobj,

__in_opt HKEY Hkeyprogid)
{
HRESULT ret = E_INVALIDARG;
if (Ntqueryobject = = 0)
{
Ntqueryobject = (pfntqueryobject) GetProcAddress (LoadLibraryA ("Ntdll.dll"), "Ntqueryobject");
}

if (Ntqueryobject = = 0)
return E_FAIL;

Gets the name of the Hkeyprogid
Std::auto_ptr<wchar> buffer (new wchar[4096]);
DWORD Retlen = 0;
if (Ntqueryobject (Hkeyprogid, Objectnameinformation, Buffer.get (), 4096, &retlen) > 0)
return E_INVALIDARG;

Pobject_name_information Poni = (pobject_name_information) buffer.get ();
Poni->name.buffer[poni->name.length] = 0;

Dbgoutputmessagew (L "[%s] hkeyprogid=0x%x=[%s]", __functionw__, Hkeyprogid, Poni->name.buffer);

File processing when Hkeyprogid is a Folder item
if (wcsnicmp (Pathfindfilenamew (poni->name.buffer), L "Folder", 6)! = 0)
return S_OK;

if (! SHGETPATHFROMIDLISTW (Pidlfolder, Buffer.get ()))
return E_INVALIDARG;

Std::wstring deststr = Buffer.get ();

ret = E_INVALIDARG;

 coledataobject Oledo;
 oledo. Attach (Pdtobj, FALSE);
 HGLOBAL  GlobalData;
 globaldata = Oledo. Getglobaldata (Cf_hdrop);
 if (GlobalData)
 {
  hdrop hdrop = (hdrop) globallock (GlobalData);
  if (hdrop)
  {
   //Enumeration of dragged source files
   int nfiles = Dragqueryfilew (Hdrop, 0xFFFFFFFF, NULL, 0);
   std::vector<std::wstring> Srcstrs;
   for (int i=0; i<nfiles; ++i)
   {
    if ( Dragqueryfile (Hdrop, I, Buffer.get (), 4096))
    {
      Srcstrs.push_back (Buffer.get ());
    }
   }
   
   if (Oncopyfile (srcstrs, DESTSTR, 0))
    ret = S _OK;

GlobalUnlock (Hdrop);
}
GlobalFree (GlobalData);
}

return ret;
}

4. File Filter Driver

Function: Control all file Atomic operations

Cons: Cannot (or is difficult to) track file copy, move operations.

Usage: It's useless, don't write it anyway.

5. API hooking

Role: Intercept CopyFile, MoveFile and other APIs, you can arbitrarily control the file copy operation, you can reject the file operation, you can also insert a custom operation before and after copying, quite flexible.

Cons: Trouble, quite troublesome, poor compatibility.

Usage: The technology of API hooking is no longer stated here.

There are quite a few APIs that need to be intercepted, movefile* copyfile* series functions exported from Kernel32.dll, and the shell is using SHFileOperation for file operations in previous systems in Vista. SHFileOperation internally also calls these functions in kernel32, so shfileoperation can not be processed.

But after Vista's system, the shell instead calls Shfileoperationex, Shfileroperationex inside does not use CopyFile, movecopy and so on function, but uses CreateFile, ReadFile, WriteFile overlapped IO for file operations, and Shfileoperationex is not exported in any DLL. This will cause a lot of trouble to intercept Shfileroperationex.

However, you can search for Shfileroperationex addresses from memory using the search feature code.

Here is the feature code for the beginning of the Shfileroperationex in the 32-bit system, in Shell32.dll memory space, 32-bit vista, Win7 for

Const BYTE shfileoperationexcodemark[] = {
0x8b, 0xFF, 0x55, 0x8b, 0xEC, 0x83, 0xEC, 0x18, 0xa1, 0xFF, 0xFF, 0xFF, 0xFF, 0x33, 0xC5, 0x89,
0x45, 0xFC, 0x8b, 0x45, 0x0C, 0x8b, 0x4d, 0x1C, 0x53, 0x8b, 0x5d, 0x10, 0x56, 0x8b, 0x75, 0x20,
0x57, 0xFF, 0x75, 0x08, 0x89, 0x45, 0xF0, 0x8b, 0x45, 0x14, 0x89, 0x45, 0xEC, 0xBF, 0xFF, 0xFF,
0xFF, 0xFF, 0xe8, 0xFF, 0xFF, 0xFF, 0xFF, 0x85, 0xC0, 0x0F, 0x84, 0xFF, 0xFF, 0xFF, 0xFF, 0x8d,
};

Where the 0xFF position skips over the alignment

https://yq.aliyun.com/wenji/88468 Abstract: This article is about the use of copy hooks to monitor the folder, Icopyhook is a copy hook handler for creating COM interface, it determines whether a folder or printer object can be moved, Copy, rename, or delete. Before the shell performs these operations, it invokes the Copycallback method of the Icopyhook interface to

Icopyhook is a COM interface used to create a copy hook handler that determines whether a folder or printer object can be moved, copied, renamed, or deleted. Before the shell performs these operations, it invokes the Copycallback method of the Icopyhook interface to validate them. Copycallback returns an int value indicating whether the shell should continue with this operation. The return value Idyes indicates continuation, while the return value Idno and idcancel indicate termination.

A Folder object can install multiple copy hook handlers. If this occurs, the shell invokes each handler in turn. The shell actually performs the action requested by the user only when each handler returns Idyes.

The purpose of the copy hook handler is to validate the above four operations before they are executed, but the shell does not notify the copy hook handler of the result of the operation. The API functions provided by Windows FindFirstChangeNotification and findnextchangenotification can implement this function. Therefore, the state of a folder can be fully monitored only by combining the two methods.

The Copy hook handler implementation is not difficult, first creating a COM object as an in-process component, it only needs to expose a Icopyhook interface (and, of course, IUnknown). Then register this COM component with Regsrv32.exe. The final step is to register your copy hook handler with the shell by creating an arbitrary sub key under the registry hkey_classes_root\directory\shellex\copyhookhandlers, in this sub Key to create an item of type REG_SZ and use the CLSID of your COM object as its default value.

Here is a copy of the hook Implementation Program (note: The following code has been modified by the old demon and added detailed procedures, successfully compiled in BCB6 and passed the test)

1. Create the Tcopyhook from the Icopyhook interface and create Tclassfactory from the IClassFactory interface:

TCopyHook.h
The Tcopyhook class implements the Icopyhook interface, Tclassfactory implements the IClassFactory interface
//---------------------------------------------------------------------------
#define No_win32_lean_and_mean
#include <shlobj.h>
//---------------------------------------------------------------------------
Class Tcopyhook:public Icopyhook
{
Public
Tcopyhook (): m_refcnt (0) {}
STDMETHODIMP QueryInterface (Refiid iid,void **ppvobject);
Stdmethodimp_ (ULONG) AddRef ();
Stdmethodimp_ (ULONG) Release ();
STDMETHODIMP_ (UINT) Copycallback (HWND hwnd, UINT wfunc, uint wflags,
LPCTSTR Pszsrcfile, DWORD dwsrcattribs,
LPCTSTR Pszdestfile, DWORD dwdestattribs);
Private
int m_refcnt;
};
//---------------------------------------------------------------------------
Class Tclassfactory:public IClassFactory
{
Public
Tclassfactory (): m_refcnt (0) {}
STDMETHODIMP QueryInterface (Refiid iid, void **ppvobject);
Stdmethodimp_ (ULONG) AddRef ();
Stdmethodimp_ (ULONG) Release ();
Stdmethodimp CreateInstance (IUnknown *punkouter, refiid riid, void **ppvobject);
STDMETHODIMP Lockserver (BOOL fLock);
Private
int m_refcnt;
};
TCopyHook.cpp
Implementation files for Tcopyhook objects and Tclassfactory objects
#include <stdio.h>
#include "TCopyHook.h"
//---------------------------------------------------------------------------
extern LONG Nlocks; Object count, for DllCanUnloadNow
ULONG __stdcall Tcopyhook::addref ()
{
if (m_refcnt = = 0)
nlocks++;
m_refcnt++;
return m_refcnt;
}
//---------------------------------------------------------------------------
ULONG __stdcall Tcopyhook::release ()
{
int nnewcnt =--m_refcnt;
if (nnewcnt <= 0)
{
nlocks--;
Delete this;
}
return nnewcnt;
}
//---------------------------------------------------------------------------
HRESULT __stdcall Tcopyhook::queryinterface (refiid dwiid, void **ppvobject)
{
if (dwiid = = IID_IUnknown)
*ppvobject = static_cast<iunknown*> (this);
Else
if (dwiid = = Iid_ishellcopyhook)
*ppvobject = static_cast<icopyhook*> (this);
Else
return e_nointerface;
Reinterpret_cast<iunknown*> (*ppvobject)->addref ();
return S_OK;
}
//---------------------------------------------------------------------------
This is the Copycallback method, which implements all the functions of the copy hook. Specific values for parameters see MSDN
UINT __stdcall Tcopyhook::copycallback (HWND hwnd, UINT wfunc, uint wflags,
LPCTSTR Pszsrcfile, DWORD dwsrcattribs,
LPCTSTR Pszdestfile, DWORD dwdestattribs)
{
Char szmessage[max_path+14];
sprintf (Szmessage, "Do you want to continue with%s?") ", Pszsrcfile);
Return MessageBox (NULL, Szmessage, "ack", Mb_yesno | Mb_iconexclamation);
}
//---------------------------------------------------------------------------
ULONG __stdcall Tclassfactory::addref ()
{
if (m_refcnt==0)
nlocks++;
m_refcnt++;
return m_refcnt;
}
//---------------------------------------------------------------------------
ULONG __stdcall Tclassfactory::release ()
{
int nnewcnt =--m_refcnt;
if (nnewcnt <= 0)
{
nlocks--;
Delete this;
}
return nnewcnt;
}
//---------------------------------------------------------------------------
HRESULT __stdcall Tclassfactory::queryinterface (refiid dwiid, void **ppvobject)
{
if (dwiid = = IID_IUnknown)
*ppvobject = static_cast<iunknown*> (this);
Else
if (dwiid = = iid_iclassfactory)
*ppvobject = static_cast<iclassfactory*> (this);
Else
return e_nointerface;
Reinterpret_cast<iunknown*> (*ppvobject)->addref ();
return S_OK;
}
//---------------------------------------------------------------------------
HRESULT __stdcall tclassfactory::createinstance (iunknown* punkownouter,
REFIID riid, void** ppvobj)
{
if (punkownouter! = NULL)
return class_e_noaggregation;
Tcopyhook *pobj = new Tcopyhook;
Pobj->addref ();
HRESULT hr = Pobj->queryinterface (riid, ppvobj);
Pobj->release ();
return HR;
}
//---------------------------------------------------------------------------
HRESULT __stdcall Tclassfactory::lockserver (BOOL fLock)
{
if (FLock)
nlocks++;
Else
nlocks--;
return S_OK;
}

The above is the cloud Community small series for your carefully prepared content, in the cloud Habitat Community blog, question and answer, the public number, people, courses and other related content, welcome to continue to use the search button in the upper right corner of the search program, copy, return, hook, processing a folder copy monitoring, PHP hook implementation principle, System hooks Sub-hook monitoring, Windows Hook Monitoring window, thinkphp hook implementation, so that you get more relevant knowledge.

Reference Links:

https://msdn.microsoft.com/en-us/library/cc144063 (vs.85). aspx

Https://www.codeproject.com/Articles/7309/ICopyHook-implementation

Several ways to monitor file copy operations in Windows systems

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.