python socket to receive specific VLAN id packets - python-3.x

Is there a way to receive just VLAN id with 100 instead of receiving all packets? If so, what value the ntohs should have?
import socket
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
while True:
packet = s.recvfrom(65565)

Related

How to create two tun for communication? What does point-to-point mean?

In order to implement a tcp stack in userspace, I try to set two tun device and exechange data between them for testing code.However, it seems like that all IP packet wrote to tun are dropped.
For example:
tun0,ip:172.19.16.1/20.
tun1,ip:172.19.32.1/20.
when I use ping 172.19.16.2,tun 0 can receive ICMP packet(from 172.19.16.1 to 172.19.16.2) and write data to tun0 for replying. But when I try to send a ICMP from tun0 to tun1(172.19.16.1 to 172.19.32.1 or vice versa), it failed. tun1 can't receive any data! Why? I try to send TCP packet from tun1 to tun0, it also failed.
From kernel document,I know tun is a point-to-point device and haven't mac address and arp. What does point-to-point mean? Can create two or three tun device for communicating each other?
import fcntl
import os
import if_tun
import ctypes
import struct
from scapy.all import *
from if_tun import IfReq, TUNSETIFF, IFF_TUN
def register_tun(name: str):
fd = os.open("/dev/net/tun",os.O_RDWR)
if fd < 0:
return fd
r = IfReq()
ctypes.memset(ctypes.byref(r), 0, ctypes.sizeof(r))
r.ifr_ifru.ifru_flags = IFF_TUN | 0x1000
r.ifr_ifrn.ifrn_name = name.encode("utf-8")
fcntl.ioctl(fd, TUNSETIFF,r)
return fd
if __name__ == "__main__":
fd = register_tun("tun2")
if fd < 0:
print("error")
while True:
type = input()
a = IP(dst="172.19.16.1",src="172.19.32.1")/TCP()
a = IP(raw(a))
a.show()
print("write:")
print(os.write(fd, raw(a)))
buf = os.read(fd,1024)
print("receive data")
IP(raw(buf)).show()

Sniff RTS's and send CTS in return with Scapy

I'm able to sniff RTS packets without a problem. I'm also able to utilize 'sendp' to send CTS packets. What I'm unable to figure out is how to have Scapy sniff RTS packets and reply to those RTS's with a crafted CTS in real-time. The intent is to send a CTS for every RTS that my AWUS036ACH can hear regardless of the intended device.
import os
import time
from threading import Thread
from scapy.layers.all import Dot11,Dot11Elt,RadioTap,sniff,sendp
def change_channel():
ch = 1
while True:
try:
os.system(f"iwconfig {iface} channel {ch}")
ch = ch % 14 + 1
time.sleep(1)
except KeyboardInterrupt:
break
if __name__ == "__main__":
iface = "wlan0"
channel_changer = Thread(target=change_channel)
channel_changer.daemon = True
channel_changer.start()
def PacketHandler(packet):
if packet.haslayer(Dot11):
if packet.type==1 and packet.subtype==11:
rts_list.append(bssid)
bssid = packet[Dot11].addr2
print("MAC: %s" %(bssid))
sniff(iface=iface, prn=PacketHandler)
i=1
while 1:
time.sleep(.100)
i = i + 1
dot11 = Dot11(type=1, subtype=12, addr1=bssid,ID=0x99)
pkt = RadioTap()/dot11
sendp(pkt,iface=iface, realtime=True)
Why don't you try to add sendp inside your PacketHandler function?
The logic goes like this:
PacketHandler is called upon every received frame
You check whether it's an RTS frame, extract all of the necessary info you need to send a CTS frame
Call sendp with received info
There are ways to write ARP response utilities, take a look for ideas.
My concern is whether it's possible to send a frame while your adapter is put in monitor mode. Unfortunately I can't test it right now.
Recommendation. Try to use BPF filter with sniff. It goes like this:
sniff(iface=iface, filter="type ctl subtype rts", prn=PacketHandler)
And get rid of testing for frame type inside you PacketHandler. This way you will filter for RTS on a kernel level thus performance is increased. Scapy itself can easily miss RTS frames in a dense wireless environment. For more BPF filters applied to 802.11 check man pcap-filter.

