Skip to content

Commit 5463a0e

Browse files
author
patched.codes[bot]
committed
Patched main.py
1 parent 2e17671 commit 5463a0e

File tree

1 file changed

+32
-5
lines changed

1 file changed

+32
-5
lines changed

main.py

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import requests
22
import subprocess
3+
import re
4+
5+
def is_valid_hostname(hostname):
6+
"""Validate hostname using regex pattern."""
7+
pattern = r'^[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?)*$'
8+
return bool(re.match(pattern, hostname))
39

410
def func_calls():
511
formats.get_format()
@@ -18,9 +24,30 @@ def func_calls():
1824
prep = req.prepare()
1925
session.rebuild_proxies(prep, proxies)
2026

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)
27+
def execute_ping(hostname):
28+
"""Execute ping command safely with input validation."""
29+
try:
30+
if not is_valid_hostname(hostname):
31+
raise ValueError("Invalid hostname format")
32+
33+
command = ["ping", hostname]
34+
result = subprocess.run(command, check=True, capture_output=True, text=True)
35+
return result.stdout
36+
except ValueError as e:
37+
raise
38+
except subprocess.CalledProcessError as e:
39+
raise
40+
except Exception as e:
41+
raise
2542

26-
print("Command executed!")
43+
if __name__ == '__main__':
44+
try:
45+
user_input = input("Enter hostname to ping: ")
46+
output = execute_ping(user_input)
47+
print(output)
48+
except ValueError as e:
49+
print(f"Error: {e}")
50+
except subprocess.CalledProcessError as e:
51+
print(f"Command failed with exit code {e.returncode}")
52+
except Exception as e:
53+
print(f"An unexpected error occurred: {e}")

0 commit comments

Comments
 (0)