feat: Add Hysteria IP limiter script
This commit is contained in:
33
core/cli.py
33
core/cli.py
@ -510,6 +510,39 @@ def check_version():
|
||||
except Exception as e:
|
||||
click.echo(f"An unexpected error occurred: {e}", err=True)
|
||||
|
||||
@cli.command('start-ip-limit')
|
||||
def start_ip_limit():
|
||||
"""Starts the IP limiter service."""
|
||||
try:
|
||||
cli_api.start_ip_limiter()
|
||||
click.echo('IP Limiter service started successfully.')
|
||||
except Exception as e:
|
||||
click.echo(f'{e}', err=True)
|
||||
|
||||
@cli.command('stop-ip-limit')
|
||||
def stop_ip_limit():
|
||||
"""Stops the IP limiter service."""
|
||||
try:
|
||||
cli_api.stop_ip_limiter()
|
||||
click.echo('IP Limiter service stopped successfully.')
|
||||
except Exception as e:
|
||||
click.echo(f'{e}', err=True)
|
||||
|
||||
@cli.command('config-ip-limit')
|
||||
@click.option('--block-duration', '-bd', type=int, help='New block duration in seconds')
|
||||
@click.option('--max-ips', '-mi', type=int, help='New maximum IPs per user')
|
||||
def config_ip_limit(block_duration: int, max_ips: int):
|
||||
"""Configures the IP limiter service parameters."""
|
||||
try:
|
||||
cli_api.config_ip_limiter(block_duration, max_ips)
|
||||
click.echo('IP Limiter configuration updated successfully.')
|
||||
if block_duration is not None:
|
||||
click.echo(f' Block Duration: {block_duration} seconds')
|
||||
if max_ips is not None:
|
||||
click.echo(f' Max IPs per user: {max_ips}')
|
||||
except Exception as e:
|
||||
click.echo(f'{e}', err=True)
|
||||
|
||||
# endregion
|
||||
|
||||
|
||||
|
||||
@ -48,6 +48,7 @@ class Command(Enum):
|
||||
STATUS_WARP = os.path.join(SCRIPT_DIR, 'warp', 'status.sh')
|
||||
SERVICES_STATUS = os.path.join(SCRIPT_DIR, 'services_status.sh')
|
||||
VERSION = os.path.join(SCRIPT_DIR, 'hysteria2', 'version.py')
|
||||
LIMIT_SCRIPT = os.path.join(SCRIPT_DIR, 'hysteria2', 'limit.sh')
|
||||
|
||||
# region Custom Exceptions
|
||||
|
||||
@ -511,5 +512,31 @@ def check_version() -> str | None:
|
||||
"""Checks if the current version is up-to-date and displays changelog if not."""
|
||||
return run_cmd(['python3', Command.VERSION.value, 'check-version'])
|
||||
|
||||
# endregion
|
||||
def start_ip_limiter():
|
||||
'''Starts the IP limiter service.'''
|
||||
run_cmd(['bash', Command.LIMIT_SCRIPT.value, 'start'])
|
||||
|
||||
def stop_ip_limiter():
|
||||
'''Stops the IP limiter service.'''
|
||||
run_cmd(['bash', Command.LIMIT_SCRIPT.value, 'stop'])
|
||||
|
||||
def config_ip_limiter(block_duration: int = None, max_ips: int = None):
|
||||
'''Configures the IP limiter service.'''
|
||||
if block_duration is not None and block_duration <= 0:
|
||||
raise InvalidInputError("Block duration must be greater than 0.")
|
||||
if max_ips is not None and max_ips <= 0:
|
||||
raise InvalidInputError("Max IPs must be greater than 0.")
|
||||
|
||||
cmd_args = ['bash', Command.LIMIT_SCRIPT.value, 'config']
|
||||
if block_duration is not None:
|
||||
cmd_args.append(str(block_duration))
|
||||
else:
|
||||
cmd_args.append('')
|
||||
|
||||
if max_ips is not None:
|
||||
cmd_args.append(str(max_ips))
|
||||
else:
|
||||
cmd_args.append('')
|
||||
|
||||
run_cmd(cmd_args)
|
||||
# endregion
|
||||
|
||||
@ -1,23 +1,32 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Configuration
|
||||
CONNECTIONS_FILE="/etc/hysteria/hysteria_connections.json"
|
||||
BLOCK_DURATION=60 # 1 minute block duration
|
||||
MAX_IPS=1 # Maximum number of IPs allowed per user
|
||||
BLOCK_LIST="/tmp/hysteria_blocked_ips.txt" # File to track blocked IPs
|
||||
source /etc/hysteria/core/scripts/path.sh
|
||||
|
||||
# Ensure the connections file exists
|
||||
# --- Configuration ---
|
||||
SERVICE_NAME="hysteria-ip-limit.service"
|
||||
|
||||
# Load configurations from .configs.env
|
||||
if [ -f "$CONFIG_ENV" ]; then
|
||||
source "$CONFIG_ENV"
|
||||
BLOCK_DURATION="${BLOCK_DURATION:-60}" # Default to 60 seconds if not set
|
||||
MAX_IPS="${MAX_IPS:-1}" # Default to 1 IP if not set
|
||||
else
|
||||
BLOCK_DURATION=240
|
||||
MAX_IPS=5
|
||||
fi
|
||||
|
||||
# --- Ensure files exist ---
|
||||
[ ! -f "$CONNECTIONS_FILE" ] && echo "{}" > "$CONNECTIONS_FILE"
|
||||
[ ! -f "$BLOCK_LIST" ] && touch "$BLOCK_LIST"
|
||||
|
||||
# Logging function
|
||||
# --- Logging function ---
|
||||
log_message() {
|
||||
local level="$1"
|
||||
local message="$2"
|
||||
echo "[$(date +"%Y-%m-%d %H:%M:%S")] [$level] $message"
|
||||
}
|
||||
|
||||
# Function to update the JSON file with new connection data
|
||||
# --- Function to update the JSON file with new connection data ---
|
||||
update_json() {
|
||||
local username="$1"
|
||||
local ip_address="$2"
|
||||
@ -42,7 +51,7 @@ update_json() {
|
||||
log_message "INFO" "Updated JSON: Added $ip_address for user $username"
|
||||
}
|
||||
|
||||
# Function to remove an IP from the JSON when client disconnects
|
||||
# --- Function to remove an IP from the JSON when client disconnects ---
|
||||
remove_ip() {
|
||||
local username="$1"
|
||||
local ip_address="$2"
|
||||
@ -58,11 +67,23 @@ remove_ip() {
|
||||
jq --arg user "$username" --arg ip "$ip_address" \
|
||||
'.[$user] = (.[$user] | map(select(. != $ip)))' "$CONNECTIONS_FILE" > "$temp_file"
|
||||
mv "$temp_file" "$CONNECTIONS_FILE"
|
||||
|
||||
# Check if the user's IP list is now empty and remove the user if so
|
||||
temp_file_check=$(mktemp)
|
||||
jq --arg user "$username" 'if .[$user] | length == 0 then del(.[$user]) else . end' "$CONNECTIONS_FILE" > "$temp_file_check"
|
||||
mv "$temp_file_check" "$CONNECTIONS_FILE"
|
||||
|
||||
else
|
||||
# Basic sed replacement (not as reliable as jq)
|
||||
sed -i -E "s/\"$ip_address\"(,|\])|\1\"$ip_address\"/\1/g" "$CONNECTIONS_FILE"
|
||||
sed -i -E "s/,\s*\]/\]/g" "$CONNECTIONS_FILE"
|
||||
sed -i -E "s/\[\s*,/\[/g" "$CONNECTIONS_FILE"
|
||||
|
||||
# VERY Basic check if user's IP list is empty and remove the user if so (less reliable)
|
||||
if grep -q "\"$username\":\s*\[\s*\]" "$CONNECTIONS_FILE"; then
|
||||
sed -i "/\"$username\":\s*\[\s*\][,\s]*/d" "$CONNECTIONS_FILE"
|
||||
sed -i "s/,\s*\}$/\n}/" "$CONNECTIONS_FILE" # Remove trailing comma if it exists after user deletion
|
||||
fi
|
||||
fi
|
||||
log_message "INFO" "Updated JSON: Removed $ip_address for user $username"
|
||||
else
|
||||
@ -70,7 +91,7 @@ remove_ip() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Block an IP using iptables and track it
|
||||
# --- Block an IP using iptables and track it ---
|
||||
block_ip() {
|
||||
local ip_address="$1"
|
||||
local username="$2"
|
||||
@ -91,7 +112,7 @@ block_ip() {
|
||||
log_message "WARN" "Blocked IP $ip_address for user $username for $BLOCK_DURATION seconds"
|
||||
}
|
||||
|
||||
# Explicitly unblock an IP using iptables
|
||||
# --- Explicitly unblock an IP using iptables ---
|
||||
unblock_ip() {
|
||||
local ip_address="$1"
|
||||
|
||||
@ -105,7 +126,7 @@ unblock_ip() {
|
||||
sed -i "/$ip_address,/d" "$BLOCK_LIST"
|
||||
}
|
||||
|
||||
# Block all IPs for a user
|
||||
# --- Block all IPs for a user ---
|
||||
block_all_user_ips() {
|
||||
local username="$1"
|
||||
local ips=()
|
||||
@ -138,7 +159,7 @@ block_all_user_ips() {
|
||||
log_message "WARN" "User $username has been completely blocked for $BLOCK_DURATION seconds"
|
||||
}
|
||||
|
||||
# Check for and unblock expired IPs
|
||||
# --- Check for and unblock expired IPs ---
|
||||
check_expired_blocks() {
|
||||
local current_time=$(date +%s)
|
||||
local ip username expiry
|
||||
@ -154,7 +175,7 @@ check_expired_blocks() {
|
||||
done < "$BLOCK_LIST"
|
||||
}
|
||||
|
||||
# Check if a user has exceeded the IP limit
|
||||
# --- Check if a user has exceeded the IP limit ---
|
||||
check_ip_limit() {
|
||||
local username="$1"
|
||||
local ips=()
|
||||
@ -184,7 +205,7 @@ check_ip_limit() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Parse log lines for connections and disconnections
|
||||
# --- Parse log lines for connections and disconnections ---
|
||||
parse_log_line() {
|
||||
local log_line="$1"
|
||||
local ip_address=""
|
||||
@ -214,47 +235,130 @@ parse_log_line() {
|
||||
fi
|
||||
}
|
||||
|
||||
# Check if running as root
|
||||
# --- Install Systemd Service ---
|
||||
install_service() {
|
||||
cat <<EOF > /etc/systemd/system/${SERVICE_NAME}
|
||||
[Unit]
|
||||
Description=Hysteria2 IP Limiter
|
||||
After=network.target hysteria-server.service
|
||||
Requires=hysteria-server.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/bin/bash ${SCRIPT_PATH} run
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
User=root
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target.target
|
||||
EOF
|
||||
systemctl daemon-reload
|
||||
systemctl enable ${SERVICE_NAME}
|
||||
systemctl start ${SERVICE_NAME}
|
||||
log_message "INFO" "IP Limiter service started"
|
||||
}
|
||||
|
||||
# --- Uninstall Systemd Service ---
|
||||
uninstall_service() {
|
||||
systemctl stop ${SERVICE_NAME} 2>/dev/null
|
||||
systemctl disable ${SERVICE_NAME} 2>/dev/null
|
||||
rm -f /etc/systemd/system/${SERVICE_NAME}
|
||||
systemctl daemon-reload
|
||||
log_message "INFO" "IP Limiter service stopped and removed"
|
||||
}
|
||||
|
||||
# --- Change Configuration ---
|
||||
change_config() {
|
||||
local new_block_duration="$1"
|
||||
local new_max_ips="$2"
|
||||
|
||||
if [[ -n "$new_block_duration" ]]; then
|
||||
if ! [[ "$new_block_duration" =~ ^[0-9]+$ ]]; then
|
||||
log_message "ERROR" "Invalid block duration: '$new_block_duration'. Must be a number."
|
||||
return 1
|
||||
fi
|
||||
sed -i "s/^BLOCK_DURATION=.*/BLOCK_DURATION=$new_block_duration/" "$CONFIG_ENV"
|
||||
BLOCK_DURATION=$new_block_duration
|
||||
log_message "INFO" "Block duration updated to $BLOCK_DURATION seconds"
|
||||
fi
|
||||
|
||||
if [[ -n "$new_max_ips" ]]; then
|
||||
if ! [[ "$new_max_ips" =~ ^[0-9]+$ ]]; then
|
||||
log_message "ERROR" "Invalid max IPs: '$new_max_ips'. Must be a number."
|
||||
return 1
|
||||
fi
|
||||
sed -i "s/^MAX_IPS=.*/MAX_IPS=$new_max_ips/" "$CONFIG_ENV"
|
||||
MAX_IPS=$new_max_ips
|
||||
log_message "INFO" "Max IPs per user updated to $MAX_IPS"
|
||||
fi
|
||||
|
||||
if systemctl is-active --quiet ${SERVICE_NAME}; then
|
||||
systemctl restart ${SERVICE_NAME}
|
||||
log_message "INFO" "IP Limiter service restarted to apply new configuration"
|
||||
fi
|
||||
}
|
||||
|
||||
# --- Check if running as root ---
|
||||
if [[ $EUID -ne 0 ]]; then
|
||||
log_message "ERROR" "This script must be run as root for iptables functionality"
|
||||
echo "Error: This script must be run as root for iptables functionality."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check for jq and warn if not available
|
||||
# --- Check for jq and warn if not available ---
|
||||
if ! command -v jq &>/dev/null; then
|
||||
log_message "WARN" "'jq' is not installed. JSON handling may be less reliable."
|
||||
log_message "WARN" "Consider installing jq with: apt install jq (for Debian/Ubuntu)"
|
||||
fi
|
||||
|
||||
# Main script
|
||||
log_message "INFO" "Monitoring Hysteria server connections. Max IPs per user: $MAX_IPS"
|
||||
log_message "INFO" "Block duration: $BLOCK_DURATION seconds"
|
||||
log_message "INFO" "Connection data saved to: $CONNECTIONS_FILE"
|
||||
log_message "INFO" "Press Ctrl+C to exit"
|
||||
log_message "INFO" "--------------------------------------------------------"
|
||||
# --- Command execution based on arguments ---
|
||||
case "$1" in
|
||||
start)
|
||||
install_service
|
||||
;;
|
||||
stop)
|
||||
uninstall_service
|
||||
;;
|
||||
config)
|
||||
change_config "$2" "$3"
|
||||
;;
|
||||
run)
|
||||
log_message "INFO" "Monitoring Hysteria server connections. Max IPs per user: $MAX_IPS"
|
||||
log_message "INFO" "Block duration: $BLOCK_DURATION seconds"
|
||||
log_message "INFO" "Connection data saved to: $CONNECTIONS_FILE"
|
||||
log_message "INFO" "Press Ctrl+C to exit"
|
||||
log_message "INFO" "--------------------------------------------------------"
|
||||
|
||||
# Background process to check for expired blocks every 10 seconds
|
||||
(
|
||||
# Background process to check for expired blocks every 10 seconds
|
||||
(
|
||||
while true; do
|
||||
check_expired_blocks
|
||||
sleep 10
|
||||
done
|
||||
) &
|
||||
CHECKER_PID=$!
|
||||
) &
|
||||
CHECKER_PID=$!
|
||||
|
||||
# Cleanup function
|
||||
cleanup() {
|
||||
# Cleanup function
|
||||
cleanup() {
|
||||
log_message "INFO" "Stopping IP limiter..."
|
||||
kill $CHECKER_PID 2>/dev/null
|
||||
exit 0
|
||||
}
|
||||
}
|
||||
|
||||
# Set trap for cleanup
|
||||
trap cleanup SIGINT SIGTERM
|
||||
# Set trap for cleanup
|
||||
trap cleanup SIGINT SIGTERM
|
||||
|
||||
# Monitor log for connections and disconnections
|
||||
journalctl -u hysteria-server.service -f | while read -r line; do
|
||||
# Monitor log for connections and disconnections
|
||||
journalctl -u hysteria-server.service -f | while read -r line; do
|
||||
if echo "$line" | grep -q "client connected\|client disconnected"; then
|
||||
parse_log_line "$line"
|
||||
fi
|
||||
done
|
||||
done
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $0 {start|stop|config|run} [block_duration] [max_ips]"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
exit 0
|
||||
@ -11,3 +11,6 @@ ONLINE_API_URL="http://127.0.0.1:25413/online"
|
||||
LOCALVERSION="/etc/hysteria/VERSION"
|
||||
LATESTVERSION="https://raw.githubusercontent.com/ReturnFI/Hysteria2/main/VERSION"
|
||||
LASTESTCHANGE="https://raw.githubusercontent.com/ReturnFI/Hysteria2/main/changelog"
|
||||
CONNECTIONS_FILE="/etc/hysteria/hysteria_connections.json"
|
||||
BLOCK_LIST="/tmp/hysteria_blocked_ips.txt"
|
||||
SCRIPT_PATH="/etc/hysteria/core/scripts/hysteria2/limit.sh"
|
||||
@ -7,6 +7,7 @@ declare -a services=(
|
||||
"hysteria-telegram-bot.service"
|
||||
"hysteria-normal-sub.service"
|
||||
"hysteria-singbox.service"
|
||||
"hysteria-ip-limit.service"
|
||||
"wg-quick@wgcf.service"
|
||||
)
|
||||
|
||||
|
||||
95
menu.sh
95
menu.sh
@ -805,6 +805,95 @@ masquerade_handler() {
|
||||
done
|
||||
}
|
||||
|
||||
ip_limit_handler() {
|
||||
while true; do
|
||||
echo -e "${cyan}1.${NC} Start IP Limiter Service"
|
||||
echo -e "${red}2.${NC} Stop IP Limiter Service"
|
||||
echo -e "${yellow}3.${NC} Change IP Limiter Configuration"
|
||||
echo "0. Back"
|
||||
read -p "Choose an option: " option
|
||||
|
||||
case $option in
|
||||
1)
|
||||
if systemctl is-active --quiet hysteria-ip-limit.service; then
|
||||
echo "The hysteria-ip-limit.service is already active."
|
||||
else
|
||||
while true; do
|
||||
read -e -p "Enter Block Duration (seconds, default: 60): " block_duration
|
||||
block_duration=${block_duration:-60} # Default to 60 if empty
|
||||
if ! [[ "$block_duration" =~ ^[0-9]+$ ]]; then
|
||||
echo "Invalid Block Duration. Please enter a number."
|
||||
else
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
while true; do
|
||||
read -e -p "Enter Max IPs per User (default: 1): " max_ips
|
||||
max_ips=${max_ips:-1} # Default to 1 if empty
|
||||
if ! [[ "$max_ips" =~ ^[0-9]+$ ]]; then
|
||||
echo "Invalid Max IPs. Please enter a number."
|
||||
else
|
||||
break
|
||||
fi
|
||||
done
|
||||
python3 $CLI_PATH config-ip-limit --block-duration "$block_duration" --max-ips "$max_ips"
|
||||
python3 $CLI_PATH start-ip-limit
|
||||
fi
|
||||
;;
|
||||
2)
|
||||
if ! systemctl is-active --quiet hysteria-ip-limit.service; then
|
||||
echo "The hysteria-ip-limit.service is already inactive."
|
||||
else
|
||||
python3 $CLI_PATH stop-ip-limit
|
||||
fi
|
||||
;;
|
||||
3)
|
||||
block_duration=""
|
||||
max_ips=""
|
||||
updated=false
|
||||
|
||||
while true; do
|
||||
read -e -p "Enter New Block Duration (seconds, current: $(grep '^BLOCK_DURATION=' /etc/hysteria/.configs.env | cut -d'=' -f2), leave empty to keep current): " input_block_duration
|
||||
if [[ -n "$input_block_duration" ]] && ! [[ "$input_block_duration" =~ ^[0-9]+$ ]]; then
|
||||
echo "Invalid Block Duration. Please enter a number or leave empty."
|
||||
else
|
||||
if [[ -n "$input_block_duration" ]]; then
|
||||
block_duration="$input_block_duration"
|
||||
updated=true
|
||||
fi
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
while true; do
|
||||
read -e -p "Enter New Max IPs per User (current: $(grep '^MAX_IPS=' /etc/hysteria/.configs.env | cut -d'=' -f2), leave empty to keep current): " input_max_ips
|
||||
if [[ -n "$input_max_ips" ]] && ! [[ "$input_max_ips" =~ ^[0-9]+$ ]]; then
|
||||
echo "Invalid Max IPs. Please enter a number or leave empty."
|
||||
else
|
||||
if [[ -n "$input_max_ips" ]]; then
|
||||
max_ips="$input_max_ips"
|
||||
updated=true
|
||||
fi
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ "$updated" == "true" ]]; then
|
||||
python3 $CLI_PATH config-ip-limit --block-duration "$block_duration" --max-ips "$max_ips"
|
||||
else
|
||||
echo "No changes to IP Limiter configuration were provided."
|
||||
fi
|
||||
;;
|
||||
0)
|
||||
break
|
||||
;;
|
||||
*)
|
||||
echo "Invalid option. Please try again."
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
# Function to display the main menu
|
||||
display_main_menu() {
|
||||
@ -933,7 +1022,8 @@ display_advance_menu() {
|
||||
echo -e "${cyan}[14] ${NC}↝ Manage Masquerade"
|
||||
echo -e "${cyan}[15] ${NC}↝ Restart Hysteria2"
|
||||
echo -e "${cyan}[16] ${NC}↝ Update Core Hysteria2"
|
||||
echo -e "${red}[17] ${NC}↝ Uninstall Hysteria2"
|
||||
echo -e "${cyan}[17] ${NC}↝ IP Limiter Menu"
|
||||
echo -e "${red}[18] ${NC}↝ Uninstall Hysteria2"
|
||||
echo -e "${red}[0] ${NC}↝ Back to Main Menu"
|
||||
echo -e "${LPurple}◇──────────────────────────────────────────────────────────────────────◇${NC}"
|
||||
echo -ne "${yellow}➜ Enter your option: ${NC}"
|
||||
@ -963,7 +1053,8 @@ advance_menu() {
|
||||
14) masquerade_handler ;;
|
||||
15) python3 $CLI_PATH restart-hysteria2 ;;
|
||||
16) python3 $CLI_PATH update-hysteria2 ;;
|
||||
17) python3 $CLI_PATH uninstall-hysteria2 ;;
|
||||
17) ip_limit_handler ;;
|
||||
18) python3 $CLI_PATH uninstall-hysteria2 ;;
|
||||
0) return ;;
|
||||
*) echo "Invalid option. Please try again." ;;
|
||||
esac
|
||||
|
||||
Reference in New Issue
Block a user