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:
|
except Exception as e:
|
||||||
click.echo(f"An unexpected error occurred: {e}", err=True)
|
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
|
# endregion
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -48,6 +48,7 @@ class Command(Enum):
|
|||||||
STATUS_WARP = os.path.join(SCRIPT_DIR, 'warp', 'status.sh')
|
STATUS_WARP = os.path.join(SCRIPT_DIR, 'warp', 'status.sh')
|
||||||
SERVICES_STATUS = os.path.join(SCRIPT_DIR, 'services_status.sh')
|
SERVICES_STATUS = os.path.join(SCRIPT_DIR, 'services_status.sh')
|
||||||
VERSION = os.path.join(SCRIPT_DIR, 'hysteria2', 'version.py')
|
VERSION = os.path.join(SCRIPT_DIR, 'hysteria2', 'version.py')
|
||||||
|
LIMIT_SCRIPT = os.path.join(SCRIPT_DIR, 'hysteria2', 'limit.sh')
|
||||||
|
|
||||||
# region Custom Exceptions
|
# 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."""
|
"""Checks if the current version is up-to-date and displays changelog if not."""
|
||||||
return run_cmd(['python3', Command.VERSION.value, 'check-version'])
|
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
|
# endregion
|
||||||
|
|||||||
@ -1,27 +1,36 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
# Configuration
|
source /etc/hysteria/core/scripts/path.sh
|
||||||
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
|
|
||||||
|
|
||||||
# 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 "$CONNECTIONS_FILE" ] && echo "{}" > "$CONNECTIONS_FILE"
|
||||||
[ ! -f "$BLOCK_LIST" ] && touch "$BLOCK_LIST"
|
[ ! -f "$BLOCK_LIST" ] && touch "$BLOCK_LIST"
|
||||||
|
|
||||||
# Logging function
|
# --- Logging function ---
|
||||||
log_message() {
|
log_message() {
|
||||||
local level="$1"
|
local level="$1"
|
||||||
local message="$2"
|
local message="$2"
|
||||||
echo "[$(date +"%Y-%m-%d %H:%M:%S")] [$level] $message"
|
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() {
|
update_json() {
|
||||||
local username="$1"
|
local username="$1"
|
||||||
local ip_address="$2"
|
local ip_address="$2"
|
||||||
|
|
||||||
if command -v jq &>/dev/null; then
|
if command -v jq &>/dev/null; then
|
||||||
temp_file=$(mktemp)
|
temp_file=$(mktemp)
|
||||||
jq --arg user "$username" --arg ip "$ip_address" \
|
jq --arg user "$username" --arg ip "$ip_address" \
|
||||||
@ -38,31 +47,43 @@ update_json() {
|
|||||||
sed -i -E "s/\{(.*)\}/{\1,\"$username\":[\"$ip_address\"]}/" "$CONNECTIONS_FILE"
|
sed -i -E "s/\{(.*)\}/{\1,\"$username\":[\"$ip_address\"]}/" "$CONNECTIONS_FILE"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
log_message "INFO" "Updated JSON: Added $ip_address for user $username"
|
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() {
|
remove_ip() {
|
||||||
local username="$1"
|
local username="$1"
|
||||||
local ip_address="$2"
|
local ip_address="$2"
|
||||||
|
|
||||||
if [ ! -f "$CONNECTIONS_FILE" ]; then
|
if [ ! -f "$CONNECTIONS_FILE" ]; then
|
||||||
log_message "ERROR" "JSON file does not exist"
|
log_message "ERROR" "JSON file does not exist"
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if grep -q "\"$username\"" "$CONNECTIONS_FILE"; then
|
if grep -q "\"$username\"" "$CONNECTIONS_FILE"; then
|
||||||
if command -v jq &>/dev/null; then
|
if command -v jq &>/dev/null; then
|
||||||
temp_file=$(mktemp)
|
temp_file=$(mktemp)
|
||||||
jq --arg user "$username" --arg ip "$ip_address" \
|
jq --arg user "$username" --arg ip "$ip_address" \
|
||||||
'.[$user] = (.[$user] | map(select(. != $ip)))' "$CONNECTIONS_FILE" > "$temp_file"
|
'.[$user] = (.[$user] | map(select(. != $ip)))' "$CONNECTIONS_FILE" > "$temp_file"
|
||||||
mv "$temp_file" "$CONNECTIONS_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
|
else
|
||||||
# Basic sed replacement (not as reliable as jq)
|
# 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/\"$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"
|
||||||
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
|
fi
|
||||||
log_message "INFO" "Updated JSON: Removed $ip_address for user $username"
|
log_message "INFO" "Updated JSON: Removed $ip_address for user $username"
|
||||||
else
|
else
|
||||||
@ -70,46 +91,46 @@ remove_ip() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
# Block an IP using iptables and track it
|
# --- Block an IP using iptables and track it ---
|
||||||
block_ip() {
|
block_ip() {
|
||||||
local ip_address="$1"
|
local ip_address="$1"
|
||||||
local username="$2"
|
local username="$2"
|
||||||
local unblock_time=$(( $(date +%s) + BLOCK_DURATION ))
|
local unblock_time=$(( $(date +%s) + BLOCK_DURATION ))
|
||||||
|
|
||||||
# Skip if already blocked
|
# Skip if already blocked
|
||||||
if iptables -C INPUT -s "$ip_address" -j DROP 2>/dev/null; then
|
if iptables -C INPUT -s "$ip_address" -j DROP 2>/dev/null; then
|
||||||
log_message "INFO" "IP $ip_address is already blocked"
|
log_message "INFO" "IP $ip_address is already blocked"
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Add to iptables
|
# Add to iptables
|
||||||
iptables -I INPUT -s "$ip_address" -j DROP
|
iptables -I INPUT -s "$ip_address" -j DROP
|
||||||
|
|
||||||
# Add to block list with expiration time
|
# Add to block list with expiration time
|
||||||
echo "$ip_address,$username,$unblock_time" >> "$BLOCK_LIST"
|
echo "$ip_address,$username,$unblock_time" >> "$BLOCK_LIST"
|
||||||
|
|
||||||
log_message "WARN" "Blocked IP $ip_address for user $username for $BLOCK_DURATION seconds"
|
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() {
|
unblock_ip() {
|
||||||
local ip_address="$1"
|
local ip_address="$1"
|
||||||
|
|
||||||
# Remove from iptables if exists
|
# Remove from iptables if exists
|
||||||
if iptables -C INPUT -s "$ip_address" -j DROP 2>/dev/null; then
|
if iptables -C INPUT -s "$ip_address" -j DROP 2>/dev/null; then
|
||||||
iptables -D INPUT -s "$ip_address" -j DROP
|
iptables -D INPUT -s "$ip_address" -j DROP
|
||||||
log_message "INFO" "Unblocked IP $ip_address"
|
log_message "INFO" "Unblocked IP $ip_address"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Remove from block list
|
# Remove from block list
|
||||||
sed -i "/$ip_address,/d" "$BLOCK_LIST"
|
sed -i "/$ip_address,/d" "$BLOCK_LIST"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Block all IPs for a user
|
# --- Block all IPs for a user ---
|
||||||
block_all_user_ips() {
|
block_all_user_ips() {
|
||||||
local username="$1"
|
local username="$1"
|
||||||
local ips=()
|
local ips=()
|
||||||
|
|
||||||
# Get all IPs for this user
|
# Get all IPs for this user
|
||||||
if command -v jq &>/dev/null; then
|
if command -v jq &>/dev/null; then
|
||||||
readarray -t ips < <(jq -r --arg user "$username" '.[$user][]' "$CONNECTIONS_FILE" 2>/dev/null)
|
readarray -t ips < <(jq -r --arg user "$username" '.[$user][]' "$CONNECTIONS_FILE" 2>/dev/null)
|
||||||
@ -125,7 +146,7 @@ block_all_user_ips() {
|
|||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Block all IPs for this user
|
# Block all IPs for this user
|
||||||
for ip in "${ips[@]}"; do
|
for ip in "${ips[@]}"; do
|
||||||
ip=${ip//\"/} # Remove quotes
|
ip=${ip//\"/} # Remove quotes
|
||||||
@ -134,15 +155,15 @@ block_all_user_ips() {
|
|||||||
block_ip "$ip" "$username"
|
block_ip "$ip" "$username"
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
log_message "WARN" "User $username has been completely blocked for $BLOCK_DURATION seconds"
|
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() {
|
check_expired_blocks() {
|
||||||
local current_time=$(date +%s)
|
local current_time=$(date +%s)
|
||||||
local ip username expiry
|
local ip username expiry
|
||||||
|
|
||||||
# Check each line in the block list
|
# Check each line in the block list
|
||||||
while IFS=, read -r ip username expiry || [ -n "$ip" ]; do
|
while IFS=, read -r ip username expiry || [ -n "$ip" ]; do
|
||||||
if [[ -n "$ip" && -n "$expiry" ]]; then
|
if [[ -n "$ip" && -n "$expiry" ]]; then
|
||||||
@ -154,11 +175,11 @@ check_expired_blocks() {
|
|||||||
done < "$BLOCK_LIST"
|
done < "$BLOCK_LIST"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Check if a user has exceeded the IP limit
|
# --- Check if a user has exceeded the IP limit ---
|
||||||
check_ip_limit() {
|
check_ip_limit() {
|
||||||
local username="$1"
|
local username="$1"
|
||||||
local ips=()
|
local ips=()
|
||||||
|
|
||||||
# Get all IPs for this user
|
# Get all IPs for this user
|
||||||
if command -v jq &>/dev/null; then
|
if command -v jq &>/dev/null; then
|
||||||
readarray -t ips < <(jq -r --arg user "$username" '.[$user][]' "$CONNECTIONS_FILE" 2>/dev/null)
|
readarray -t ips < <(jq -r --arg user "$username" '.[$user][]' "$CONNECTIONS_FILE" 2>/dev/null)
|
||||||
@ -174,9 +195,9 @@ check_ip_limit() {
|
|||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
fi
|
fi
|
||||||
|
|
||||||
ip_count=${#ips[@]}
|
ip_count=${#ips[@]}
|
||||||
|
|
||||||
# If the user has more IPs than allowed, block ALL their IPs
|
# If the user has more IPs than allowed, block ALL their IPs
|
||||||
if (( ip_count > MAX_IPS )); then
|
if (( ip_count > MAX_IPS )); then
|
||||||
log_message "WARN" "User $username has $ip_count IPs (max: $MAX_IPS) - blocking all IPs"
|
log_message "WARN" "User $username has $ip_count IPs (max: $MAX_IPS) - blocking all IPs"
|
||||||
@ -184,16 +205,16 @@ check_ip_limit() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
# Parse log lines for connections and disconnections
|
# --- Parse log lines for connections and disconnections ---
|
||||||
parse_log_line() {
|
parse_log_line() {
|
||||||
local log_line="$1"
|
local log_line="$1"
|
||||||
local ip_address=""
|
local ip_address=""
|
||||||
local username=""
|
local username=""
|
||||||
|
|
||||||
# Extract IP address and username
|
# Extract IP address and username
|
||||||
ip_address=$(echo "$log_line" | grep -oP '"addr": "([^:]+)' | cut -d'"' -f4)
|
ip_address=$(echo "$log_line" | grep -oP '"addr": "([^:]+)' | cut -d'"' -f4)
|
||||||
username=$(echo "$log_line" | grep -oP '"id": "([^">]+)' | cut -d'"' -f4)
|
username=$(echo "$log_line" | grep -oP '"id": "([^">]+)' | cut -d'"' -f4)
|
||||||
|
|
||||||
if [[ -n "$username" && -n "$ip_address" ]]; then
|
if [[ -n "$username" && -n "$ip_address" ]]; then
|
||||||
if echo "$log_line" | grep -q "client connected"; then
|
if echo "$log_line" | grep -q "client connected"; then
|
||||||
# Check if this IP is in the block list
|
# Check if this IP is in the block list
|
||||||
@ -214,47 +235,130 @@ parse_log_line() {
|
|||||||
fi
|
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
|
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
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Check for jq and warn if not available
|
# --- Check for jq and warn if not available ---
|
||||||
if ! command -v jq &>/dev/null; then
|
if ! command -v jq &>/dev/null; then
|
||||||
log_message "WARN" "'jq' is not installed. JSON handling may be less reliable."
|
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)"
|
log_message "WARN" "Consider installing jq with: apt install jq (for Debian/Ubuntu)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Main script
|
# --- Command execution based on arguments ---
|
||||||
log_message "INFO" "Monitoring Hysteria server connections. Max IPs per user: $MAX_IPS"
|
case "$1" in
|
||||||
log_message "INFO" "Block duration: $BLOCK_DURATION seconds"
|
start)
|
||||||
log_message "INFO" "Connection data saved to: $CONNECTIONS_FILE"
|
install_service
|
||||||
log_message "INFO" "Press Ctrl+C to exit"
|
;;
|
||||||
log_message "INFO" "--------------------------------------------------------"
|
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
|
while true; do
|
||||||
check_expired_blocks
|
check_expired_blocks
|
||||||
sleep 10
|
sleep 10
|
||||||
done
|
done
|
||||||
) &
|
) &
|
||||||
CHECKER_PID=$!
|
CHECKER_PID=$!
|
||||||
|
|
||||||
# Cleanup function
|
# Cleanup function
|
||||||
cleanup() {
|
cleanup() {
|
||||||
log_message "INFO" "Stopping IP limiter..."
|
log_message "INFO" "Stopping IP limiter..."
|
||||||
kill $CHECKER_PID 2>/dev/null
|
kill $CHECKER_PID 2>/dev/null
|
||||||
exit 0
|
exit 0
|
||||||
}
|
}
|
||||||
|
|
||||||
# Set trap for cleanup
|
# Set trap for cleanup
|
||||||
trap cleanup SIGINT SIGTERM
|
trap cleanup SIGINT SIGTERM
|
||||||
|
|
||||||
# Monitor log for connections and disconnections
|
# Monitor log for connections and disconnections
|
||||||
journalctl -u hysteria-server.service -f | while read -r line; do
|
journalctl -u hysteria-server.service -f | while read -r line; do
|
||||||
if echo "$line" | grep -q "client connected\|client disconnected"; then
|
if echo "$line" | grep -q "client connected\|client disconnected"; then
|
||||||
parse_log_line "$line"
|
parse_log_line "$line"
|
||||||
fi
|
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"
|
LOCALVERSION="/etc/hysteria/VERSION"
|
||||||
LATESTVERSION="https://raw.githubusercontent.com/ReturnFI/Hysteria2/main/VERSION"
|
LATESTVERSION="https://raw.githubusercontent.com/ReturnFI/Hysteria2/main/VERSION"
|
||||||
LASTESTCHANGE="https://raw.githubusercontent.com/ReturnFI/Hysteria2/main/changelog"
|
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-telegram-bot.service"
|
||||||
"hysteria-normal-sub.service"
|
"hysteria-normal-sub.service"
|
||||||
"hysteria-singbox.service"
|
"hysteria-singbox.service"
|
||||||
|
"hysteria-ip-limit.service"
|
||||||
"wg-quick@wgcf.service"
|
"wg-quick@wgcf.service"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
95
menu.sh
95
menu.sh
@ -805,6 +805,95 @@ masquerade_handler() {
|
|||||||
done
|
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
|
# Function to display the main menu
|
||||||
display_main_menu() {
|
display_main_menu() {
|
||||||
@ -933,7 +1022,8 @@ display_advance_menu() {
|
|||||||
echo -e "${cyan}[14] ${NC}↝ Manage Masquerade"
|
echo -e "${cyan}[14] ${NC}↝ Manage Masquerade"
|
||||||
echo -e "${cyan}[15] ${NC}↝ Restart Hysteria2"
|
echo -e "${cyan}[15] ${NC}↝ Restart Hysteria2"
|
||||||
echo -e "${cyan}[16] ${NC}↝ Update Core 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 "${red}[0] ${NC}↝ Back to Main Menu"
|
||||||
echo -e "${LPurple}◇──────────────────────────────────────────────────────────────────────◇${NC}"
|
echo -e "${LPurple}◇──────────────────────────────────────────────────────────────────────◇${NC}"
|
||||||
echo -ne "${yellow}➜ Enter your option: ${NC}"
|
echo -ne "${yellow}➜ Enter your option: ${NC}"
|
||||||
@ -963,7 +1053,8 @@ advance_menu() {
|
|||||||
14) masquerade_handler ;;
|
14) masquerade_handler ;;
|
||||||
15) python3 $CLI_PATH restart-hysteria2 ;;
|
15) python3 $CLI_PATH restart-hysteria2 ;;
|
||||||
16) python3 $CLI_PATH update-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 ;;
|
0) return ;;
|
||||||
*) echo "Invalid option. Please try again." ;;
|
*) echo "Invalid option. Please try again." ;;
|
||||||
esac
|
esac
|
||||||
|
|||||||
Reference in New Issue
Block a user