网络安全----web安全防范

以下代码用来防范流行的DDoS攻击,ARP欺骗,CC攻击,XXS攻击,对输入的恶意代码进行过滤,嵌入到web程序可以很好的防范网络攻击,但如果想要更好的防范网络攻击,还需要更加复杂的配置和更硬核的硬件。


import socket

import struct

import time

import threading

定义一些常量

ARP_PACKET_TYPE = 0x0806

IP_PACKET_TYPE = 0x0800

用于检测 ARP 欺骗的函数

def detect_arp_spoofing():

创建原始套接字

sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(ARP_PACKET_TYPE))

while True:

packet = sock.recvfrom(65535)

eth_header = packet00:14

eth = struct.unpack("!6s6sH", eth_header)

if eth2 == ARP_PACKET_TYPE:

arp_packet = packet014:

arp_header = struct.unpack("!HHBBH6s4s6s4s", arp_packet:28)

检查 ARP 应答的合法性

if arp_header4 == 2:

在此添加验证 MAC 地址和 IP 地址对应关系的逻辑

pass

time.sleep(0.1)

用于检测 DDoS 攻击的函数(简单示例,通过监测短时间内的连接数量)

def detect_ddos():

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.bind(('0.0.0.0', 80))

connection_count = 0

threshold = 100 # 每秒连接数阈值

last_time = time.time()

while True:

sock.listen(5)

client_sock, addr = sock.accept()

connection_count += 1

current_time = time.time()

if current_time - last_time >= 1:

if connection_count > threshold:

print("可能的 DDoS 攻击检测到")

connection_count = 0

last_time = current_time

用于检测 CC 攻击的函数(简单示例,通过监测短时间内对同一资源的请求频率)

def detect_cc():

resource_request_count = {}

threshold = 10 # 每秒对同一资源的请求阈值

last_time = time.time()

while True:

假设这里获取到请求的资源路径

resource_path = "example_resource_path"

if resource_path in resource_request_count:

resource_request_countresource_path += 1

else:

resource_request_countresource_path = 1

current_time = time.time()

if current_time - last_time >= 1:

for resource, count in resource_request_count.items():

if count > threshold:

print(f"可能的 CC 攻击针对资源 {resource} 检测到")

resource_request_count = {}

last_time = current_time

用于检测 XSS 攻击的函数(简单示例,检查输入中是否存在可疑脚本标签)

def detect_xss(input_string):

suspicious_keywords = "\", "\", "\", "javascript:"

for keyword in suspicious_keywords:

if keyword in input_string:

print("可能的 XSS 攻击检测到")

创建线程来运行各个检测函数

threads = [

threading.Thread(target=detect_arp_spoofing),

threading.Thread(target=detect_ddos),

threading.Thread(target=detect_cc),

]

for thread in threads:

thread.start()

相关推荐
卓豪终端管理21 小时前
应用白名单和黑名单怎么建?一份可落地的应用程序控制指南
安全·web安全·php
LightBreeze20022 天前
华为防火墙双机热备与虚拟系统详解:HRP高可靠性及VSYS虚拟化技术原理与实验
web安全·虚拟系统·双机热备·vgmp·心跳链路·主备备份·负载分担
VW_4044 天前
M0-本机实验环境与工具链
web安全
kingx36 天前
BUGKU Make Me Cry 解题:curl 探测与 POST 路径参数构造
web安全·curl·bugku·路径遍历·参数构造
kingx37 天前
DASCTF 02-cookies 解题:Flappy Bird 分数 Cookie 的 Base64+gzip 构造
web安全·php·base64·gzip解压·cookie伪造
国科安芯7 天前
可信的电流:ASP4644S2B电源模块与星载电子供应链网络安全防护体系
网络·安全·web安全·架构·芯片·抗辐射
kitsch0x977 天前
MITRE Engage 中的网络欺骗
安全·web安全·php
如夏倾城8 天前
WAF (Web Application Firewall,Web应用防火墙)
前端·网络·安全·web安全·web app
真上帝的左手8 天前
7. 网络安全-网关-认证鉴权实战-Spring Boot+SpringSecurity+JWT登录认证
java·spring boot·web安全
kingx39 天前
DASCTF Uploadfile 解题:PHP5.5 上传点与 phtml 绕过后门利用
web安全·文件上传·phtml 绕过·php 5.5·ctf 渗透