-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmac_daemon.py
More file actions
executable file
·270 lines (235 loc) · 8.67 KB
/
mac_daemon.py
File metadata and controls
executable file
·270 lines (235 loc) · 8.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#!/usr/bin/env python3
"""
VM-to-Host Command Bridge Daemon
Runs on Mac host, accepts commands from VM via reverse SSH tunnel
"""
import socket
import json
import subprocess
import threading
import logging
import sys
import os
from datetime import datetime
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(os.path.expanduser('~/Library/Logs/vm-bridge.log')),
logging.StreamHandler()
]
)
# Command whitelist with configuration
COMMANDS = {
'pbcopy': {
'binary': '/usr/bin/pbcopy',
'allow_stdin': True,
'allow_args': False,
'max_stdin_size': 10 * 1024 * 1024, # 10MB max
'description': 'Copy to Mac clipboard'
},
'pbpaste': {
'binary': '/usr/bin/pbpaste',
'allow_stdout': True,
'allow_args': False,
'description': 'Paste from Mac clipboard'
},
'notify': {
'binary': '/usr/bin/osascript',
'allow_args': True,
'args_template': ['-e', 'display notification "{message}" with title "VM Bridge"'],
'description': 'Show Mac notification'
},
'open_url': {
'binary': '/usr/bin/open',
'allow_args': True,
'args_validator': lambda args: len(args) == 1 and args[0].startswith(('http://', 'https://')),
'description': 'Open URL in Mac browser'
}
}
class CommandHandler:
"""Handle individual command execution"""
@staticmethod
def execute(request):
"""Execute a whitelisted command"""
try:
cmd_name = request.get('cmd')
if not cmd_name or cmd_name not in COMMANDS:
return {
'success': False,
'error': f'Unknown command: {cmd_name}'
}
config = COMMANDS[cmd_name]
# Validate stdin size if provided
stdin_data = request.get('stdin', '')
if stdin_data and config.get('allow_stdin'):
max_size = config.get('max_stdin_size', float('inf'))
if len(stdin_data) > max_size:
return {
'success': False,
'error': f'Stdin too large: {len(stdin_data)} > {max_size}'
}
elif stdin_data and not config.get('allow_stdin'):
return {
'success': False,
'error': f'Command {cmd_name} does not accept stdin'
}
# Build command
cmd = [config['binary']]
# Handle arguments
if config.get('allow_args'):
args = request.get('args', [])
if config.get('args_template'):
# Use template (for notify)
template = config['args_template'].copy()
for i, arg in enumerate(template):
if '{message}' in arg and args:
template[i] = arg.replace('{message}', args[0])
cmd.extend(template)
elif config.get('args_validator'):
# Validate args
if config['args_validator'](args):
cmd.extend(args)
else:
return {
'success': False,
'error': 'Invalid arguments'
}
else:
cmd.extend(args)
# Execute command
process = subprocess.Popen(
cmd,
stdin=subprocess.PIPE if stdin_data else None,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
stdout, stderr = process.communicate(
input=stdin_data if stdin_data else None,
timeout=request.get('timeout', 5)
)
return {
'success': process.returncode == 0,
'stdout': stdout if config.get('allow_stdout') else '',
'stderr': stderr,
'exit_code': process.returncode
}
except subprocess.TimeoutExpired:
return {
'success': False,
'error': 'Command timed out'
}
except Exception as e:
logging.error(f"Command execution error: {e}")
return {
'success': False,
'error': str(e)
}
class ClientHandler(threading.Thread):
"""Handle individual client connections"""
def __init__(self, client_socket, address):
super().__init__()
self.client = client_socket
self.address = address
self.daemon = True
def run(self):
"""Handle client request"""
try:
# Receive data (up to 10MB)
data = b''
while True:
chunk = self.client.recv(4096)
if not chunk:
break
data += chunk
if len(data) > 10 * 1024 * 1024:
raise ValueError("Request too large")
# Check if we have a complete JSON object
try:
json.loads(data.decode('utf-8'))
break # Valid JSON, we have the complete message
except:
continue # Keep reading
# Parse request
request = json.loads(data.decode('utf-8'))
request_id = request.get('id', 'unknown')
logging.info(f"Request {request_id}: {request.get('cmd')} from {self.address}")
# Execute command
result = CommandHandler.execute(request)
# Add request ID to response
result['id'] = request_id
# Send response
response = json.dumps(result).encode('utf-8')
self.client.send(response)
logging.info(f"Request {request_id}: {'Success' if result.get('success') else 'Failed'}")
except Exception as e:
logging.error(f"Client handler error: {e}")
error_response = json.dumps({
'success': False,
'error': str(e)
}).encode('utf-8')
try:
self.client.send(error_response)
except:
pass
finally:
self.client.close()
class VMBridgeDaemon:
"""Main daemon class"""
def __init__(self, host='127.0.0.1', port=9999):
self.host = host
self.port = port
self.socket = None
self.running = False
def start(self):
"""Start the daemon"""
try:
# Create socket
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind to localhost only for security
self.socket.bind((self.host, self.port))
self.socket.listen(5)
self.running = True
logging.info(f"VM Bridge Daemon started on {self.host}:{self.port}")
print(f"🚀 VM Bridge Daemon listening on {self.host}:{self.port}")
print(f"📝 Logs: ~/Library/Logs/vm-bridge.log")
print(f"Available commands: {', '.join(COMMANDS.keys())}")
# Accept connections
while self.running:
try:
client, address = self.socket.accept()
handler = ClientHandler(client, address)
handler.start()
except KeyboardInterrupt:
break
except Exception as e:
logging.error(f"Accept error: {e}")
except Exception as e:
logging.error(f"Daemon start error: {e}")
print(f"❌ Failed to start daemon: {e}")
sys.exit(1)
finally:
self.stop()
def stop(self):
"""Stop the daemon"""
self.running = False
if self.socket:
self.socket.close()
logging.info("VM Bridge Daemon stopped")
print("\n👋 VM Bridge Daemon stopped")
def main():
"""Main entry point"""
print("=" * 50)
print("VM-to-Host Command Bridge Daemon")
print("=" * 50)
daemon = VMBridgeDaemon()
try:
daemon.start()
except KeyboardInterrupt:
print("\nShutting down...")
daemon.stop()
if __name__ == '__main__':
main()