Skip to content

Commit 9debf6b

Browse files
author
patched.codes[bot]
committed
Patched main.py
1 parent 2441ace commit 9debf6b

File tree

1 file changed

+102
-16
lines changed

1 file changed

+102
-16
lines changed

main.py

Lines changed: 102 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,112 @@
11
import requests
22
import subprocess
3+
import re
4+
import os
5+
from typing import Tuple
6+
from urllib.parse import urlparse
37

4-
def func_calls():
5-
formats.get_format()
6-
algorithms.HMACAlgorithm.prepare_key()
7-
cli.VerifyOperation.perform_operation()
8-
sessions.SessionRedirectMixin.resolve_redirects()
8+
def validate_host(host: str) -> Tuple[bool, str]:
9+
"""
10+
Validate if the input is a valid hostname or IP address.
11+
12+
Args:
13+
host: The hostname or IP address to validate
14+
15+
Returns:
16+
Tuple of (is_valid: bool, error_message: str)
17+
"""
18+
# Remove any whitespace
19+
host = host.strip()
20+
21+
# Check for empty input
22+
if not host:
23+
return False, "Host cannot be empty"
24+
25+
# Check input length
26+
if len(host) > 255:
27+
return False, "Host name too long"
28+
29+
# Basic hostname/IP validation regex
30+
# Matches hostnames and IPv4 addresses
31+
pattern = r'^[a-zA-Z0-9]([a-zA-Z0-9\-\.]{0,253}[a-zA-Z0-9])?$'
32+
if not re.match(pattern, host):
33+
return False, "Invalid hostname format"
34+
35+
return True, ""
36+
37+
def safe_ping(host: str) -> Tuple[bool, str]:
38+
"""
39+
Safely execute a ping command with proper input validation and error handling.
40+
41+
Args:
42+
host: The hostname or IP to ping
43+
44+
Returns:
45+
Tuple of (success: bool, message: str)
46+
"""
47+
# Validate input
48+
is_valid, error = validate_host(host)
49+
if not is_valid:
50+
return False, f"Invalid input: {error}"
51+
52+
try:
53+
# Use subprocess.run with a list of arguments and shell=False for security
54+
result = subprocess.run(
55+
['ping', '-c', '4', host], # Fixed number of pings for safety
56+
shell=False,
57+
capture_output=True,
58+
text=True,
59+
timeout=10 # Timeout after 10 seconds
60+
)
61+
62+
if result.returncode == 0:
63+
return True, result.stdout
64+
else:
65+
return False, f"Ping failed: {result.stderr}"
66+
67+
except subprocess.TimeoutExpired:
68+
return False, "Ping timed out after 10 seconds"
69+
except subprocess.SubprocessError as e:
70+
return False, f"Error executing ping: {str(e)}"
71+
except Exception as e:
72+
return False, f"Unexpected error: {str(e)}"
73+
74+
def get_proxy_config() -> dict:
75+
"""
76+
Get proxy configuration from environment variables.
77+
Returns an empty dict if no proxy is configured.
78+
"""
79+
proxy_config = {}
80+
81+
# Read proxy settings from environment variables
82+
http_proxy = os.getenv('HTTP_PROXY')
83+
https_proxy = os.getenv('HTTPS_PROXY')
84+
85+
if http_proxy:
86+
proxy_config['http'] = http_proxy
87+
if https_proxy:
88+
proxy_config['https'] = https_proxy
89+
90+
return proxy_config
991

1092
if __name__ == '__main__':
1193
session = requests.Session()
12-
proxies = {
13-
'http': 'http://test:pass@localhost:8080',
14-
'https': 'http://test:pass@localhost:8090',
15-
}
94+
95+
# Get proxy configuration from environment instead of hardcoding
96+
proxies = get_proxy_config()
97+
1698
url = 'http://example.com' # Replace with a valid URL
1799
req = requests.Request('GET', url)
18100
prep = req.prepare()
19-
session.rebuild_proxies(prep, proxies)
20-
21-
# Introduce a command injection vulnerability
22-
user_input = input("Enter a command to execute: ")
23-
command = "ping " + user_input
24-
subprocess.call(command, shell=True)
101+
if proxies:
102+
session.rebuild_proxies(prep, proxies)
25103

26-
print("Command executed!")
104+
# Secure implementation of ping command
105+
user_input = input("Enter a hostname or IP to ping: ")
106+
success, message = safe_ping(user_input)
107+
108+
if success:
109+
print("Ping successful!")
110+
print(message)
111+
else:
112+
print(f"Error: {message}")

0 commit comments

Comments
 (0)