ChrisSacrumCor commited on
Commit
6a00d1e
·
verified ·
1 Parent(s): 3a19347

Create tools/linux_tools.py

Browse files
Files changed (1) hide show
  1. tools/linux_tools.py +359 -0
tools/linux_tools.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Linux administration tools for Gradio MCP server.
3
+ Uses @gr.tool decorator to automatically create MCP tools.
4
+ """
5
+
6
+ import gradio as gr
7
+ import subprocess
8
+ import os
9
+ import pwd
10
+ import grp
11
+ import shlex
12
+ from typing import List, Optional
13
+ from shared.config import config
14
+ import logging
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ # Sensitive Tools (require Socratic dialogue)
19
+
20
+ @gr.tool
21
+ def add_user(username: str, groups: Optional[List[str]] = None,
22
+ create_home: bool = True, shell: str = "/bin/bash") -> dict:
23
+ """
24
+ Add a new system user with proper validation.
25
+ This is a SENSITIVE operation requiring careful consideration.
26
+
27
+ Args:
28
+ username: Username (lowercase, alphanumeric, starts with letter)
29
+ groups: Additional groups for the user (optional)
30
+ create_home: Create home directory for user
31
+ shell: Default shell for user
32
+
33
+ Returns:
34
+ Dictionary with success status and details
35
+ """
36
+ # Validate username
37
+ if not _validate_username(username):
38
+ return {
39
+ "success": False,
40
+ "error": "Invalid username format",
41
+ "details": "Username must be lowercase, alphanumeric, and start with letter",
42
+ "tool_type": "sensitive_operation"
43
+ }
44
+
45
+ # Check if user already exists
46
+ try:
47
+ pwd.getpwnam(username)
48
+ return {
49
+ "success": False,
50
+ "error": f"User '{username}' already exists",
51
+ "tool_type": "sensitive_operation"
52
+ }
53
+ except KeyError:
54
+ pass # User doesn't exist, which is what we want
55
+
56
+ # Build useradd command
57
+ cmd = ["useradd"]
58
+
59
+ if create_home:
60
+ cmd.append("-m")
61
+
62
+ if shell:
63
+ cmd.extend(["-s", shell])
64
+
65
+ if groups:
66
+ # Validate groups exist
67
+ valid_groups = []
68
+ for group in groups:
69
+ try:
70
+ grp.getgrnam(group)
71
+ valid_groups.append(group)
72
+ except KeyError:
73
+ logger.warning(f"Group '{group}' does not exist, skipping")
74
+
75
+ if valid_groups:
76
+ cmd.extend(["-G", ",".join(valid_groups)])
77
+
78
+ cmd.append(username)
79
+
80
+ try:
81
+ logger.info(f"Adding user: {' '.join(cmd)}")
82
+ result = subprocess.run(
83
+ cmd,
84
+ capture_output=True,
85
+ text=True,
86
+ timeout=config.security.command_timeout,
87
+ check=False
88
+ )
89
+
90
+ if result.returncode == 0:
91
+ return {
92
+ "success": True,
93
+ "message": f"User '{username}' created successfully",
94
+ "details": {
95
+ "username": username,
96
+ "groups": groups or [],
97
+ "home_created": create_home,
98
+ "shell": shell
99
+ },
100
+ "tool_type": "sensitive_operation"
101
+ }
102
+ else:
103
+ return {
104
+ "success": False,
105
+ "error": f"Failed to create user: {result.stderr}",
106
+ "exit_code": result.returncode,
107
+ "tool_type": "sensitive_operation"
108
+ }
109
+
110
+ except Exception as e:
111
+ return {
112
+ "success": False,
113
+ "error": f"Error creating user: {str(e)}",
114
+ "tool_type": "sensitive_operation"
115
+ }
116
+
117
+ @gr.tool
118
+ def create_file(filepath: str, content: str, permissions: str = "644",
119
+ owner: Optional[str] = None) -> dict:
120
+ """
121
+ Create a new file with specified content and permissions.
122
+ This is a SENSITIVE operation that modifies the filesystem.
123
+
124
+ Args:
125
+ filepath: Full path where file should be created
126
+ content: Content to write to the file
127
+ permissions: File permissions in octal notation (e.g., 644, 755)
128
+ owner: File owner (optional, defaults to current user)
129
+
130
+ Returns:
131
+ Dictionary with success status and details
132
+ """
133
+ # Validate file path
134
+ if not _validate_filepath(filepath):
135
+ return {
136
+ "success": False,
137
+ "error": "Invalid file path - must be absolute and safe",
138
+ "tool_type": "sensitive_operation"
139
+ }
140
+
141
+ # Check if file already exists
142
+ if os.path.exists(filepath):
143
+ return {
144
+ "success": False,
145
+ "error": f"File '{filepath}' already exists",
146
+ "tool_type": "sensitive_operation"
147
+ }
148
+
149
+ try:
150
+ # Create directory if needed
151
+ directory = os.path.dirname(filepath)
152
+ if directory and not os.path.exists(directory):
153
+ os.makedirs(directory, mode=0o755)
154
+
155
+ # Write file
156
+ with open(filepath, 'w') as f:
157
+ f.write(content)
158
+
159
+ # Set permissions
160
+ os.chmod(filepath, int(permissions, 8))
161
+
162
+ # Change owner if specified
163
+ if owner:
164
+ try:
165
+ user_info = pwd.getpwnam(owner)
166
+ os.chown(filepath, user_info.pw_uid, user_info.pw_gid)
167
+ except KeyError:
168
+ logger.warning(f"User '{owner}' not found, keeping current owner")
169
+
170
+ return {
171
+ "success": True,
172
+ "message": f"File '{filepath}' created successfully",
173
+ "details": {
174
+ "path": filepath,
175
+ "permissions": permissions,
176
+ "owner": owner,
177
+ "size": len(content)
178
+ },
179
+ "tool_type": "sensitive_operation"
180
+ }
181
+
182
+ except Exception as e:
183
+ return {
184
+ "success": False,
185
+ "error": f"Error creating file: {str(e)}",
186
+ "tool_type": "sensitive_operation"
187
+ }
188
+
189
+ @gr.tool
190
+ def change_permission(path: str, permissions: str, recursive: bool = False,
191
+ owner: Optional[str] = None) -> dict:
192
+ """
193
+ Change file or directory permissions.
194
+ This is a SENSITIVE operation that affects system security.
195
+
196
+ Args:
197
+ path: Path to file or directory
198
+ permissions: New permissions in octal notation (e.g., 755, 644)
199
+ recursive: Apply permissions recursively (for directories)
200
+ owner: Change owner as well (optional)
201
+
202
+ Returns:
203
+ Dictionary with success status and details
204
+ """
205
+ if not os.path.exists(path):
206
+ return {
207
+ "success": False,
208
+ "error": f"Path '{path}' does not exist",
209
+ "tool_type": "sensitive_operation"
210
+ }
211
+
212
+ try:
213
+ # Change permissions
214
+ perm_octal = int(permissions, 8)
215
+
216
+ if recursive and os.path.isdir(path):
217
+ # Recursively change permissions
218
+ for root, dirs, files in os.walk(path):
219
+ os.chmod(root, perm_octal)
220
+ for file in files:
221
+ os.chmod(os.path.join(root, file), perm_octal)
222
+ else:
223
+ os.chmod(path, perm_octal)
224
+
225
+ # Change owner if specified
226
+ if owner:
227
+ try:
228
+ user_info = pwd.getpwnam(owner)
229
+ if recursive and os.path.isdir(path):
230
+ for root, dirs, files in os.walk(path):
231
+ os.chown(root, user_info.pw_uid, user_info.pw_gid)
232
+ for file in files:
233
+ os.chown(os.path.join(root, file), user_info.pw_uid, user_info.pw_gid)
234
+ else:
235
+ os.chown(path, user_info.pw_uid, user_info.pw_gid)
236
+ except KeyError:
237
+ return {
238
+ "success": False,
239
+ "error": f"User '{owner}' not found",
240
+ "tool_type": "sensitive_operation"
241
+ }
242
+
243
+ return {
244
+ "success": True,
245
+ "message": f"Permissions changed for '{path}'",
246
+ "details": {
247
+ "path": path,
248
+ "permissions": permissions,
249
+ "recursive": recursive,
250
+ "owner": owner
251
+ },
252
+ "tool_type": "sensitive_operation"
253
+ }
254
+
255
+ except Exception as e:
256
+ return {
257
+ "success": False,
258
+ "error": f"Error changing permissions: {str(e)}",
259
+ "tool_type": "sensitive_operation"
260
+ }
261
+
262
+ # Safe Command Tool (direct execution)
263
+
264
+ @gr.tool
265
+ def run_safe_command(command: str, args: Optional[List[str]] = None,
266
+ working_directory: Optional[str] = None) -> dict:
267
+ """
268
+ Execute safe, whitelisted system commands for information gathering.
269
+ These are READ-ONLY or low-risk operations.
270
+
271
+ Args:
272
+ command: Command to execute (must be from approved whitelist)
273
+ args: Command arguments (optional)
274
+ working_directory: Directory to run command in (optional)
275
+
276
+ Returns:
277
+ Dictionary with command output and status
278
+ """
279
+ if command not in config.security.safe_commands:
280
+ return {
281
+ "success": False,
282
+ "error": f"Command '{command}' not in whitelist",
283
+ "whitelist": config.security.safe_commands,
284
+ "tool_type": "safe_command"
285
+ }
286
+
287
+ # Build command
288
+ cmd_parts = [command]
289
+ if args:
290
+ # Validate and sanitize arguments
291
+ sanitized_args = [shlex.quote(arg) for arg in args if arg]
292
+ cmd_parts.extend(sanitized_args)
293
+
294
+ # Set working directory
295
+ if not working_directory:
296
+ working_directory = "/home"
297
+
298
+ try:
299
+ logger.info(f"Executing safe command: {' '.join(cmd_parts)} in {working_directory}")
300
+
301
+ result = subprocess.run(
302
+ cmd_parts,
303
+ cwd=working_directory,
304
+ capture_output=True,
305
+ text=True,
306
+ timeout=config.security.command_timeout,
307
+ check=False # Don't raise exception on non-zero exit
308
+ )
309
+
310
+ return {
311
+ "success": result.returncode == 0,
312
+ "output": result.stdout,
313
+ "error": result.stderr,
314
+ "exit_code": result.returncode,
315
+ "command": ' '.join(cmd_parts),
316
+ "tool_type": "safe_command"
317
+ }
318
+
319
+ except subprocess.TimeoutExpired:
320
+ return {
321
+ "success": False,
322
+ "error": f"Command timed out after {config.security.command_timeout} seconds",
323
+ "exit_code": -1,
324
+ "tool_type": "safe_command"
325
+ }
326
+ except Exception as e:
327
+ return {
328
+ "success": False,
329
+ "error": f"Execution error: {str(e)}",
330
+ "exit_code": -1,
331
+ "tool_type": "safe_command"
332
+ }
333
+
334
+ # Helper functions
335
+
336
+ def _validate_username(username: str) -> bool:
337
+ """Validate username format"""
338
+ if not username or not isinstance(username, str):
339
+ return False
340
+ if len(username) > 32: # Typical Linux limit
341
+ return False
342
+ if not username[0].islower() or not username[0].isalpha():
343
+ return False
344
+ return all(c.islower() or c.isdigit() or c in '_-' for c in username)
345
+
346
+ def _validate_filepath(filepath: str) -> bool:
347
+ """Basic file path validation"""
348
+ if not filepath or not isinstance(filepath, str):
349
+ return False
350
+ if not os.path.isabs(filepath):
351
+ return False
352
+ # Prevent path traversal
353
+ if '..' in filepath:
354
+ return False
355
+ # Prevent access to sensitive system files
356
+ forbidden_paths = ['/etc/passwd', '/etc/shadow', '/etc/sudoers']
357
+ if filepath in forbidden_paths:
358
+ return False
359
+ return True