Implementing reliability in UDP (python)

I have written the code for transferring an audio file from client to server using udp (python).
Now I am required to introduce reliability in the codes of UDP. The instructions are given as:
"You will be required to implement following to make UDP reliable:
(a) Sequence and acknowledge numbers
(b) Re-transmission (selective repeat)
(c) Window size of 5-10 UDP segments (stop n wait)
(d) Re ordering on receiver side "
THE SENDER THAT IS CLIENT CODE IS GIVEN BELOW
from socket import *
import time
# Assigning server IP and server port
serverName = "127.0.0.1"
serverPort = 5000
# Setting buffer length
buffer_length = 500
# Assigning the audio file a name
my_audio_file = r"C:\Users\mali.bee17seecs\PycharmProjects\TestProject\Aye_Rah-e-Haq_Ke_Shaheedo.mp3"
clientSocket = socket(AF_INET, SOCK_DGRAM)
# Opening the audio file
f = open(my_audio_file, "rb")
# Reading the buffer length in data
data = f.read(buffer_length)
# While loop for the transfer of file
while data:
if clientSocket.sendto(data, (serverName, serverPort)):
data = f.read(buffer_length)
time.sleep(0.02) # waiting for 0.02 seconds
clientSocket.close()
f.close()
print("File has been Transferred")
THE RECEIVER THAT IS SERVER CODE IS GIVEN BELOW
from socket import *
import select
# Assigning server IP and server port
serverName = "127.0.0.1"
serverPort = 5000
# Setting timeout
timeout = 3
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind((serverName, serverPort))
# While loop for the receiving of file
while True:
data, serverAddress = serverSocket.recvfrom(1024)
if data:
file = open(r"C:\Users\mali.bee17seecs\PycharmProjects\TestProject\Aye_Rah-e-Haq_Ke_Shaheedo.mp3",
"wb")
while True:
ready = select.select([serverSocket], [], [], timeout)
if ready[0]:
data, serverAddress = serverSocket.recvfrom(500)
file.write(data)
else:
file.close()
print("File has been Received")
break
Before answer each request, you should know that we build a reliable UDP by adding some specific infomation before the real content, which you can think as a application layer head. We use them to do some control or collect infomation like TCP does in traffic layer by the head part. It may look like below:
struct Head {
int seq;
int size;
}
(a) Sequence and acknowledge numbers
If you're familar with TCP, it is not hard. You can set seq and when the other side receive it, the controller will judge it and to check if we need to do b/d.
(b) Re-transmission (selective repeat) & (d) Reordering on receiver side
They are familiar to realise, using GBN/ARQ/SACK algorithm to do retransmission, using some simple algorithm like sorting to do reording.
(c) Window size of 5-10 UDP segments (stop n wait)
This part need to do some thing like traffic control that TCP does. I don't how complex you want to do, it's can be really complex or simple, it depends on you.

Udp connection port 25000 returns no data

I want to receive data from uk.tcpvpn.com on port 25000 udp
I have tried this code but no way i did not receive data
import socket, struct, time, math
from math import pi
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(struct.pack("dddddd",0,0,0,0,0,0), ("uk.tcpvpn.com", 25000))
data, addr = sock.recvfrom(1024)
sock.close()
print(data)
But when i tried with dns servers like 8.8.8.8 port 53 i get data
Is there a solution ?

Unable to create OpenFlow13 message with Scapy

