Monday, April 30, 2012

Execute ShellCode Using Python

After writing shell code generally we use a C code like this to test our shell code.
char code[] = "shell code";
int main(int argc, char **argv)
  int (*func)();
  func = (int (*)()) code;

In this article I am going to show you, how can we use python and its "ctypes" library to execute a "calc.exe" shell code or any other shell code.ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

I will be using six Win32 APIs to execute the shell code. These Win32 apis are very important in dynamic memory management on windows platform. Here ctype will help us to directly interact with these required APIs.

The concept is like :

1)  First VirtualAlloc() will allow us to create a new executable memory region and copy our shellcode to it, and after that execute it.
2)  VirtualLock() locks the specified region of the process's virtual address space into physical memory, ensuring that subsequent access to the region will not incur a page fault.
It accepts a pointer to the base address of the region of pages to be locked and the size of the region to be locked, in bytes.
A simple example of this function can be found here in MSDN:

3)  RtlMoveMemory() function accepts 3 arguments , a pointer to the destination (returned form virtualAlloc()), Pointer to the memory to be copied and the number of bytes to be copied.

4)  CreateThread() accepts 6 arguments
In our case the third argument is very important.We need to pass a pointer to the application-defined function to be executed by the thread returned by VirtualAlloc().If the function succeeds, the return value is a handle to the new thread.

5)  WaitForSingleObject() function accepts 2 arguments 1st one is the handle to the object (Returned by CreateThread()) and the time-out interval, in milliseconds. If a nonzero value is specified, the function waits until the object is signaled or the interval elapses.

API Description (Source : MSDN)

VirtualAlloc function:
It reserves or commits a region of pages in the virtual address space of the calling process. Memory allocated by this function is automatically initialized to zero, unless MEM_RESET isspecified.

  __in_opt  LPVOID lpAddress,
  __in      SIZE_T dwSize,
  __in      DWORD flAllocationType,
  __in      DWORD flProtect

VirtualLock function:
It locks the specified region of the process's virtual address space into physical memory, ensuring that subsequent access to the region will not incur a page fault.

