@@ -18,9 +18,35 @@ def func_calls():
1818 prep = req .prepare ()
1919 session .rebuild_proxies (prep , proxies )
2020
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 )
21+ def is_valid_host (host ):
22+ """Validate if input is a valid hostname or IP address."""
23+ import re
24+ # Simple regex for IP address or hostname validation
25+ # Allows IPv4 addresses and hostnames with letters, numbers, dots, and hyphens
26+ pattern = r'^[a-zA-Z0-9][-a-zA-Z0-9.]{0,253}[a-zA-Z0-9]$|^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$'
27+ if not re .match (pattern , host ):
28+ return False
29+ # Check length constraints
30+ if len (host ) > 255 : # Maximum length for a hostname
31+ return False
32+ return True
2533
26- print ("Command executed!" )
34+ try :
35+ user_input = input ("Enter an address to ping: " ).strip ()
36+ if not is_valid_host (user_input ):
37+ raise ValueError ("Invalid host address. Please provide a valid hostname or IP address." )
38+
39+ # Use list of arguments and shell=False for security
40+ result = subprocess .run (['/usr/bin/ping' , '-c' , '4' , user_input ],
41+ shell = False ,
42+ check = True ,
43+ capture_output = True ,
44+ text = True )
45+ print ("Command executed successfully!" )
46+ print (result .stdout )
47+ except ValueError as e :
48+ print (f"Validation error: { e } " )
49+ except subprocess .CalledProcessError as e :
50+ print (f"Error executing ping command: { e } " )
51+ except Exception as e :
52+ print (f"Unexpected error: { e } " )
0 commit comments