I am writing a code where I am capturing openflow13 packets using tcpdump and wireshark. I am running mininet topo and floodlight SDN controller. Once I get my SDN controller IP and port details from the capture, I intent to create multiple OFPTHello messages and send it to the SDN Controller [sort of DDoS attack]. Although I am able to extract the controller's details, I am unable to create Scapy OFPTHello message packets.
Request to please help me identify and resolve the issue
Mininet Topo I am running-
sudo mn --topo=linear,4 --mac --controller=remote,ip=192.168.56.102 --switch=ovsk,protocols=OpenFlow13
My Code-
#!/usr/bin/env python3
try:
import time
import subprocess
import json
import sys
from scapy.all import *
from scapy.contrib.openflow import _ofp_header
from scapy.fields import ByteEnumField, IntEnumField, IntField, LongField, PacketField, ShortField, XShortField
from scapy.layers.l2 import Ether
ofp_table = {0xfe: "MAX",
0xff: "ALL"}
ofp_buffer = {0xffffffff: "NO_BUFFER"}
ofp_version = {0x04: "OpenFlow 1.3"}
ofp_type = {0: "OFPT_HELLO"}
class OFPHET(_ofp_header):
#classmethod
def dispatch_hook(cls, _pkt=None, *args, **kargs):
if _pkt and len(_pkt) >= 2:
t = struct.unpack("!H", _pkt[:2])[0]
return ofp_hello_elem_cls.get(t, Raw)
return Raw
def extract_padding(self, s):
return b"", s
class OFPTHello(_ofp_header):
name = "OFPT_HELLO"
fields_desc = [ByteEnumField("version", 0x04, ofp_version),
ByteEnumField("type", 0, ofp_type),
ShortField("len", None),
IntField("xid", 0),
PacketListField("elements", [], OFPHET, length_from=lambda pkt: pkt.len - 8)]
# Capture controller's IP address and Port
Hello_Msg = []
Switch_TCP_Port = []
p = subprocess.Popen(['sudo', 'tcpdump', '-i', 'eth1', 'port', '6653', '-w', 'capture.pcap'], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
time.sleep(45)
p.terminate()
captures = rdpcap('capture.pcap')
for capture in captures:
msg = (capture.summary()).split(" ")
i = len(msg)
if (msg[i-1] == "OFPTFeaturesRequest"):
Features_Request = capture.summary()
break;
elif (msg[i-1] == "OFPTHello"):
Hello_Msg.append(capture.summary())
for Hello in Hello_Msg:
frame = Hello.split("/")[2]
port = ((frame.split(" ")[2]).split(":"))[1]
Switch_TCP_Port.append(port)
Features_Request = Features_Request.split("/")[2]
Source_Frame = (Features_Request.split(" ")[2]).split(":")
Controller_IP = Source_Frame[0]
Controller_Port = int(Source_Frame[1])
print("\nController's IP Address: %s"%Controller_IP)
print("Controller's Port: %s"%Controller_Port)
# Generating Openfow PAcket_In using Scapy
for p in Switch_TCP_Port:
p = int(p)
packet = Ether(src='08:00:27:fa:75:e9',dst='08:00:27:f1:24:22')/IP(src='192.168.56.101',dst=Controller_IP)/TCP(sport=p,dport=Controller_Port)/OFPTHello()
send(packet)
except ImportError as e:
print ("\n!!! ImportError !!!")
print ("{0}. Install it.\n".format(e))
Wireshark Capture- [Only has 4 hello packets, no Scapy packets are captured]
Question/Issue- I am able to receive the ideal number of 4 hello packets from the mininet topology. However, the new hello packets I am trying to create using scapy are not being sent/ captured by wireshark. I have attached my scapy code for reference.
In your code do this
modify the line:
send(packet)
To
send(packet,iface='eth1') where eth1 is the egress interface of the attacking VM
The reason is that even if a malformed Openflow packet is put on the wire, Wireshark will still be able to capture it, assuming your attack VM has a route to the controller VM. This means that your code is not putting the Packet on the right wire, send(packet,iface='eth1') will put it on the right wire.

Resources