Coder Social home page Coder Social logo

phaethon / kamene Goto Github PK

View Code? Open in Web Editor NEW
863.0 48.0 193.0 2.59 MB

Network packet and pcap file crafting/sniffing/manipulation/visualization security tool. Originally forked from scapy in 2015 and providing python3 compatibility since then.

License: GNU General Public License v2.0

Python 99.94% Shell 0.03% Batchfile 0.03%
scapy pcap network-scanner security packet-crafting sniff python3

kamene's Introduction

kamene (formerly known as "scapy for python3" or scapy3k)

General

Follow @pkt_kamene for recent news. Original documentation updated for kamene

News

We underwent naming transition (of github repo, pip package name, and python package name), which will be followed by new functionality. More updates to follow.

Kamene is included in the Network Security Toolkit Release 28. It used to be included in NST since Release 22 under former name.

History

This is a fork of scapy (http://www.secdev.org) originally developed to implement python3 compatibility. It has been used in production on python3 since 2015 (while secdev/scapy implemented python3 compatibility in 2018). The fork was renamed to kamene in 2018 to reduce any confusion.

These features were first implemented in kamene and some of them might have been reimplemented in scapy by now:

  • replaced PyCrypto with cryptography.io (thanks to @ThomasFaivre)
  • Windows support without a need for libdnet
  • option to return Networkx graphs instead of image, e.g. for conversations
  • replaced gnuplot with Matplotlib
  • Reading PCAP Next Generation (PCAPNG) files (please, add issues on GitHub for block types and options, which need support. Currently, reading packets only from Enhanced Packet Block)
  • new command tdecode to call tshark decoding on one packet and display results, this is handy for interactive work and debugging
  • python3 support

Installation

Install with python3 setup.py install from source tree (get it with git clone https://github.com/phaethon/kamene.git) or pip3 install kamene for latest published version.

On all OS except Linux libpcap should be installed for sending and receiving packets (not python modules - just C libraries) or winpcap driver on Windows. On some OS and configurations installing libdnet may improve experience (for MacOS: brew install libdnet). On Windows libdnet is not required. On some less common configurations netifaces may improve experience.

Usage

Use bytes() (not str()) when converting packet to bytes. Most arguments expect bytes value instead of str value except the ones, which are naturally suited for human input (e.g. domain name).*

You can use kamene running kamene command or by importing kamene as library from interactive python shell (python or ipython) or code. Simple example that you can try from interactive shell:

from kamene.all import *
p = IP(dst = 'www.somesite.ex') / TCP(dport = 80) / Raw(b'Some raw bytes')
# to see packet content as bytes use bytes(p) not str(p)
sr1(p)

Notice 'www.somesite.ex' as a string, and b'Some raw bytes' as bytes. Domain name is normal human input, thus it is string, raw packet content is byte data. Once you start using, it will seem easier than it looks.

Use ls() to list all supported layers. Use lsc() to list all commands.

Currently, works on Linux, Darwin, Unix and co. Using python 3.4+ on Ubuntu, MacOS, FreeBSD, Windows 10 for testing.

Compatible with scapy-http module

Reading huge pcap file

rdpcap reads whole pcap file into memory. If you need to process huge file and perform some operation per packet or calculate some statistics, you can use PcapReader with iterator interface.

with PcapReader('filename.pcap') as pcap_reader:
  for pkt in pcap_reader:
    #do something with the packet

kamene's People

Contributors

0x5e avatar belboj avatar bioh4z4rd avatar bobsaintcool avatar desbma avatar futuresharks avatar iluxonchik avatar invernizzi avatar jamesgries avatar jessicaspencer avatar johnthagen avatar lawnmowerlatte avatar mateo13 avatar matsoken avatar miziaiba avatar mordechaimaman avatar pgawlowicz avatar phaethon avatar polybassa avatar ppietikainen avatar richard-kinder avatar rwhalb avatar sshresthacp avatar sumpfgottheit avatar syakesaba avatar tan-wei avatar teruyam avatar therealtailopez avatar tmblazek avatar ybrustin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

kamene's Issues

hide_default()

Using hide_defaults() example from documentation gives this error:

----> 1 c.hide_defaults()

/home/phaethon/projects/scapy/scapy/packet.py in hide_defaults(self)
    650                 if self.default_fields[k] == self.fields[k]:
    651                     del(self.fields[k])
--> 652         self.payload.hide_defaults()
    653 
    654     def clone_with(self, payload=None, **kargs):

/home/phaethon/projects/scapy/scapy/packet.py in hide_defaults(self)
    646     def hide_defaults(self):
    647         """Removes fields' values that are the same as default values."""
--> 648         for k in self.fields.keys():
    649             if k in self.default_fields:
    650                 if self.default_fields[k] == self.fields[k]:

RuntimeError: dictionary changed size during iteration

AttributeError: 'NoneType' object has no attribute 'encode' when running on Windows 10

System: Windows 10
Python: 3.4
scapy-python3: 0.18

When starting sniff I get the following traceback:

Traceback (most recent call last):
  File "C:/Users/yop/dev/sentinel/honeysyn/honeysyn.py", line 82, in <module>
    scapy.sniff(iface=h.config['interface'], prn=h.filtre)
  File "C:\Python34\lib\site-packages\scapy\arch\windows\__init__.py", line 444, in sniff
    s = L2socket(type=ETH_P_ALL, *arg, **karg)
  File "C:\Python34\lib\site-packages\scapy\arch\pcapdnet.py", line 266, in __init__
    self.ins = open_pcap(iface, 1600, self.promisc, 100)
  File "C:\Python34\lib\site-packages\scapy\arch\windows\__init__.py", line 222, in <lambda>
    pcapdnet.open_pcap = lambda iface,*args,**kargs: _orig_open_pcap(pcap_name(iface),*args,**kargs)
  File "C:\Python34\lib\site-packages\scapy\arch\pcapdnet.py", line 251, in <lambda>
    open_pcap = lambda *args,**kargs: _PcapWrapper_pypcap(*args,**kargs)
  File "C:\Python34\lib\site-packages\scapy\arch\pcapdnet.py", line 215, in __init__
    self.iface = create_string_buffer(device.encode('ascii'))
AttributeError: 'NoneType' object has no attribute 'encode'

The interface which is used via the iface parametr is {FEC67D86-A8E0-4362-8D9E-CD8EA834EB0C}. I retrieved it via Get-NetAdapter | select Name, InterfaceIndex, InterfaceDescription, InterfaceGuid, MacAddress | fl (or netifaces) and it is the Ethernet card.

The same code ran on Linux works fine (with the relevant interface, of course)

Powershell ExecutionPolicy Problem

OS: Windows 10
Python 3.5.1

When running from scapy.all import *, a ValueError exception is thrown.
Here is a sample output:

WARNING: Windows support for scapy3k is currently in testing. Sniffing/sending/receiving packets should be working with WinPcap d
river and Powershell. Create issues at https://github.com/phaethon/scapy
Traceback (most recent call last):
  File ".\arper.py", line 1, in <module>
    from scapy.all import *
  File "C:\ProgramData\chocolatey\lib\python3\tools\lib\site-packages\scapy\all.py", line 16, in <module>
    from .arch import *
  File "C:\ProgramData\chocolatey\lib\python3\tools\lib\site-packages\scapy\arch\__init__.py", line 88, in <module>
    from .windows import *
  File "C:\ProgramData\chocolatey\lib\python3\tools\lib\site-packages\scapy\arch\windows\__init__.py", line 200, in <module>
    ifaces.load_from_powershell()
  File "C:\ProgramData\chocolatey\lib\python3\tools\lib\site-packages\scapy\arch\windows\__init__.py", line 151, in load_from_pow
ershell
    for i in get_windows_if_list():
  File "C:\ProgramData\chocolatey\lib\python3\tools\lib\site-packages\scapy\arch\windows\__init__.py", line 87, in get_windows_if
_list
    name, value = [ j.strip() for j in i.split(':') ]
ValueError: too many values to unpack (expected 2)

This occurred because in scapy\arch\windows\__init__.py line 78, where the powershell is started an error message saying that the profile could not be loaded due to ExecutionPolicy is shown before the output of Get-NetAdapter. Here is an example of that message:

. : File C:\Users\USERNAME\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 cannot be loaded because running
scripts is disabled on this system. For more information, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:3
+ . 'C:\Users\iluxo\Documents\WindowsPowerShell\Microsoft.PowerShell_pr ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

A simple solution would be to pass an additional -NoProfile option when starting the powershell subprocess. This is probably a better way of doing it anyways, since if that flag is not passed, the poweshell will first load the profile and only then run the Get-NetAdapter command, which takes some extra time.

DHCP6OptIAAddress may create DHCP option data

Type the command was shown below to create a dhcpv6 reply packet.

dhcpv6Reply=Ether(type=34525, dst='00:e0:4c:36:00:db', src='00:0c:29:10:0d:12')/IPv6(nh=17, src='fe80::20c:29ff:fe10:d12', fl=0, tc=0, dst='fe80::ade6:e8b1:d7da:dff2', version=6, hlim=64)/UDP(sport=547, dport=546)/DHCP6_Reply(msgtype=7, trid=4692328)/DHCP6OptIA_NA(T2=0, optcode=3, ianaopts=[DHCP6OptIAAddress(optcode=5, addr='2001:db8:0:1::253', preflft=375, validlft=600)], T1=0, iaid=738254924)/DHCP6OptClientId(optcode=1, duid=DUID_LLT(type=1, lladdr='38:2c:4a:c9:3d:a4', timeval=474539933, hwtype=1))/DHCP6OptServerId(optcode=2, duid=DUID_LLT(type=1, lladdr='00:0c:29:10:0d:12', timeval=492749262, hwtype=1))

Send this packet and capture this packet by Wireshark.

dhcp6optiaaddress issue

In red block, the DHCP option was created but the command doesn't include any DHCPv4 options.
For windows 7 DHCPv6 client, it looks like cannot be received.
The IPv6 will be released..

srp fails to capture ICMPv6EchoReply if EchoRequest has data

I send a simple ICMPv6EchoRequest to a remote device, and want to capture the response (a good old IPv6 "ping").

  • With a ICMPv6EchoRequest without data, scapy.all.srp captures the response as expected
  • With a ICMPv6EchoRequest with data, scapy.all.srp fails to capture a response
  • Using scapy.all.sniff response is captured as expected (I use this workaround for now)
  • Wireshark sees the request and response fine in all cases
  • ping6 command line utility works fine too

Here is a full test case to reproduce (ping from LOCAL_IP to REMOTE_IP), test_captureWithSniff succeeds and test_captureWithSrp fails:

#!/usr/bin/env python3

import os
import threading
import unittest

import scapy.all


REMOTE_MAC = "00:01:02:03:04:05"  # change for your config
REMOTE_IP = "2015::2"
LOCAL_ITF = "eth5"
LOCAL_IP = "2015::1"


class SniffThread(threading.Thread):

  def __init__(self, *args, **kwargs):
    self.args = args
    self.kwargs = kwargs
    self.received = []
    super().__init__()

  def run(self):
    self.received.extend(scapy.all.sniff(*self.args, **self.kwargs))


class TestPingScapySrpIssue(unittest.TestCase):

  def test_captureWithSniff(self):
    for ping_data in (None, os.urandom(8)):
      # build eth frame
      eth = scapy.all.Ether(src=scapy.all.get_if_hwaddr(LOCAL_ITF),
                            dst=REMOTE_MAC)
      ipv6 = scapy.all.IPv6(src=LOCAL_IP,
                            dst=REMOTE_IP)
      icmp = scapy.all.ICMPv6EchoRequest()
      frame = eth / ipv6 / icmp
      if ping_data is not None:
        frame = frame / ping_data

      # send it and get response
      sniff_thread = SniffThread(timeout=1,
                                 iface=LOCAL_ITF,
                                 lfilter=lambda x: x.haslayer("ICMPv6EchoReply"))
      sniff_thread.start()
      scapy.all.sendp(frame, iface=LOCAL_ITF, verbose=False)
      sniff_thread.join()

      # build expected response
      expected_eth = scapy.all.Ether(src=REMOTE_MAC,
                                     dst=scapy.all.get_if_hwaddr(LOCAL_ITF))
      expected_ipv6 = scapy.all.IPv6(src=REMOTE_IP,
                                     dst=LOCAL_IP)
      expected_icmp = scapy.all.ICMPv6EchoReply()
      expected_frame = expected_eth / expected_ipv6 / expected_icmp
      if ping_data is not None:
        expected_frame = expected_frame / ping_data

      # check response
      self.assertEqual(len(sniff_thread.received), 1)
      self.assertEqual(bytes(sniff_thread.received[0]), bytes(expected_frame))

  def test_captureWithSrp(self):
    for ping_data in (None, os.urandom(8)):
      # build eth frame
      eth = scapy.all.Ether(src=scapy.all.get_if_hwaddr(LOCAL_ITF),
                            dst=REMOTE_MAC)
      ipv6 = scapy.all.IPv6(src=LOCAL_IP,
                            dst=REMOTE_IP)
      icmp = scapy.all.ICMPv6EchoRequest()
      ping_data = os.urandom(8)
      frame = eth / ipv6 / icmp
      if ping_data is not None:
        frame = frame / ping_data

      # send it and get response
      answered, unanswered = scapy.all.srp(frame,
                                           iface=LOCAL_ITF,
                                           timeout=1,
                                           verbose=False)

      # build expected response
      expected_eth = scapy.all.Ether(src=REMOTE_MAC,
                                     dst=scapy.all.get_if_hwaddr(LOCAL_ITF))
      expected_ipv6 = scapy.all.IPv6(src=REMOTE_IP,
                                     dst=LOCAL_IP)
      expected_icmp = scapy.all.ICMPv6EchoReply()
      expected_frame = expected_eth / expected_ipv6 / expected_icmp
      if ping_data is not None:
        expected_frame = expected_frame / ping_data

      # check response
      self.assertEqual(len(answered), 1)  # fails here if ping_data != None
      self.assertEqual(bytes(answered[0]), bytes(expected_frame))


if __name__ == "__main__":
    unittest.main()

Context :

  • Ubuntu 14.04
  • Python 3.4
  • Scapy v0.13 from this repo.

Error when building DHCP packet

from scapy.all import *

ethernet = Ether(dst='ff:ff:ff:ff:ff:ff', type=0x800)
udp = UDP(sport=68, dport=67)
bootp = BOOTP(ciaddr='0.0.0.0', flags=1)
dhcp = DHCP(options=[("message-type", "discover"), "end"])
packet = ethernet / udp / bootp / dhcp

print(packet)

Running the above code will yield the error below:

Traceback (most recent call last):
  File "/Users/zachary/script.py", line 9, in <module>
    print(packet)
  File "/usr/local/lib/python3.5/site-packages/scapy/packet.py", line 283, in __str__
    return repr(bytes(self)) 
  File "/usr/local/lib/python3.5/site-packages/scapy/packet.py", line 285, in __bytes__
    return self.build()
  File "/usr/local/lib/python3.5/site-packages/scapy/packet.py", line 353, in build
    p = self.do_build()
  File "/usr/local/lib/python3.5/site-packages/scapy/packet.py", line 345, in do_build
    pay = self.do_build_payload()
  File "/usr/local/lib/python3.5/site-packages/scapy/packet.py", line 337, in do_build_payload
    return self.payload.do_build()
  File "/usr/local/lib/python3.5/site-packages/scapy/packet.py", line 345, in do_build
    pay = self.do_build_payload()
  File "/usr/local/lib/python3.5/site-packages/scapy/packet.py", line 337, in do_build_payload
    return self.payload.do_build()
  File "/usr/local/lib/python3.5/site-packages/scapy/packet.py", line 342, in do_build
    pkt = self.self_build()
  File "/usr/local/lib/python3.5/site-packages/scapy/packet.py", line 333, in self_build
    p = f.addfield(self, p, val)
  File "/usr/local/lib/python3.5/site-packages/scapy/fields.py", line 365, in addfield
    return s+self.i2m(pkt, val)
  File "/usr/local/lib/python3.5/site-packages/scapy/fields.py", line 362, in i2m
    x=str(x).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\x82' in position 1: ordinal not in range(128)

Process finished with exit code 1

Windows 10 64bit WinError126

Hi all, when I try running:
from scapy.all import *

I get the error: [WinError 126] The specified module could not be found

After looking at the traceback in ipython it looks like an exception is found when trying to access _lib=CDLL('wpcap.dll').

I installed scapy-python3 using pip, any ideas?

Use generators for packet list.

This is an enhancement suggestion.

Presently only lists can be used, can we add generator support?

import ipaddress
from scapy.all import *

# this works
res = sr([IP(dst=str(ip)) / ICMP() for ip in ipaddress.ip_network('10.200.0.0/24')], timeout=3)

# generators do not
res = sr((IP(dst=str(ip)) / ICMP() for ip in ipaddress.ip_network('10.200.0.0/24')), timeout=3)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-943976262ad1> in <module>()
----> 1 res = sr((IP(dst=str(ip)) / ICMP() for ip in ipaddress.ip_network('10.200.0.0/24')), timeout=3)

/usr/local/lib/python3.5/site-packages/scapy/sendrecv.py in sr(x, filter, iface, nofilter, *args, **kargs)
    325         kargs["timeout"] = -1
    326     s = conf.L3socket(filter=filter, iface=iface, nofilter=nofilter)
--> 327     a,b=sndrcv(s,x,*args,**kargs)
    328     s.close()
    329     return a,b

/usr/local/lib/python3.5/site-packages/scapy/sendrecv.py in sndrcv(pks, pkt, timeout, inter, verbose, chainCC, retry, multi)
     53     hsent={}
     54     for i in tobesent:
---> 55         h = i.hashret()
     56         if h in hsent:
     57             hsent[h].append(i)

AttributeError: 'generator' object has no attribute 'hashret'

unknown os's with p0f module

Hi, I'd like to use p0f module to determine os's on local network.
But when I run:

>>> load_module("p0f")
>>> a=sniff(prn=prnp0f)

I see only unknown:

192.168.1.103:ssh - UNKNOWN [260:64:1.0:0:.:AFD:?:?]
  -> 192.168.1.95:59213 (PA)
192.168.1.103:ssh - UNKNOWN [260:64:1.0:0:.:AFD:?:?]
  -> 192.168.1.95:59213 (PA)

I use raspbian with p0f 2.0.8 and scapy 3.0.0.
What possible solutions may be for such problem?

Scapy3 on Windows7

I am trying to explore scapy3 on a Windows7 platform and was successful with installing the required packages. I am a beginner in this tool and I am trying a few examples from the documentation page. I understand that scapy3 on a Windows platform is still under testing, but here in my organisation we use Python3.4 on a Windows platform and hence the need to try this tool on a Windows platform. To start with a very basic step, I was able to create a IP packet with some destination address, but when I execute the show() command, I get the following error.

"

In [9]: IP().show()
←[0m###[←[0m ←[31m←[1mIP←[0m ←[0m]###←[0m
←[34mversion←[0m←[0m=←[0m ←[35m4←[0m
←[34mihl←[0m←[0m=←[0m ←[35mNone←[0m
←[34mtos←[0m←[0m=←[0m ←[35m0x0←[0m
←[34mlen←[0m←[0m=←[0m ←[35mNone←[0m
←[34mid←[0m←[0m=←[0m ←[35m1←[0m
←[34mflags←[0m←[0m=←[0m ←[35m←[0m
←[34mfrag←[0m←[0m=←[0m ←[35m0←[0m
←[34mttl←[0m←[0m=←[0m ←[35m64←[0m
←[34mproto←[0m←[0m=←[0m ←[35mip←[0m
←[34mchksum←[0m←[0m=←[0m ←[35mNone←[0m
←[34m←[4m←[1msrc←[0m←[0m=←[0m ←[35m←[4m←[1m0.0.0.0←[0m
←[34m←[4m←[1mdst←[0m←[0m=←[0m ←[35m←[4m←[1m127.0.0.1←[0m
\←[34moptions←[0m\

In [10]:"
I see that this could be some kind of encoding / decoding issue. Have anybody tried this and come across this issue? Any help is much appreciated.

IPv6 ICMP Echo Request is sent to broadcast MAC-address

Hi,

I've tried to send a crafted IPv6 ICMP Echo Request via scapy for Python 3.4 and noticed the warning:

>>> sr1(IPv6(dst='2a00:1450:4013:c00::71')/ICMPv6EchoRequest(), timeout=1)
Begin emission:
.WARNING: Mac address to reach destination not found. Using broadcast.
Finished to send 1 packets.
....................................................................................
Received 85 packets, got 0 answers, remaining 1 packets

The dump file could be found here. You can see, that Echo Request frame is sent to broadcast MAC-address FF:FF:FF:FF:FF:FF.

The same command with version for python 2 works okay.
Am I doing smth wrong? I've tried setting dst mac-address in Ether, but the packet is still sent to broadcast.

Cheers.

parsing pcap through paramiko and named_pipe results in bad magic exception

Hi I have a simple application that i was trying to change from python2 to python3.
It's using paramiko to setup a ssh connection to a router and run a tcpdump, pump the results through a named pipe to scapy's sniffer.

It runs perfectly well with python2 and scapy, but i'm running into this exception with python3 and scapy3k, i printed out the magic, and it indeed is not what is expected according to the source.
bad magic: b'T\xe8\x9c0'

WARNING: No route found for IPv6 destination :: (no default route?)
WARNING: Please, report issues to https://github.com/phaethon/scapy
main : DEBUG running process queue
main : DEBUG started threads
main : DEBUG Thread <ThreadingIntervalTimer(Thread-1, started daemon 140516139489024)> isDeamon: True
main : DEBUG Thread <StoppableThread(Thread-2, started daemon 140516131096320)> isDeamon: True
main : DEBUG Thread <StoppableThread(Thread-3, started daemon 140516122703616)> isDeamon: True
paramiko.transport: DEBUG starting thread (client mode): 0x39af510
paramiko.transport: INFO Connected (version 2.0, client dropbear_2014.63)
...
paramiko.transport: DEBUG userauth is OK
paramiko.transport: INFO Authentication (publickey) successful!
paramiko.transport: DEBUG [chan 0] Max packet in: 32768 bytes
paramiko.transport: DEBUG [chan 0] Max packet out: 32768 bytes
paramiko.transport: DEBUG Secsh channel 0 opened.
paramiko.transport: DEBUG [chan 0] Sesch channel 0 request ok
main : DEBUG read 24bytes
main : DEBUG read 394bytes
bad magic: b'T\xe8\x9c0'
Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python3.2/threading.py", line 740, in _bootstrap_inner
self.run()
File "wifi-mac-scraper.py", line 68, in run
self.target(*self.args)
File "wifi-mac-scraper.py", line 117, in sniffer
scapy.all.sniff(offline=_named_pipe_path, prn=process_packet, store=0)
File "/usr/local/lib/python3.2/dist-packages/scapy/sendrecv.py", line 568, in sniff
s = PcapReader(offline)
File "/usr/local/lib/python3.2/dist-packages/scapy/utils.py", line 625, in init
RawPcapReader.init(self, filename)
File "/usr/local/lib/python3.2/dist-packages/scapy/utils.py", line 549, in init
raise Scapy_Exception("Not a pcap capture file (bad magic)")
scapy.error.Scapy_Exception: Not a pcap capture file (bad magic)

^[[A^C__main__ : DEBUG received sigal: 2
main : DEBUG stopped threads
main : DEBUG Stopped ThreadingIntervalTimer

The code in question is:

def sniffer(_named_pipe_path, _q):
scapy.all.sniff(offline=_named_pipe_path, prn=process_packet, store=0)

def remotetcpdump_ssh(_named_pipe_path):

sshclient = paramiko.SSHClient()
_named_pipe = open(_named_pipe_path, 'wb', 0)

try:
    sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshclient.connect('xxx,xxx,xxx,xxx', username='xxxx', password='xxxx')

    chan = sshclient.get_transport().open_session()
    chan.exec_command('/usr/sbin/tcpdump -q -U -w - -i moni0 "wlan type mgt subtype probe-req or wlan type mgt subtype assoc-req or wlan type mgt subtype reassoc-req"')

    while True:
        if chan.recv_ready():
            data = chan.recv(66560)
            logger.debug("read " + str(len(data)) + "bytes")
            _named_pipe.write(data)
        time.sleep(0.1)

except paramiko.SSHException as _e:
    logger.debug("SSH exception: %s" % _e)
    _named_pipe.close()
    sshclient.close()
    raise

_named_pipe.close()
sshclient.close()

def remotetcpdump(_named_pipe_path):
while True:
try:
remotetcpdump_ssh(_named_pipe_path)
except:
time.sleep(5)
remotetcpdump_ssh(_named_pipe_path)

segfault caused by pcap_get_selectable_fd on Mac OS X 10.10

Code resulting in segfault:

from scapy.all import *
p = IP(dst = 'www.bing.com') / TCP(dport = 80) / Raw(b'Some raw bytes')
# to see packet content as bytes use bytes(p) not str(p)
sr1(p)

You can get some details by man pcap_get_selectable_fd
This info may be helpful:

INFO: Can't import matplotlib. Not critical, but won't be able to plot.
INFO: Can't import networkx. Not criticial, but won't be able to draw network graphs.
INFO: Can't import PyX. Won't be able to use psdump() or pdfdump().
WARNING: Could not load module netifaces: No module named 'netifaces'
INFO: No IPv6 support in kernel
WARNING: No route found for IPv6 destination :: (no default route?). This affects only IPv6
INFO: Please, report issues to https://github.com/phaethon/scapy
INFO: Can't import python Crypto lib. Won't be able to decrypt WEP.
INFO: Can't import python Crypto lib. Disabled certificate manipulation tools
Python 3.5.1 (default, Dec 7 2015, 21:59:08)

I'm not capable of debuging scapy due to some trivial ctypes related code. So.... Any suggestions?

RandIP() (at least) behaviour change due to code relying on old-style classes

This may be more ugly than seems at a first glance:

Welcome to Scapy (2.2.0-dev)
>>> print(RandIP())
251.239.113.24

vs.

Welcome to Scapy (3.0.0)
>>> print(RandIP())
<RandIP>

which is explained by the use of old-style Python 2 classes and __getattr__in VolatileValue magically fixing things up. Easily fixed by adding a

def __str__(self): 
   return self._fix()

to class VolatileValue, but then there's int(RandShort()) etc.

Quickly grepping around for previously old-style classes with __getattr__ seems like there might be other places where this may cause mysterious bugs...

bytes(SCTP()) fails

>>> bytes(SCTP())
Traceback (most recent call last):
  File "/usr/lib/python3.4/code.py", line 90, in runcode
    exec(code, self.locals)
  File "<console>", line 1, in <module>
  File "/tmp/scapy3/scapy/packet.py", line 289, in __bytes__
    return self.build()
  File "/tmp/scapy3/scapy/packet.py", line 357, in build
    p = self.do_build()
  File "/tmp/scapy3/scapy/packet.py", line 350, in do_build
    p = self.post_build(pkt,pay)
  File "/tmp/scapy3/scapy/layers/sctp.py", line 204, in post_build
    crc = crc32c(str(p))
  File "/tmp/scapy3/scapy/layers/sctp.py", line 92, in crc32c
    crc = (crc>>8) ^ crc32c_table[(crc^(c)) & 0xFF]
TypeError: unsupported operand type(s) for ^: 'int' and 'str'

$ python3 --version
Python 3.4.3+

CharEnumField throws TypeError during instantiation

Using a CharEnumField throws a TypeError when it attempts to index into the enum dictionary keys, which are dict_keys objects in python3 instead of lists.

I'm using scapy-python3 version 0.18 and python 3.5.1

Traceback:

Traceback (most recent call last):
  File "bug.py", line 3, in <module>
    class SomeLayer(Packet):
  File "bug.py", line 5, in SomeLayer
    CharEnumField("foo", "X", {"X": 1, "Y": 2})
  File "/usr/local/lib/python3.5/dist-packages/scapy/fields.py", line 766, in __init__
    if k and len(k[0]) != 1:
TypeError: 'dict_keys' object does not support indexing

Snippet to reproduce:

from scapy.all import *

class SomeLayer(Packet):
    fields_desc = [
        CharEnumField("foo", "X", {"X": 1, "Y": 2})
    ]

Converting the keys to a list first seems like a straightforward fix, i.e.:

class CharEnumField(EnumField):
    def __init__(self, name, default, enum, fmt = "1s"):
        EnumField.__init__(self, name, default, enum, fmt)
        k = list(self.i2s.keys())
        if k and len(k[0]) != 1:
            self.i2s,self.s2i = self.s2i,self.i2s

full scapy tutorial

I'm new to scapy. Am not able how to use scapy and how to import scapy modules in python script. Can any one help me to by showing simple tutorial example. I read documentation but there is no full script.

AttributeError: 'NoneType' object has no attribute 'route'

# pip install scrapy-python3
from scapy.layers.inet import traceroute
# next line is from tutorial
res,unans = traceroute(["www.microsoft.com","www.cisco.com","www.yahoo.com","www.wanadoo.fr","www.pacsec.com"],dport=[80,443],maxttl=20,retry=-2)
Traceback (most recent call last):
  File "/Users/luckydonald/Documents/Python/SimpleStuff/lan-utils.py", line 10, in <module>
    ],dport=[80,443],maxttl=20,retry=-2)
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/layers/inet.py", line 1315, in traceroute
    timeout=timeout, filter=filter, verbose=verbose, **kargs)
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/sendrecv.py", line 327, in sr
    a,b=sndrcv(s,x,*args,**kargs)
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/sendrecv.py", line 55, in sndrcv
    h = i.hashret()
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/layers/inet.py", line 377, in hashret
    return strxor(inet_aton(self.src),inet_aton(self.dst))+struct.pack("B",self.proto)+self.payload.hashret()
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/packet.py", line 195, in __getattr__
    return fld.i2h(self, v)
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/fields.py", line 260, in i2h
    iff,x,gw = conf.route.route(dst)
AttributeError: 'NoneType' object has no attribute 'route'

Mac OSX 10.9.5

mac:SimpleStuff luckydonald$ uname -a
Darwin mac.fritz.box 13.4.0 Darwin Kernel Version 13.4.0: Wed Mar 18 16:20:14 PDT 2015; root:xnu-2422.115.14~1/RELEASE_X86_64 x86_64
Python 3.4.3 (default, Aug 10 2015, 16:40:44) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin

Mac OS X wi-fi monitor sniff

There is simple wi-fi sniff script for SSIDs:

from scapy.all import *

ap_list = []
def ssid(pkt):
    print(pkt.show())
    if pkt.haslayer(Dot11):
        if pkt.type == 0 and pkt.subtype == 8:
            if pkt.addr2 not in ap_list:
                ap_list.append(pkt.addr2)
                print("AP: %s SSID: %s" % (pkt.addr2, pkt.info))

sniff(iface='en1', prn=ssid)

Where en1 is wi-fi interface.

When I run this script (from sudo or not), while I am connected to some wi-fi - there are many packets captured (no one is Beacon) (thanks to pkt.show() in script)

But if I force switch interface to monitor mode (through one of these commands)

  • sudo tcpdump -p -I -i en1 -y IEEE802_11
  • sudo tcpdump -p -I -i en1
  • airport en1 sniff 1
  • wireshark GUI capture with monitor mode

output of script stops, as there is no packets here at all (while tcpdump captures many beacons well)

Can you explain me, what I am doing wrong, or scapy-py3k needs some patching for mac os x?

gnuplot not working

gnuplot currently is not working. At least 2 known reasons:

  • unresolved import issue in plist.py affecting gnuplot
  • layers/inet.py issue with replacing new.instancemethod

explicit import scapy.config required regression vs. python2

This used to work:

Python 3.4.1 (default, Nov 3 2014, 14:38:10)
[GCC 4.9.1 20140930 (Red Hat 4.9.1-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.

from scapy.volatile import RandIP, RandMAC, RandByte, RandNum, RandIP6
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.4/site-packages/scapy/volatile.py", line 11, in
from .base_classes import Net
File "/usr/lib/python3.4/site-packages/scapy/base_classes.py", line 15, in
import scapy.config
File "/usr/lib/python3.4/site-packages/scapy/config.py", line 12, in
import scapy.base_classes as base_classes
AttributeError: 'module' object has no attribute 'base_classes'

and now I need to do import scapy.config before doing that (and also "from scapy.route import Route" to get some side-effects from that class, but that was also with python2).

I suspect most people use from scapy.all import *, which pollutes your namespace quite badly + takes a measurable amount of extra time.

Sending packets to localhost crashes the process.

This inexplicably breaks things.

In [8]: from scapy.all import *

In [9]: res = sr(IP(dst="127.0.0.1") / TCP(dport=0, flags="S"), timeout=3)
Begin emission:
............................WARNING: Child died unexpectedly. Packets may have not been sent 11771

Received 28 packets, got 0 answers, remaining 1 packets

In [10]: res = sr(IP(dst="127.0.0.1") / ICMP(), timeout=3)
Begin emission:
........WARNING: Child died unexpectedly. Packets may have not been sent 11771

Received 8 packets, got 0 answers, remaining 1 packets

Using $ ping 127.0.0.1 works in the command line.

Mac OSX python3.5.1 crash when stack a ether/ip header and show the header

Hi,
I using python 3.5.1 on mac osx. When I load the scapy lib and stack mac and ip header, the python crashed.
my python output:
`➜ ~ python3
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

from scapy.all import *
aWARNING: No route found for IPv6 destination :: (no default route?). This affects only IPv6
a=Ether()/IP()
a.show()

[ Ethernet ]

[1] 1018 segmentation fault python3
➜ ~`

Error using PcapReader as an iterator

When trying the example from the README i encounter the following error. I have installed scapy-python3 via pip3.

Traceback (most recent call last):
File "parse.py", line 8, in
for pkt in pcap_reader:
TypeError: iter() returned non-iterator of type 'PcapReader'

scapy3k export history file

can you implement this in scapy3k please

SCAPY_HISTFILE env var to set scapy history file

secdev/scapy#103

  • histfile = os.path.join(os.path.expanduser("~"), ".scapy_history")
  • histfile = os.getenv('SCAPY_HISTFILE',
  •                     os.path.join(os.path.expanduser("~"),
    
  •                                  ".scapy_history"))
    

Windows status

Hi,

I am opening this as there is no other method to communicate with you. You are doing a great work, I see you integrated the winpcapy, but I could not actually use it even in most basic method, iface is not initialized if I workaround it I get complain that pcap fd is not selectable etc...

Is there any method to use it even in primitive l2 only mode? I see windump can be used and all that is required is completion of network topology.

Thanks,

UDP packets split over multiple ethernet frames are not merged into the right session on sessions() call

Use case:

  1. read pcap file containing "large" UDP/IP packets (split across many ethernet frames)
  2. try to split the data stream onto sessions
    Result:
    in case of 3 UDP source/destination sessions the data is split onto 4 lists. Three of them contain ethernet frames with UDP headers matching the three sessions, the fourth one contains all other ethernet frames that do not contain UDP headers and are the mising fragments of those UDP packets.

Expected result: all ethernet frames with IP headers get included into the correct of those 3 sessions.

Should this issue be handled here or in the python 2 upstream?

set Ether src to 'aa:aa:aa:aa:aa:aa' did not work

I'm trying to send PPPoED packet with custom mac address, but seems very strange.. On wireshark I can see two same packet with different ether src 'aa:aa:aa:aa:aa:aa' and 'a4:5e:60:b7:75:7b'(original mac address).
Why 'a4:5e:60:b7:75:7b' packet appears, and seems no one has received 'aa:aa:aa:aa:aa:aa' packet?
image

duplicate.pcap.zip

subprocess.TimeoutExpired

When I run from scapy.all import *, I get the following output:

WARNING: Windows support for scapy3k is currently in testing. Sniffing/sending/receiving packets     should be working with WinPcap driver and Powershell. Create issues at     https://github.com/phaethon/scapy
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    from scapy.all import *
  File "C:\Python34\lib\site-packages\scapy\all.py", line 16, in <module>
    from .arch import *
  File "C:\Python34\lib\site-packages\scapy\arch\__init__.py", line 88, in <module>
    from .windows import *
  File "C:\Python34\lib\site-packages\scapy\arch\windows\__init__.py", line 23, in <module>
    from scapy.arch import pcapdnet
  File "C:\Python34\lib\site-packages\scapy\arch\pcapdnet.py", line 32, in <module>
    from .winpcapy import *
  File "C:\Python34\lib\site-packages\scapy\arch\winpcapy.py", line 26, in <module>
    _lib=CDLL('wpcap.dll')
  File "C:\Python34\lib\ctypes\__init__.py", line 351, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found

What's wrong?

scapy fails to launch when netifaces is installed

(scapy3k)~ ❯❯❯ scapy

INFO: Can't import python gnuplot wrapper . Won't be able to plot.
Traceback (most recent call last):
  File "/Users/tzudot/.virtualenvs/scapy3k/bin/scapy", line 25, in <module>
    interact()
  File "/Users/tzudot/.virtualenvs/scapy3k/lib/python3.5/site-packages/scapy/main.py", line 293, in interact
    scapy_builtins = __import__("scapy.all",globals(),locals(),".").__dict__
  File "/Users/tzudot/.virtualenvs/scapy3k/lib/python3.5/site-packages/scapy/all.py", line 25, in <module>
    from .route import *
  File "/Users/tzudot/.virtualenvs/scapy3k/lib/python3.5/site-packages/scapy/route.py", line 163, in <module>
    conf.route=Route()
  File "/Users/tzudot/.virtualenvs/scapy3k/lib/python3.5/site-packages/scapy/route.py", line 22, in __init__
    self.resync()
  File "/Users/tzudot/.virtualenvs/scapy3k/lib/python3.5/site-packages/scapy/route.py", line 31, in resync
    self.routes = read_routes()
  File "/Users/tzudot/.virtualenvs/scapy3k/lib/python3.5/site-packages/scapy/arch/unix.py", line 82, in read_routes
    ifaddr = scapy.arch.get_if_addr(netif)
  File "/Users/tzudot/.virtualenvs/scapy3k/lib/python3.5/site-packages/scapy/arch/__init__.py", line 37, in get_if_addr
    return socket.inet_ntoa(get_if_raw_addr(iff))
TypeError: a bytes-like object is required, not 'NoneType'

Is netifaces package optional? I see, you have stated this on stackoverflow.com. What do you suggest, should netifaces be installed or not?

EDIT: I am running scapy on Mac OS X 10.10.5.

Fixed pdfdump() and psdump() line drawing references...

I have fixed both the pdfdump() and psdump() functions so that line drawing reference now show up in the right side of the drawing:

In file packet.py:

  1. Change line 373:
    if type(p) is str:
    to:
    if type(p) is bytes:

  2. Change line 449:
    s.append("%02x" % ord(c))
    to:
    s.append("%02x" % c)

To test:

IP().pdfdump()

-- Ron Henderson

problem with dissection of DNSRR

I think I found a problem with dissection of DNS answers.
The problem is easy to duplicate:

def filt(p):
  if p.haslayer( DNSRR):
    for i in range( 0, p[DNS].ancount):
      print( p[DNS].an[i].rdata, p[DNS].an[i].rrname.decode())

s=sniff(count=50, lfilter=filt)

Here's an excerpt of what I got:

184.150.182.119 plus.l.google.com.
184.150.182.99 plus.l.google.com.
184.150.182.89 plus.l.google.com.
b'plus.l.google.com.' apis.google.com.
2607:f8b0:400b:806::1006 plus.l.google.com.
184.150.153.168 encrypted-tbn2.gstatic.com.

Clearly, the 4th line in the result is wrong; rdata must not be a name.
My preliminary analysis show that scapy has a problem when dissecting a DNSRR with an IPV6 address.
Looking at s in the previous code example should prove it.
Note: I set a count of 50 in sniff. Depending on the sites you visit (do they use IPV6?), you may need more or less).

I haven't checked if the problem was in Scapy V2

Windows adapter name is misspelled when containing non-ascii characters

from scapy.all import *

File "C:\Python34\lib\site-packages\scapy\all.py", line 16, in
from .arch import *
File "C:\Python34\lib\site-packages\scapy\arch__init__.py", line 88, in
from .windows import *
File "C:\Python34\lib\site-packages\scapy\arch\windows__init__.py", line 201, in
ifaces.load_from_powershell()
File "C:\Python34\lib\site-packages\scapy\arch\windows__init__.py", line 151, in load_from_powershell
for i in get_windows_if_list():
File "C:\Python34\lib\site-packages\scapy\arch\windows__init__.py", line 91, in get_windows_if_list
current_interface['name'] = value.decode('ascii')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa1 in position 1: ordinal not in range(128)

API Reference

From the first time I used scapy I've always wanted an API reference. To figure out how to use scapy in a program, there is no easily accessed API reference as far as I know.

The ls() and lsc() commands list what you can do in the scapy interpreter, but I'm looking for the classes and modules that can be used in a Python script.

I don't know how many of these features exist beyond ls()/lsc(), but one example is PcapWriter.

I'm not sure about the best way to get to an explicit API reference, but we can use Sphinx and readthedocs.org for hosting.

Windows python 3.4

Hi ,

I want to know when will the scapy be available on Windows platform for python 3.4 series
I have many libraries thats already built in 3.4 and we cannot port back to older version,

Is there any way to run Scapy on python 3.4 windows platform ?

many thanks

Documentation: Move all API elements to top level

It's hard to figure out what classes and modules are available. Best workflow I have now is to read through code, grep, or use Google.

One idea is to put everything at the top level to simplify the API. The best approach I know of is to use __init__.py. Check out pip for an example: https://github.com/pypa/pip/blob/develop/pip/__init__.py

This would have two major benefits:

  1. No more trying to figure out which file to include ("Of course IP is in Layer2, what did you expect? Layer3?").
  2. Incidental documentation of what's in the API.

INFO and WARNING for OSX installation

Please find the info and warning for os x installation.

I installed by pip3 on homebrew.

$ scapy
INFO: Can't import python gnuplot wrapper . Won't be able to plot.
INFO: Can't import PyX. Won't be able to use psdump() or pdfdump().
WARNING: Could not load module netifaces: No module named 'netifaces'
WARNING: No route found for IPv6 destination :: (no default route?)

Cannot pass the iface option to the parse_option method of the DHCPv6_am class

line 77 of the file scapy/scapy/ansmachine.py will delete the iface option from the kargs, because it is in the list of sniff_options_list and send_options_list.

Therefore the method of the parse_options of DHCPv6_am in the file scapy/layers/dhcp6.py will have issue to compute the source ip address
see line 1360

should provide a way for the sub class of the answer machine can have access to those options

Maybe just don't delete them.

Python 3.5.1, Windows 7/64 Import stack trace

FYI

from scapy.all import *
WARNING: Windows support for scapy3k is currently in testing. Sniffing/sending/receiving packets should be working with
WinPcap driver and Powershell. Create issues at https://github.com/phaethon/scapy
Traceback (most recent call last):
File "", line 1, in
File "lib\scapy\all.py", line 16, in
from .arch import *
File "lib\scapy\arch__init__.py", line 88, in
from .windows import *
File "lib\scapy\arch\windows__init__.py", line 200, in
ifaces.load_from_powershell()
File "lib\scapy\arch\windows__init__.py", line 151, in load_from_powershell
for i in get_windows_if_list():
File "lib\scapy\arch\windows__init__.py", line 87, in get_windows_if_list
name, value = [ j.strip() for j in i.split(':') ]
ValueError: too many values to unpack (expected 2)

OSError: Cannot find libdnet.so

# pip install scrapy-python3
from scapy.layers.inet import traceroute
# next line is from tutorial
res,unans = traceroute(["www.microsoft.com","www.cisco.com","www.yahoo.com","www.wanadoo.fr","www.pacsec.com"],dport=[80,443],maxttl=20,retry=-2)
/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/bin/python3.4 /Users/luckydonald/Documents/Python/SimpleStuff/lan-utils.py
Traceback (most recent call last):
  File "/Users/luckydonald/Documents/Python/SimpleStuff/lan-utils.py", line 8, in <module>
    from scapy.layers.inet import traceroute
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/layers/inet.py", line 14, in <module>
    from scapy.layers.l2 import *
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/layers/l2.py", line 14, in <module>
    from scapy.ansmachine import *
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/ansmachine.py", line 14, in <module>
    from .sendrecv import send,sendp,sniff
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/sendrecv.py", line 13, in <module>
    import scapy.arch
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/arch/__init__.py", line 84, in <module>
    from .bsd import *
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/arch/bsd.py", line 12, in <module>
    from .unix import *
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/arch/unix.py", line 22, in <module>
    from .pcapdnet import *
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/arch/pcapdnet.py", line 22, in <module>
    from .cdnet import *
  File "/Users/luckydonald/Documents/Python/virtualenv3.4.3_brew.venv/lib/python3.4/site-packages/scapy/arch/cdnet.py", line 17, in <module>
    raise OSError("Cannot find libdnet.so")
OSError: Cannot find libdnet.so

Mac OSX 10.9.5

mac:SimpleStuff luckydonald$ uname -a
Darwin mac.fritz.box 13.4.0 Darwin Kernel Version 13.4.0: Wed Mar 18 16:20:14 PDT 2015; root:xnu-2422.115.14~1/RELEASE_X86_64 x86_64
Python 3.4.3 (default, Aug 10 2015, 16:40:44) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin

Automation - Too many open files

When I run a large automation script I'll get this Exception


OSError Traceback (most recent call last)
in ()
1 for i in range(0,46):
2 for c in chars:
----> 3 if testChar(i, c):
4 flag = flag + c
5 print(c)

in testChar(pos, char)
2 ip_layer = sc.IP(dst="192.168.42.223")
3 icmp_layer = sc.ICMP(type=13, seq=pos, id=ord(char))
----> 4 response = sc.sr1(ip_layer/icmp_layer, verbose=False)
5 raw = str(bytes(response[0][0][1]))
6 if re.search('->OK'd<-', raw):

/usr/local/homebrew/lib/python3.4/site-packages/scapy/sendrecv.py in sr1(x, filter, iface, nofilter, _args, *_kargs)
337 kargs["timeout"] = -1
338 s=conf.L3socket(filter=filter, nofilter=nofilter, iface=iface)
--> 339 a,b=sndrcv(s,x,args,*kargs)
340 s.close()
341 if len(a) > 0:

/usr/local/homebrew/lib/python3.4/site-packages/scapy/sendrecv.py in sndrcv(pks, pkt, timeout, inter, verbose, chainCC, retry, multi)
71 timeout = None
72
---> 73 rdpipe,wrpipe = os.pipe()
74 rdpipe=os.fdopen(rdpipe, "rb")
75 wrpipe=os.fdopen(wrpipe,"wb")

OSError: [Errno 24] Too many open files

Scapy on Windows 7

Still doesn't work, as explained in issue #50

Here's sample code:

#!/usr/bin/env python3

from scapy.all import *

with PcapReader('cap.pcap') as pcap_reader:
    for pkt in pcap_reader:
        print('Packet!')

With that code, an exception is thrown when importing the package:
too many values to unpack (expected 2)

I'm reopening a new issue because the code provided by sysengkm works, so it would be nice to see if it can be merged in.

Console output discarded after importing scapy

System: Windows 10
Python: 3.4
scapy-python3: 0.18

The following code

print('hello')
import scapy.all as scapy
print('world')

outputs

hello
WARNING: Windows support for scapy3k is currently in testing. Sniffing/sending/receiving packets should be working with WinPcap driver and Powershell. Create issues at https://github.com/phaethon/scapy
WARNING: No route found for IPv6 destination :: (no default route?). This affects only IPv6

All console messages after the import are discarded.

This applies only to Windows, Linux shows the output as expected.

scapy.all.sniff sometimes adds 4 bytes of UDP payload

Under the following circumstances :

  • UDP over IPv6
  • UDP port around 500 (501 works too, but not 600 for example)
  • UDP payload length <= 24

scapy.all.sniff incorrectly adds 4 bytes of additional data to the captured UDP payload.

Using a socket to receive the data, or capturing with Wireshark, these 4 bytes do not appear.

Here is a full test case to reproduce (test with 2 interfaces connected by a simple cable):

#!/usr/bin/env python3

import contextlib
import os
import socket
import threading
import unittest

import scapy.all


ITF_SRC = "eth6"
ITF_DST = "eth5"
IP_SRC = "2014::1"
IP_DST = "2015::1"
UDP_PORT = 500


class SniffThread(threading.Thread):

  def __init__(self, *args, **kwargs):
    self.args = args
    self.kwargs = kwargs
    self.received = []
    super().__init__()

  def run(self):
    self.received.extend(scapy.all.sniff(*self.args, **self.kwargs))


class TestScapyUdpCaptureIssue(unittest.TestCase):

  def test_captureSocket(self):
    for udp_payload_size in (25, 24):
      # build udp frame
      eth = scapy.all.Ether(src=scapy.all.get_if_hwaddr(ITF_SRC),
                            dst=scapy.all.get_if_hwaddr(ITF_DST))
      ip = scapy.all.IPv6(src=IP_SRC,
                          dst=IP_DST)
      udp = scapy.all.UDP(sport=UDP_PORT, dport=UDP_PORT)
      payload_udp = os.urandom(udp_payload_size)
      frame = eth / ip / udp / payload_udp

      # listen for future response
      with contextlib.closing(socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)) as sckt_rec:
        sckt_rec.settimeout(1)
        sckt_rec.bind((IP_DST, UDP_PORT))

        # send frame
        scapy.all.sendp(frame, iface=ITF_SRC, verbose=False)

        # check response
        try:
          received, address = sckt_rec.recvfrom(16384)
        except socket.timeout as e:
          self.fail("%s: %s (udp_payload_size = %u)" % (e.__class__.__name__, e, udp_payload_size))
        self.assertEqual(address, (IP_SRC, UDP_PORT, 0, 0), "udp_payload_size = %u" % (udp_payload_size))
        self.assertSequenceEqual(received, payload_udp, "udp_payload_size = %u" % (udp_payload_size))

  def test_captureSniff(self):
    for udp_payload_size in (25, 24):
      # build udp frame
      eth = scapy.all.Ether(src=scapy.all.get_if_hwaddr(ITF_SRC),
                            dst=scapy.all.get_if_hwaddr(ITF_DST))
      ip = scapy.all.IPv6(src=IP_SRC,
                          dst=IP_DST)
      udp = scapy.all.UDP(sport=UDP_PORT, dport=UDP_PORT)
      payload_udp = os.urandom(udp_payload_size)
      frame = eth / ip / udp / payload_udp

      # listen for future response
      ipv6nh_codes = dict(zip(scapy.all.ipv6nh.values(), scapy.all.ipv6nh.keys()))
      sniff_thread = SniffThread(timeout=1,
                                 iface=ITF_DST,
                                 lfilter=lambda x: x[scapy.all.IPv6].nh not in (ipv6nh_codes["ICMPv6"],
                                                                                ipv6nh_codes["Hop-by-Hop Option Header"]))
      sniff_thread.start()

      # send frame
      scapy.all.sendp(frame, iface=ITF_SRC, verbose=False)
      sniff_thread.join()

      # build expected response
      expected_eth = scapy.all.Ether(src=scapy.all.get_if_hwaddr(ITF_SRC),
                                     dst=scapy.all.get_if_hwaddr(ITF_DST))
      expected_ip = scapy.all.IPv6(src=IP_SRC, dst=IP_DST)
      expected_udp = scapy.all.UDP(sport=UDP_PORT, dport=UDP_PORT)
      expected = expected_eth / expected_ip / expected_udp / payload_udp

      # check response
      self.assertEqual(len(sniff_thread.received), 1, "udp_payload_size = %u" % (udp_payload_size))  # fails if udp_payload_size == 24
      self.assertSequenceEqual(bytes(sniff_thread.received[0]),
                               bytes(expected),
                               "udp_payload_size = %u" % (udp_payload_size))


if __name__ == "__main__":
    unittest.main()

Context :

  • Ubuntu 14.04
  • Python 3.4
  • Scapy v0.13 from this repo.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.