Windows API Hooking in Python with Deviare

The code below uses Python to intercept the CreateFile function on the kernel32.dll to forbid opening certain files. It hooks the CreateFile function for the notepad.exe application. The Python code is very small and to the point, and you can customize it for your own purposes. For example, it can be used to sandbox an application to restrict it to a certain set of files, registry keys, and network accesses.

Python has a relatively long history of being used in the computer security field. Among IDA Pro plugins, IDAPython is more popular than IDARub. If search results can be used as a measure of success, a search for each major scripting language plus “reverse engineering” returns:

Query# of results
“python” AND “reverse engineering”215K
“perl” AND “reverse engineering”184K
“ruby” AND “reverse engineering”95.2K

 

Why is that? some people wrote specifically about that in Python and Reverse EngineeringPython Arsenal for Reverse Engineering Whitepaper, and a good video of RECON 2008: Reverse Engineering Dynamic Languages a Focus on Python, Aaron Portn.  The bias towards a programming language might be related to a network effect, but even so, a programming language with a vibrant community is fertile ground for trying out new ideas.

Code

Prerequisites

  1. Install Python 2.7.3 for Windows
  2. Download Deviare and Register DeviareCOM.dll and DeviareCOM64.dll if the script should under an x64 platform: open a command prompt with administrator rights, navigate to the folder where the Deviare’s *.dll files are located, execute “regsvr32 DeviareCOM.dll” and “regsvr32 DeviareCOM64.dll”
  3. Download and install Python Win32 Extensions
  4. The code is also available on github

Python Win32 Extensions Notes

Be careful to download the appropriate version for your platform and Python version.
If you get a message stating that you haven’t installed Python in your system yet (but you did and you are completely sure that you downloaded the correct Python Win32 Extensions installer) you can copy the registry folder HKEY_LOCAL_MACHINESOFTWAREWow6432NodePython to HKEY_LOCAL_MACHINESOFTWAREPython (or viceversa). To do this, you should:
  1. Open the registry editor (start -> run… -> “regedit”)
  2. Find the folder you want to copy
  3. Right click on the folder and select “Export”. This will allow you to save a file with the registry folder content
  4. Edit the file you just created and change all the paths in the file accordingly to where you want to move the folder
  5. Save the file and then double-click it. A message box should appear prompting if you want to add information to the registry. Click “yes” and you are done
  6. Once you’ve done this, the Python Win32 Extensions installer should recognize your Python installation
If you still have problems to install this demo, please visit our forum to get further assistance.

DeviarePythonDemo.py

import win32com.client
import ctypes

from EventHandlers import NktSpyMgrEvents
from AuxFunctions import *

spyManager = win32com.client.DispatchWithEvents('DeviareCOM.NktSpyMgr', NktSpyMgrEvents)
spyManager.Initialize()

StartNotepadAndHook(spyManager)

MessageBox = ctypes.windll.user32.MessageBoxA
MessageBox(None, 'Press OK to end the demo.', 'Deviare Python Demo', 0)

EventHandlers.py

import win32com.client

class NktSpyMgrEvents:
	def OnProcessStarted(self, nktProcessAsPyIDispatch):
		nktProcess = win32com.client.Dispatch(nktProcessAsPyIDispatch)
		if (nktProcess.Name == "notepad.exe"):
			print 'Notepad was started.'

	def OnProcessTerminated(self, nktProcessAsPyIDispatch):
		nktProcess = win32com.client.Dispatch(nktProcessAsPyIDispatch)
		if (nktProcess.Name == "notepad.exe"):
			print 'Notepad was terminated.'

	def OnFunctionCalled(self, nktHookAsPyIDispatch, nktProcessAsPyIDispatch, nktHookCallInfoAsPyIDispatch):
		nktHookCallInfo = win32com.client.Dispatch(nktHookCallInfoAsPyIDispatch)
		nktProcess = win32com.client.Dispatch(nktProcessAsPyIDispatch)

		if (nktHookCallInfo.IsPreCall):
			fileName = self.GetFileNameParam(nktHookCallInfo.Params())
			if (fileName.endswith('.txt')):
				self.SkipCall(nktHookCallInfo, nktProcess)

