1
1
import requests
2
2
import subprocess
3
+ import re
4
+ import logging
3
5
4
6
def func_calls ():
5
7
formats .get_format ()
6
8
algorithms .HMACAlgorithm .prepare_key ()
7
9
cli .VerifyOperation .perform_operation ()
8
10
sessions .SessionRedirectMixin .resolve_redirects ()
9
11
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
+
10
31
if __name__ == '__main__' :
32
+ # Set up logging
33
+ logging .basicConfig (level = logging .INFO )
34
+
11
35
session = requests .Session ()
12
36
proxies = {
13
37
'http' : 'http://test:pass@localhost:8080' ,
@@ -18,9 +42,12 @@ def func_calls():
18
42
prep = req .prepare ()
19
43
session .rebuild_proxies (prep , proxies )
20
44
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