Breaking Code

April 2, 2010

Using Impacket/Pcapy with Python 2.6 on Windows

Filed under: Tools — Tags: , , , , , , , , , , — Mario Vilas @ 5:30 pm

Hello everyone! Today we’ll be installing Impacket and Pcapy for Python 2.6 on Windows. The Impacket module lets you parse network packets, this is very useful for example when developing a sniffer. The Pcapy module interfaces with WinPcap to do the actual packet capture.

From the CORE Security webpage:

What is Impacket?

Impacket is a collection of Python classes focused on providing access to network packets. Impacket allows Python developers to craft and decode network packets in simple and consistent manner. It includes support for low-level protocols such as IP, UDP and TCP, as well as higher-level protocols such as NMB and SMB. Impacket is highly effective when used in conjunction with a packet capture utility or package such as Pcapy. Packets can be constructed from scratch, as well as parsed from raw data. Furthermore, the object oriented API makes it simple to work with deep protocol hierarchies.

What is Pcapy?

Pcapy is a Python extension module that interfaces with the libpcap packet capture library. Pcapy enables python scripts to capture packets on the network. Pcapy is highly effective when used in conjunction with a packet-handling package such as Impacket, which is a collection of Python classes for constructing and dissecting network packets.

There is a problem though – Pcapy hasn’t been updated in quite a while, so there is no MSI installer for Python 2.6. I’ve built it myself and hosted in here in the blog, so you don’t have to. 🙂 I’ve also built an EXE installer for Impacket, it’s not really needed since it’s a pure Python module, but why not?

So this is the list of files we’ll be needing:

WinPcap_4_1_1.exe

pcapy-0.10.5.win32-py2.6.msi

Impacket-0.9.8.0.win32.exe

Installation is now pretty much straight forward. After running all the installers, let’s try it out with this example script to dump all connection attempts by sniffing SYN packets:

    C:\Documents and Settings\Mario Vilas\Desktop>python connections.py
    Available network interfaces:
            1 - \Device\NPF_GenericDialupAdapter
            2 - \Device\NPF_{5BE055D9-461D-4F51-99DD-188224D1A6D0}
            3 - \Device\NPF_{9B7DC2FB-7660-4E68-B4EC-DB9682C76E40}
            4 - \Device\NPF_{166A618C-4230-42E7-93AD-298D1145F5BC}
            5 - \Device\NPF_{BE987C8D-D523-49B8-8B95-DDDBAA46EB3F}

    Choose an interface [0 to quit]: 2
    Listening on: \Device\NPF_{5BE055D9-461D-4F51-99DD-188224D1A6D0}
    Connection attempt 10.0.2.15 -> 192.168.254.254
    Connection attempt 10.0.2.15 -> 192.168.254.254
    Connection attempt 10.0.2.15 -> 192.168.254.254
    Connection attempt 10.0.2.15 -> 192.168.254.254
    Connection attempt 10.0.2.15 -> 192.168.254.254
    Connection attempt 10.0.2.15 -> 209.85.227.106
    Connection attempt 10.0.2.15 -> 209.85.227.104
    Connection attempt 10.0.2.15 -> 209.85.227.104
    Connection attempt 10.0.2.15 -> 209.85.227.104
    Connection attempt 10.0.2.15 -> 209.85.227.100
    ^C

Below is the source code to the script. Enjoy! 🙂

Updates

  • A newer version of Impacket is hosted at Google Code, so I built a new installer. The previous version of the installer, based on the version of Impacket found in the Core Security webpage, is still available here: Impacket-0.9.6.0.win32.exe
  • Ge0 has built Pcapy for Python 2.7 using MingW to avoid having a depencency against the Visual Studio runtimes. You can download it from here: pcapy.pyd

Download

connections.py

Source code

#!/usr/bin/env python

# Copyright (c) 2009-2010, Mario Vilas
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#     * Redistributions of source code must retain the above copyright notice,
#       this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice,this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the copyright holder nor the names of its
#       contributors may be used to endorse or promote products derived from
#       this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from pcapy import findalldevs, open_live
from impacket import ImpactDecoder, ImpactPacket