# Aux Functions

	def SkipCall(self, nktHookCallInfo, nktProcess):
		nktHookCallInfo.SkipCall()
		if (nktProcess.PlatformBits == 64):
			nktHookCallInfo.Result().LongLongVal = -1
		else:
			nktHookCallInfo.Result().LongVal = -1
		nktHookCallInfo.LastError = 5

	def GetFileNameParam(self, nktParamsEnum):
		nktParam = nktParamsEnum.First()
		return nktParam.Value

AuxFunctions.py

from subprocess import *

def GetPIDByProcessName(aProcessName):
	for proc in psutil.process_iter():
		if proc.name == aProcessName:
			return proc.pid

def OpenNotepadAndGetPID():
	print 'Starting Notepad...'
	pid = Popen("notepad").pid
	print 'Notepad started successfully'
	return pid

def HookFunctionForProcess(spyManager, functionModuleAndName, notepadPID):
	print 'Hooking function ' + functionModuleAndName + ' for Notepad...'
	hook = spyManager.CreateHook(functionModuleAndName, 0)
	hook.Attach(notepadPID, True)
	hook.Hook(True)
	print 'Notepad successfully hooked'
	return hook

def StartNotepadAndHook(spyManager):

	notepadPID = OpenNotepadAndGetPID()
	hook = HookFunctionForProcess(spyManager, "kernel32.dll!CreateFileW", notepadPID)

Related Services

  1. Reverse Engineering
  2. Interception and Filter Drivers Services
  3. Application Virtualization and Packaging