BOOL WINAPI VirtualLock(
  __in  LPVOID lpAddress,
  __in  SIZE_T dwSize

RtlMoveMemory routine:
The RtlMoveMemory routine moves memory either forward or backward, aligned or unaligned, in 4-byte blocks, followed by any remaining bytes.

VOID RtlMoveMemory(
  __in  VOID UNALIGNED *Destination,
  __in  const VOID UNALIGNED *Source,
  __in  SIZE_T Length

CreateThread function:
Creates a thread to execute within the virtual address space of the calling process.

  __in_opt   LPSECURITY_ATTRIBUTES lpThreadAttributes,
  __in       SIZE_T dwStackSize,
  __in       LPTHREAD_START_ROUTINE lpStartAddress,
  __in_opt   LPVOID lpParameter,
  __in       DWORD dwCreationFlags,
  __out_opt  LPDWORD lpThreadId

WaitForSingleObject function:
Waits until the specified object is in the signaled state or the time-out interval elapses.

DWORD WINAPI WaitForSingleObject(
  __in  HANDLE hHandle,
  __in  DWORD dwMilliseconds

The python code goes here.

import ctypes
#x86/shikata_ga_nai succeeded with size 227 (iteration=1)
#Metasploit windows/exec calc.exe
shellcode = bytearray(
ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),
buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)
ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),


  1. I really appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You’ve made my day! Thx again!
    python Training institute in Bangalore
    python Training in Pune

  2. I am sure this post has helped me save many hours of browsing other related posts just to find what I was looking for. Many thanks!
    Python Online training
    Python Course institute in Bangalore

  3. Such an ideal piece of blog. It’s quite interesting to read content like this. I appreciate your blog
    Data Science Certification

  4. Its as if you had a great grasp on the subject matter, but you forgot to include your readers. Perhaps you should think about this from more than one angle.
    python training in bangalore

  5. Thank you for excellent article.You made an article that is interesting.
    Tavera car for rent in coimbatore|Indica car for rent in coimbatore|innova car for rent in coimbatore|mini bus for rent in coimbatore|tempo traveller for rent in coimbatore|kodaikanal tour package from chennai

    Keep on the good work and write more article like this...

    Great work !!!!Congratulations for this blog

  6. Nice blog post on Python. Python is used in data science as well.Please refer to my blog here.

    python training in hyderabad

  7. Thank you for providing the valuable information …
    If you want to connect with AI (Artificial Intelligence) World
    as like


    RPA (Robotic Process Automation)

    UiPath Training

    Blue Prism

    Data -Science

    ML(Machine Learning)
    related more information then meet on EmergenTeck Training Institute .

    Thank you.!

  8. This blog is very informative. It has very good information about python course training in banglore
    which will help user to be clear about the course and future oppurtunity.
    python training in banglore

  9. Best place to learn python in Bangalore. myTectra!
    Python training in bangalore

  10. This is quite educational arrange. It has famous breeding about what I rarity to vouch. Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved. This arrange is synchronous s informative impolites festivity to pity. I appreciated what you ok extremely here 
    Apache Spark with Scala certification training
    AWS certification training

  11. Nice Blog.
    For Data Science training in Bangalore, Visit:
    Data Science training in Bangalore

  12. A universal message I suppose, not giving up is the formula for success I think. Some things take longer than others to accomplish, so people must understand that they should have their eyes on the goal, and that should keep them motivated to see it out til the end.
    Salesforce online training
    Hadoop online training

  13. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
    Apache Spark with Scala online training
    AWS online training

  14. Nice Blog
    Visit for Data Science training in Bangalore :
    Data Science training in Bangalore

  15. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    AWS online training
    Advanced Java online training

  16. Soma pill is very effective as a painkiller that helps us to get effective relief from pain. This cannot cure pain. Yet when it is taken with proper rest, it can offer you effective relief from pain.
    This painkiller can offer you relief from any kind of pain. But Soma 350 mg is best in treating acute pain. Acute pain is a type of short-term pain which is sharp in nature. Buy Soma 350 mg online to get relief from your acute pain.

    Buy Soma 350 mg
    Soma Pill
    Buy Soma 350 mg online

    Buy Soma 350 mg online
    Soma Pill
    Buy Soma 350 mg

  17. I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on some general things, The web site style is perfect, the articles is really great : D. Good job, cheers.
    tree trimmers greenacres

  18. Hi, This is nice article you shared great information i have read it thanks for giving such a wonderful Blog for reader.
    bathroom remodel long beach ca

  19. You have a good point here!I totally agree with what you have said!!Thanks for sharing your views...hope more people will read this article!!!
    tree service palm beach gardens

  20. I think this is one of the most significant information for me. And i’m glad reading your article. But should remark on some general things, The web site style is perfect, the articles is really great : D. Good job, cheers Website

  21. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place. patio screen repair fort lauderdale

  22. In DevOps Training course online you will be introduced to the DevOps pipeline demo in various industry domains like media, finance, medical projects and more. You will get hands-on experience in Docker containerization by deploying Jenkins, working with integration tests in DevOps, Project Reports and finance app configuration.

  23. It has been great for me to read such great information about python Training.python training in bangalore

  24. Thank you for excellent article.You made an article that is interesting.
    Best AWS certification training courses. Build your AWS cloud skills with expert instructor- led classes. Live projects, Hands-on training,24/7 support.

  25. Thank you for sharing this information.your information very helpful for my business. I have gained more information about your sites. I am also doing business related this.
    Thank you.
    Data Science Training in Hyderabad

    Hadoop Training in Hyderabad

    Java Training in Hyderabad

    Python online Training in Hyderabad

  26. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    top angular js online training

  27. I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously in their life, he/she can earn his living by doing blogging.thank you for thizs article. best devops online training