def get_interface():

    # Get the list of interfaces we can listen on
    ifs = findalldevs()

    # No interfaces found
    if len(ifs) == 0:
        raise RuntimeError, "Error: no available network interfaces, or you don't have enough permissions on this system."

    # A single interface was found
    if len(ifs) == 1:
        interface = ifs[0]

    # Multiple interfaces found
    else:
        print "Available network interfaces:"
        for i in xrange(len(ifs)):
            print '\t%i - %s' % (i + 1, ifs[i])
        print
        while 1:
            choice = raw_input("Choose an interface [0 to quit]: ")
            try:
                i = int(choice)
                if i == 0:
                    interface = None
                    break
                interface = ifs[i-1]
                break
            except Exception:
                pass

    # Return the selected interface
    return interface

def sniff(interface):
    print "Listening on: %s" % interface

    # Open a live capture
    reader = open_live(interface, 1500, 0, 100)

    # Set a filter to be notified only for TCP packets
    reader.setfilter('ip proto \\tcp')

    # Run the packet capture loop
    reader.loop(0, callback)

def callback(hdr, data):

    # Parse the Ethernet packet
    decoder = ImpactDecoder.EthDecoder()
    ether = decoder.decode(data)

    # Parse the IP packet inside the Ethernet packet
    iphdr = ether.child()

    # Parse the TCP packet inside the IP packet
    tcphdr = iphdr.child()

    # Only process SYN packets
    if tcphdr.get_SYN() and not tcphdr.get_ACK():

        # Get the source and destination IP addresses
        src_ip = iphdr.get_ip_src()
        dst_ip = iphdr.get_ip_dst()

        # Print the results
        print "Connection attempt %s -> %s" % (src_ip, dst_ip)

def main():
    interface = get_interface()
    if interface:
        sniff(interface)

if __name__ == "__main__":
    main()