If you liked this article, you might also like:

  • http://www.fireboxtraining.com/ Seth Williams

    Hey Sebastian, this was an interesting tutorial on Windows API hooking in Python, thanks for sharing. We create many Python tutorials as well that
    may benefit your readers at https://www.youtube.com/fireboxtraining.

  • mena99260

    HookFunctionForProcess(spyManager, functionModuleAndName, notepadPID):
    print ‘Hooking function ‘ + functionModuleAndName + ‘ for Notepad…’
    hook = spyManager.CreateHook(functionModuleAndName, 0)
    hook.Attach(notepadPID, True)
    hook.Hook(True) print ‘Notepad successful

    best cookware
    sets

  • mena99260

    HookFunctionForProcess(spyManager, functionModuleAndName, notepadPID):
    print ‘Hooking function ‘ + functionModuleAndName + ‘ for Notepad…’
    hook = spyManager.CreateHook(functionModuleAndName, 0)
    hook.Attach(notepadPID, True)…
    debt
    consolidation

  • mena99260

    HookFunctionForProcess(spyManager, functionModuleAndName, notepadPID):
    print ‘Hooking function ‘ + functionModuleAndName + ‘ for Notepad…’
    hook = spyManager.CreateHook(functionModuleAndName, 0)
    hook.Attach(notepadPID, True)…
    found
    here

  • mena99260

    HookFunctionForProcess(spyManager, functionModuleAndName, notepadPID):
    print ‘Hooking function ‘ +
    catering
    halls queens new york

  • mena99260

    HookFunctionForProcess(spyManager, functionModuleAndName, notepadPID):
    print ‘Hooking function ‘ +
    Miami
    Escorts

  • mena99260

    HookFunctionForProcess(spyManager, functionModuleAndName, notepadPID):
    print ‘Hooking function ‘ +
    seasonal allergies natural remedies

  • mena99260

    HookFunctionForProcess(spyManager, functionModuleAndName, notepadPID):
    print ‘Hooking function ‘ +
    twitter accounts

  • Ashar Arain

    The code below uses Python to intercept the create file
    function on the kernel32.dll to forbid opening certain files. It hooks
    the CreateFile function for the notepad.exe application. The Python code
    is very small and to the point, and you can customize it for your own
    purposes. For example, it can be used to sandbox an application to restrict it to a certain set of files, registry keys, and network accesses…..
    Free PDF Links

  • Ashar Arain

    The Python code
    is very small and to the point, and you can customize it for your own
    purposes.
    For example, it can be used to sandbox an application to restrict it to
    a certain set of files, registry keys, and network accesses…..
    best free standing
    punching bag

  • Black Men

    It hooks the CreateFile function for the notepad.exe application.
    best backlink gig fiverr
    alternatives

  • Black Men

    certain set of files, registry keys, and network accesses.
    Den Haag

  • Black Men

    so, a programming language with a vibrant community is fertile ground for trying out new ideas.
    rasvaimu eestis

  • Black Men

    The bias towards a programming language might be related..
    ibs

  • Black Men

    The bias towards a programming language might be related to a network
    effect, but even so, a programming language with a vibrant community is
    fertile ground for trying out new ideas.
    loft conversions wandsworth

  • Black Men

    If search results can be used as a measure of success, a search for each
    major scripting language plus “reverse engineering” returns:
    loft conversions
    london

  • Black Men

    The bias towards a programming language might be related to a network
    effect, but even so, a programming language with a vibrant community is
    fertile ground for trying out new ideas.
    freestanding
    baths

  • Black Men

    application to restrict it to a certain set of files, registry keys, and network accesses.
    Mercedes Benz servicing

  • Black Men

    If search results can be used as a measure of success, a search for each
    major scripting language plus “reverse engineering” returns: madbussen

  • Black Men

    Goliaths promising equal value at the lowest cost, though lacking the
    personal touch and neighborly comfort that make independent record
    stores like Luna Music in Indianapolis so indispensable.vert shock program

  • Black Men

    registry keys, and network accesses.hotel villa de pertis

  • Black Men

    a search for each major scripting language plus “reverse engineering” returns:Good GPT Sites

  • Imtiaz Ali

    scripting language plus “reverse engineering”.
    redirected
    here

  • Black Men

    Some of them accommodations are pioneering gay-only hotels, whilst some market themselves towards the gay community and some are located in destinations popular among gay travelers.loft conversions

  • Black Men

    The bias towards a programming language might be related to a network
    effect, but even so, a programming language with a vibrant community is
    fertile ground for trying out new ideas. air tightness testing

  • Black Men

    The bias towards a programming language might be related to a network
    effect, but even so, a programming language with a vibrant community is
    fertile ground for trying out new ideas.limo hire london

  • Imtiaz Ali

    language with a vibrant community is fertile ground for trying out new ideas.
    PVA Email accounts

  • Black Men

    The bias towards a programming language might be related to a network
    effect, but even so, a programming language with a vibrant community is
    fertile ground for trying out new ideas.van rental london

  • Black Men

    application to restrict it to a certain set of files, registry keys, and network accesses.http://theofficialwebsite.co/dr-david-desire-system-review/

  • Imtiaz Ali

    programming language might be related to a network
    effect, but even so, a programming.
    car rental jaipur to
    delhi

  • Black Men

    If search results can be used as a measure of success, a search for each
    major scripting language plus.. If search results can be used as a measure of success, a search for each
    major scripting language plus “reverse engineering” returns:

  • Black Men

    Once you’ve done this, the Python Win32 Extensions installer should recognize your Python installation.. free wp plugin premium

  • Imtiaz Ali

    command prompt with administrator rights, navigate to the folder where the Deviare’s..
    what is
    dedicated hosting

  • Imtiaz Ali

    If search results can be used as a measure of success, a search for each..
    jaipur car rental
    services

  • Imtiaz Ali

    If search results can be used as a measure of success, a search for each..
    idaho falls
    seo

  • Imtiaz Ali

    Want
    Higher Ranking In Google?? Nothing Is Better Than HIGH PR BLOG COMMENTING
    SERVICE. Google Love These Kinds Of Back Links Because Your Website Is
    Linking To Authority Site That Is Already Index In Search Engines. This
    Service Is A WIN For Both Your Site, And Sites Where We Will Place Your Link
    With Additional Unique Content.

    Backlinks

  • Ashar Arain

    Thank you very much! My friends and family members will be happy after hearing about this…

    3 credit scores

  • Imtiaz Ali

    Nothing Is Better Than HIGH PR BLOG COMMENTING
    SERVICE. Google Love These Kinds Of Back Links Because Your Website Is
    Linking To Authority Site That Is Alread
    ..
    one piece

  • imtiaz

    Is there really only the way to upload via Dropbox itself
    and than attach it to my mail….
    delhi to jaipur
    taxi

    • imtiaz

      the content that you mentioned. I enjoyed every bit ‘part of it.It contains found it
      all the information.
      list email

  • imtiaz

    Is there really only the way to upload via Dropbox itself
    and than attach it to my mail.
    email marketing leads

  • imtiaz

    the Python Win32 Extensions installer should recognize your Python installation…
    business emails

  • https://twitter.com/SeoComenting SEO Commenting

    And he in fact ordered me dinner because I -idblogs found it for him… lol. So allow me to reword this. psd-loft.com

  • imtiaz

    Is there really only the way to upload via Dropbox itself
    and than attach it to my mail…
    top blogging
    sites

  • imtiaz

    And he in fact ordered me dinner because I -idblogs found it for him… lol. So allow me to reword thi.
    targeted email lists for sale

  • https://twitter.com/SeoComenting John SEO

    I appreciate everything you have added to my knowledge base.Admiring the
    time and effort you put into your blog and detailed information you
    offer Thanks.
    gramichicago.com

  • https://twitter.com/SeoComenting John SEO

    I appreciate everything you have added to my knowledge base.Admiring the time and effort you put into your blog and detailed information you offer Thanks
    salvia for sale

  • https://twitter.com/SeoComenting CanadiaN WeB HosT

    Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites.
    alcohol and drug treatment centers

  • https://twitter.com/SeoComenting CanadiaN WeB HosT

    Thanks a ton for sharing your knowledge! It is great to see that some people still put in an effort into managing their websites.
    start a blog on wordpress

  • https://www.facebook.com/ SEO Worker

    Thank you for writing such a wonderful article

  • https://www.facebook.com/ SEO Worker

    Thank you for writing such a wonderful article!
    buy email lists

  • imtiiz seo

    hooking techniques to extend the application functionalit
    car
    from delhi to jaipur

  • robinjack529

    AMERIKA will bomb AGAIN SOON IN IRAQ….
    manual backlinks

  • imtiiz seo

    ordered me dinner because I -idblogs found it for him… lol. So allow me to reword thi..
    pest
    control

  • robinjack529

    We Are A
    Full-Service Provider Of High Quality Backlinks That Help Boost Traffic,
    Increase Rankings, And Build Authority. With Years Of Experience We Know
    Exactly What Type Of Manual Dofollow Blog Comments It Takes To Quickly
    Increase Your Online Visibility

    link Building

  • robinseo

    come up where I will be making some pretty
    damn good money but I
    what is modafinil
    would need to work throughout the week, so
    continuing school isn’t an option right now

  • AJ seo1

    And Build Authority. With Years Of Experience We Know
    Exactly What Type Of Manual Dofollow Blog Comments It Takes To Quickly
    Increase Your Online Visibility

    packers and movers aundh

  • AJ seo1

    High Quality Backlinks That Help Boost Traffic,
    Increase Rankings,
    living room ideas

  • loferboy

    The sites you have referred was good. Thanks for sharing.. read more here The information you have posted is very useful…
    vancouver employment agencies

  • loferboy

    your blog in exchange for a link back to mine. Please shoot me an email if interested
    citation

  • AJ seo1

    Manual Dofollow Blog Comments It Takes To Quickly
    Increase Your Online Visibility
    vector logo

  • https://www.facebook.com/ SEO Worker

    You made a good point but I can’t help but wonder, what about the other side? THANKS!

  • https://www.facebook.com/ SEO Worker

    You made a good point but I can’t help but wonder, what about the other side? THANKS!
    marketing emails

  • https://www.facebook.com/ SEO Worker

    The bias towards a programming language might be related to a network
    effect, but even so, a programming language with a vibrant community is
    fertile ground for trying out new ideas.
    email mail list

  • loferboy

    Explorer to easily distinguish between day and night, but also
    has a tough shell, which is true for the expedition challenge the
    limits.
    website

  • anasqureshi

    The internet has made this things even more easier too. You will be able
    to add some really nice special effects by using some good editing
    programs, which shall enhance the appearance of the video
    Ultrasound Technician
    Overview

  • loferboy

    I found this blog. Thank you for sharing with us,I too always learn something new from your post.
    hand car wash supplies

  • AJ seo1

    Man paraphernalia online or HAT.ZE, a website dedicated to selling comically expensive baseball hats to wealthy young people
    cheap commercial insurance

  • loferboy

    Harden has served as Secretary Tom
    Vilsack’s chief of staff and assistant secretary for congressional
    relations.
    view website

  • loferboy

    I really loved reading your blog. It was very well authored and easy to
    understand. Unlike other blogs I have read which are really not that
    good
    site here

  • loferboy

    This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion.
    web designer los angeles

  • loferboy

    I am happy to find this post very useful for me, as it contains lot of
    information. I always prefer to read the quality content and this thing I
    found in you post.
    read more here

  • maaz seo

    I really loved reading your blog. It was very well authored and easy to
    understand
    taxi from delhi to jaipur

  • robinseo

    offensive or abusive will be edited or removed and we reserve the right to suspend the accounts of users posting such material.
    https://www.rebelmouse.com/oldschoolnewbodypdfreview/

  • garida

    Im glad to have found this post as its such an interesting one! I am
    always on the lookout for quality posts and articles so i suppose im
    lucky to have found this! I hope you will be adding more in the
    future…
    anti inflammatory agents

  • https://www.facebook.com/ SEO Worker

    Good quality info. Lucky to me I came to your website not on purpose, but now I have bookmarked it.
    severe tmj symptoms

  • maaz seo

    I am a big believer in commenting on blogs to inform the blog
    writers know that they’ve added something worthwhile

    packers and movers pune to hyderabad

  • maaz seo

    Lucky to me I came to your website not on purpose, but now I have bookmarked it.
    idaho falls diesel repair

  • https://www.facebook.com/ SEO Worker

    This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up .
    tankless water heater san diego

  • robinjack529

    We work closely with all the Hotels in Sri Lanka We ensure the comfort
    and safety to our clients by providing comfortable
    Low
    OBL backlinks < 100

  • https://www.facebook.com/ SEO Worker

    I really loved reading your blog. It was very well authored and easy to understand. Unlike other blogs I have read which are really not that good.
    lawsuit attorneys

  • https://www.facebook.com/ SEO Worker

    Wonderful blog! I found it while surfing around on Yahoo News. Do you
    have any suggestions on how to get listed in Yahoo News? I’ve been
    trying for a while but I never seem to get there! Appreciate it.
    ebook design

  • robinjack529

    I actually thought you have something interesting to say. All I hear is a
    bunch of whining about something that you could fix if you werent too
    busy looking for attention
    Click Here

  • ayeshakhan

    He should be so much knowledgeable in his job so that a look at the web page will tell you what the disadvantages of the web page are and how to enhance it in a much more expert way.
    will writing service

  • https://www.facebook.com/ SEO Worker

    You make it enjoyable and you still take care of to stay it wise. I can not wait to learn far more from you. This is really a tremendous site.
    Racing Rivals Hack

  • jesus phrak

    Thank for share it. This is the first time I read and understand this issue. marvel future fight hack

  • ayeshakhan

    I was looking at some of your posts on sexy mannequin this website and I conceive this web site is really instructive! Keep putting up….
    Bra

  • loferboy

    Anda yang sedang mencari property hunian ataupun untuk dijadikan sarana
    berinvestasi. Harga tanah di Bandung cenderung meningkat, cocok bila
    dijadikan investasi untuk masa depan Anda.
    over here

  • https://www.facebook.com/ SEO Worker

    I like your post. It is good to see you verbalize from the heart and clarity on this important subject can be easily observed. more info view site.
    Tumblr verified accounts

  • roshan seo

    you feel stressed, and you don’t get enough sleep. It’s normal to feel

    scared, overwhelmed, or moody for a few days after giving birth../.
    movers and packers pune

  • ayeshakhan

    Divert your calls to your personally allocated number or we’ll give you your own personal number and we’ll answer your calls for you…

    recommended reading

  • roshan seo

    I decidedly getting a charge out of every tad bit of it and I have you bookmarked to look at new stuff you weblog post..
    gurgaon to jaipur cab

  • ayeshakhan

    auto loan payments
    I really loved reading your blog. It was very well authored and easy to
    understand. Unlike other blogs I have read which are really not that
    good…

  • https://www.facebook.com/ SEO Worker

    I needed to much obliged in your time for this sublime read!! I
    decidedly getting a charge out of every tad bit of it and I have you
    bookmarked to look at new stuff you weblog post.
    instant followers

    getting likes on instagram

  • anasqureshi

    (the Wingless Wonders won the 1966 World Cup, for example). But it’s
    good for the soul to be reminded that there’s something else
    there—something that can come at you from a place beyond your quotidian
    thought. Garrincha’s innate irreverence was a thing of joy. His game
    wasn’t some mutant strain of football—it was football, only more so

    Olegario
    Vazquez Aldir