11import requests
22import subprocess
3+ import re
4+ import logging
35
46def func_calls ():
57 formats .get_format ()
68 algorithms .HMACAlgorithm .prepare_key ()
79 cli .VerifyOperation .perform_operation ()
810 sessions .SessionRedirectMixin .resolve_redirects ()
911
12+ def validate_hostname (hostname ):
13+ """Validate hostname using regex pattern."""
14+ pattern = r'^[a-zA-Z0-9.-]+$'
15+ return bool (re .match (pattern , hostname ))
16+
17+ def safe_ping (hostname ):
18+ """Execute ping command safely with input validation."""
19+ if not validate_hostname (hostname ):
20+ logging .warning (f"Invalid hostname attempted: { hostname } " )
21+ raise ValueError ("Invalid hostname. Only alphanumeric characters, dots, and hyphens are allowed." )
22+
23+ try :
24+ logging .info (f"Executing ping command for hostname: { hostname } " )
25+ result = subprocess .call (['ping' , hostname ], shell = False )
26+ return result
27+ except Exception as e :
28+ logging .error (f"Error executing ping command: { str (e )} " )
29+ raise
30+
1031if __name__ == '__main__' :
32+ # Set up logging
33+ logging .basicConfig (level = logging .INFO )
34+
1135 session = requests .Session ()
1236 proxies = {
1337 'http' : 'http://test:pass@localhost:8080' ,
@@ -18,9 +42,12 @@ def func_calls():
1842 prep = req .prepare ()
1943 session .rebuild_proxies (prep , proxies )
2044
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 )
25-
26- print ("Command executed!" )
45+ # Execute ping command safely
46+ try :
47+ user_input = input ("Enter a hostname to ping: " )
48+ safe_ping (user_input )
49+ print ("Command executed successfully!" )
50+ except ValueError as e :
51+ print (f"Error: { e } " )
52+ except Exception as e :
53+ print (f"An unexpected error occurred: { e } " )
0 commit comments