22 Comments »

  1. Esta línea:

    # Parse the IP packet inside the Ethernet packet
    iphdr = packet.child()

    No debería ser en realidad:

    iphdr = ether.child()

    ?

    Comment by Caribú — April 3, 2010 @ 6:50 am

  2. @Caribu: Si, se me escapo un typo por hacer cambios de ultimo momento, lo corrijo ahora mismo. Gracias! 🙂

    Comment by Mario Vilas — April 3, 2010 @ 1:27 pm

  3. Crossposted at the Reversing.AR blog:

    http://blog.reversing.com.ar/2010/04/using-impacketpcapy-with-python-2-6-on-windows/

    Comment by Mario Vilas — April 3, 2010 @ 10:12 pm

  4. Thanks dude! I love your work. Gracias!

    Comment by Arya — April 6, 2010 @ 3:39 am

  5. Je, groso! Que bueno! yo estaba usando las versiones de la pagina de oss de COre, a ver las de google code, a ver!

    Comment by diegobt — August 5, 2010 @ 12:56 am

  6. […] pentest, python, reverse engineering, SMB, tool, vulnerability research, win32, Windows Breaking Code This entry was posted in Breaking Code and tagged Impacket/Pcapy, Python, Using, Windows. […]

    Pingback by Using Impacket/Pcapy with Python 2.6 on Windows | Linux-backtrack.com — January 24, 2011 @ 6:57 pm

  7. Good, i appreciate the work of impacket maker… btw, my time for learning network deeply more effective with impacket.

    Comment by keyp@d — May 22, 2011 @ 2:14 pm

  8. […] – tested […]

    Pingback by Aircrack-ng&Tcpdump « Mihaela Loredana — April 20, 2012 @ 5:30 pm

  9. Hi, how did you build yourself your msi installer? I try to do it myself with Python 2.7 actually…
    Thx

    Comment by Ge0 — July 16, 2012 @ 1:48 pm

  10. Hi Ge0, I didn’t do anything special, just ran setup.py bdist_wininst. I suppose bdist_msi works just the same, it’s a source only package so there should be no problems… let me know if this doesn’t work for you and I’ll check it out.

    Comment by Mario Vilas — July 16, 2012 @ 2:32 pm

  11. Hi Mario,
    Many thanks for your fast reply.
    Actually I also tried to build something with the well known “setup.py install”, but after that I get an error such “error: Unable to find vcvarsall.bat”, even though the intersting batch file is located in a dir specified in PATH. I use VS2010 for information.

    Did you encounter such any problem so far?

    Cheers

    Comment by Ge0 — July 16, 2012 @ 2:46 pm

  12. Hi Ge0, try running the script from the Visual Studio Command Prompt instead of a regular cmd.exe console. That should fix any lurking environment problems besides the PATH. I’ll try downloading the latest source code and trying it on my end to see what happens.

    Comment by Mario Vilas — July 16, 2012 @ 2:56 pm

  13. Ok, I evidently got it mixed up with Impacket because Pcapy isn’t installing right out of the box for me either. It sucks that I didn’t think of writing down how I did it back then. 😦

    So I tried again. First I downloaded the WinPcap development files, extracted them in C:\WpdPack and then run the setup.py script from the Visual Studio console: setup.py build_ext –include-dirs C:\WpdPack\Include –library-dirs C:\WpdPack\Lib. This worked properly for 32 bits for failed with a link error for 64 bits, I fixed that changing the following: –library-dirs C:\WpdPack\Lib\x64. Now that the C code is compiled just do setup.py install and it works, same for setup.py bdist_msi. For bdist_wininst you should add the –user-access-control=auto command line switch.

    Comment by Mario Vilas — July 16, 2012 @ 3:19 pm

  14. Oh, BTW, in Impacket (not Pcapy) you also have to fix the version number in setup.py, it reports itself as an older version.

    Comment by Mario Vilas — July 16, 2012 @ 3:21 pm

  15. Hey Mario, you’ve definitely done great job so far. I have also found a straightforward how-to there: http://louppen.wordpress.com/2011/06/22/installing-the-sulley-fuzzer-framework-on-windows-xp-professional-the-trial-and-error-way/

    I shall tell you once this hell comes over.

    Cheers

    Comment by Ge0 — July 16, 2012 @ 4:07 pm

  16. Nice find! They’re using MingW instead of Visual Studio, I like that 🙂

    I’ve uploaded the new installers I just built, seems to work on my machine, but they probably depend on the Visual Studio runtime now. If you get it to work with MingW and you upload the results let me know and I’ll link it from here.

    Cheers!

    Comment by Mario Vilas — July 16, 2012 @ 4:19 pm

  17. All right, I get .pyd files instead of msi, is it that you want or do I have to perform another task?

    Comment by Ge0 — July 16, 2012 @ 4:23 pm

  18. However you wish, if you upload them somewhere just send me the link and I’ll add it.

    Comment by Mario Vilas — July 16, 2012 @ 4:26 pm

  19. Ok here it is.

    pcapy.pyd, built with MinGW: http://dl.free.fr/cYBGCMLKq (Careful, the link won’t be available beyond 30 days)

    Please let me know if it is not sufficient.

    For impacket I did not have to build anything, sounds good then.

    Thanks!

    Comment by Ge0 — July 16, 2012 @ 4:34 pm

  20. Done, linked here. I’ve also added a link to your blog. Cheers! 🙂

    Comment by Mario Vilas — July 16, 2012 @ 4:41 pm

  21. Thanks, that’s nice. I have done the same on my blog.

    Catch up with you later on twitter! 😉

    Comment by Ge0 — July 16, 2012 @ 5:14 pm

  22. His Great grandfather was pure African who married a mulatto lady by the name of Brodber. Decided to assist elect a black President and flip the United States into one large mitochondria. We don’t even try to be that way, we just are.

    Comment by Belkis Bravard — June 19, 2021 @ 9:22 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Create a free website or blog at WordPress.com.