-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopenhands-server-userdata.sh
More file actions
522 lines (429 loc) · 14.4 KB
/
openhands-server-userdata.sh
File metadata and controls
522 lines (429 loc) · 14.4 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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
#!/bin/bash
# OpenHands Server User Data Script
# This script sets up the isolated OpenHands server with strict network controls
set -e
# Variables from template
PROJECT_NAME="${project_name}"
LLM_ENDPOINT="${llm_endpoint}"
# Update system
apt-get update && apt-get upgrade -y
# Install required packages
apt-get install -y \
python3 \
python3-pip \
python3-venv \
nodejs \
npm \
docker.io \
docker-compose \
git \
curl \
wget \
ufw \
iptables-persistent \
dnsutils \
fail2ban \
awscli \
htop \
vim \
unzip
# Create openhands user with secure password
useradd -m -s /bin/bash openhands
OPENHANDS_PASSWORD=$(openssl rand -base64 32)
echo "openhands:$OPENHANDS_PASSWORD" | chpasswd
# Add user to necessary groups
usermod -aG docker,sudo openhands
# Configure strict firewall rules
ufw --force reset
ufw default deny incoming
ufw default deny outgoing
# Allow SSH from public subnet (web proxy)
ufw allow from 10.0.0.0/24 to any port 22
# Allow OpenHands web interface from public subnet
ufw allow from 10.0.0.0/24 to any port 3000
# Allow outbound HTTPS and HTTP (will be restricted further by iptables)
ufw allow out 443
ufw allow out 80
# Allow DNS to VPC resolver
ufw allow out to 10.0.0.2 port 53
# Allow NTP for time synchronization
ufw allow out 123
# Enable firewall
ufw enable
# Start and enable Docker
systemctl enable docker
systemctl start docker
# Install Node.js LTS (if needed for OpenHands frontend)
curl -fsSL https://deb.nodesource.com/setup_lts.x | bash -
apt-get install -y nodejs
# Clone and setup OpenHands as the openhands user
cd /home/openhands
sudo -u openhands git clone https://github.com/All-Hands-AI/OpenHands.git
chown -R openhands:openhands OpenHands
# Setup OpenHands environment
sudo -u openhands bash << 'EOSU'
cd /home/openhands/OpenHands
# Create Python virtual environment
python3 -m venv venv
source venv/bin/activate
# Upgrade pip and install OpenHands
pip install --upgrade pip
pip install -e .
# Create OpenHands configuration directory
mkdir -p /home/openhands/.openhands
# Create configuration file
cat > /home/openhands/.openhands/config.toml << EOF
[core]
workspace_base = "/home/openhands/workspace"
persist_sandbox = false
max_iterations = 100
[llm]
model = "gpt-4"
api_key = "your-api-key-here"
base_url = "$LLM_ENDPOINT/v1"
max_tokens = 4000
temperature = 0.1
[agent]
memory_enabled = true
max_chars = 30000
[security]
security_analyzer = "default"
allow_file_uploads = false
restrict_file_types = true
confirmation_mode = true
[server]
host = "0.0.0.0"
port = 3000
cors_allowed_origins = ["*"]
[sandbox]
runtime = "eventstream"
container_image = "ghcr.io/all-hands-ai/runtime:0.8-nikolaik"
timeout = 120
EOSU
# Create workspace directory with proper permissions
mkdir -p /home/openhands/workspace
chown -R openhands:openhands /home/openhands/workspace
chmod 755 /home/openhands/workspace
# Create startup script
cat > /home/openhands/start_openhands.sh << 'EOF'
#!/bin/bash
# OpenHands startup script
cd /home/openhands/OpenHands
source venv/bin/activate
# Check if API key is set
if [ -z "$OPENAI_API_KEY" ]; then
echo "============================================"
echo "ERROR: OPENAI_API_KEY environment variable not set"
echo "============================================"
echo "Please set your API key:"
echo "export OPENAI_API_KEY='your-actual-api-key-here'"
echo ""
echo "Then restart the service:"
echo "sudo systemctl restart openhands"
echo "============================================"
exit 1
fi
echo "Starting OpenHands server..."
echo "API Key configured: ${OPENAI_API_KEY:0:8}..."
echo "Server will be available on port 3000"
# Start OpenHands with proper logging
python -m openhands.server.listen \
--host 0.0.0.0 \
--port 3000 \
--file-store-path /home/openhands/workspace \
2>&1 | tee -a /var/log/openhands.log
EOF
chmod +x /home/openhands/start_openhands.sh
chown openhands:openhands /home/openhands/start_openhands.sh
# Create systemd service for OpenHands
cat > /etc/systemd/system/openhands.service << 'EOF'
[Unit]
Description=OpenHands AI Assistant
Documentation=https://github.com/All-Hands-AI/OpenHands
After=network.target docker.service
Requires=docker.service
Wants=network-online.target
[Service]
Type=simple
User=openhands
Group=openhands
WorkingDirectory=/home/openhands/OpenHands
Environment=OPENAI_API_KEY=your-api-key-here
Environment=PYTHONPATH=/home/openhands/OpenHands
ExecStart=/home/openhands/start_openhands.sh
ExecReload=/bin/kill -HUP $MAINPID
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=openhands
# Security settings
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=false
ReadWritePaths=/home/openhands
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
[Install]
WantedBy=multi-user.target
EOF
# Reload systemd
systemctl daemon-reload
# Create network restriction script
cat > /home/openhands/restrict_network.sh << 'EOF'
#!/bin/bash
# Network restriction script - allows only LLM endpoints
set -e
echo "Applying strict network restrictions..."
echo "This will block all outbound connections except to LLM endpoints"
# Function to resolve domain to IPs
resolve_domain() {
local domain=$1
dig +short "$domain" | grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' || true
}
# Clear existing OUTPUT rules
sudo iptables -F OUTPUT
sudo iptables -P OUTPUT DROP
# Allow loopback traffic
sudo iptables -A OUTPUT -o lo -j ACCEPT
# Allow established and related connections
sudo iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow DNS to VPC resolver only
sudo iptables -A OUTPUT -d 10.0.0.2 -p udp --dport 53 -j ACCEPT
# Allow NTP for time synchronization
sudo iptables -A OUTPUT -p udp --dport 123 -j ACCEPT
# Get and allow OpenAI endpoints
echo "Resolving OpenAI endpoints..."
OPENAI_DOMAINS=("api.openai.com" "openai.com" "cdn.openai.com")
for domain in "${OPENAI_DOMAINS[@]}"; do
IPS=$(resolve_domain "$domain")
for ip in $IPS; do
if [ ! -z "$ip" ]; then
sudo iptables -A OUTPUT -d "$ip" -p tcp --dport 443 -j ACCEPT
sudo iptables -A OUTPUT -d "$ip" -p tcp --dport 80 -j ACCEPT
echo "Allowed access to $domain ($ip)"
fi
done
done
# Get and allow Anthropic endpoints (Claude)
echo "Resolving Anthropic endpoints..."
ANTHROPIC_DOMAINS=("api.anthropic.com" "anthropic.com")
for domain in "${ANTHROPIC_DOMAINS[@]}"; do
IPS=$(resolve_domain "$domain")
for ip in $IPS; do
if [ ! -z "$ip" ]; then
sudo iptables -A OUTPUT -d "$ip" -p tcp --dport 443 -j ACCEPT
sudo iptables -A OUTPUT -d "$ip" -p tcp --dport 80 -j ACCEPT
echo "Allowed access to $domain ($ip)"
fi
done
done
# Allow other common LLM providers if needed
# Add more providers here as needed
# Save iptables rules
sudo iptables-save > /etc/iptables/rules.v4
echo "============================================"
echo "Network restrictions applied successfully!"
echo "============================================"
echo "Allowed connections:"
echo "- Loopback (127.0.0.1)"
echo "- DNS to VPC resolver (10.0.0.2:53)"
echo "- NTP (port 123)"
echo "- LLM endpoints (HTTPS/HTTP)"
echo ""
echo "All other outbound connections are BLOCKED"
echo "============================================"
# Test connectivity
echo "Testing connectivity..."
if curl -s --max-time 10 https://api.openai.com > /dev/null; then
echo "✓ OpenAI API accessible"
else
echo "✗ OpenAI API not accessible"
fi
if ! curl -s --max-time 5 https://google.com > /dev/null 2>&1; then
echo "✓ General internet access blocked (as expected)"
else
echo "✗ WARNING: General internet access not properly blocked"
fi
EOF
chmod +x /home/openhands/restrict_network.sh
chown openhands:openhands /home/openhands/restrict_network.sh
# Create monitoring script
cat > /home/openhands/monitor_openhands.sh << 'EOF'
#!/bin/bash
# OpenHands monitoring script
LOG_FILE="/var/log/openhands-monitor.log"
echo "=== $(date) ===" >> $LOG_FILE
# Check OpenHands service status
if systemctl is-active --quiet openhands; then
echo "OpenHands Service: RUNNING" >> $LOG_FILE
# Check if port 3000 is listening
if netstat -tlnp | grep -q ":3000"; then
echo "OpenHands Port 3000: LISTENING" >> $LOG_FILE
else
echo "OpenHands Port 3000: NOT LISTENING" >> $LOG_FILE
fi
else
echo "OpenHands Service: STOPPED" >> $LOG_FILE
fi
# Check Docker status
if systemctl is-active --quiet docker; then
echo "Docker: RUNNING" >> $LOG_FILE
else
echo "Docker: STOPPED - Attempting restart" >> $LOG_FILE
systemctl restart docker
fi
# Check disk space
DISK_USAGE=$(df -h /home/openhands | awk 'NR==2 {print $5}')
echo "Disk usage (/home/openhands): $DISK_USAGE" >> $LOG_FILE
# Check memory usage
MEM_USAGE=$(free | grep Mem | awk '{printf("%.1f%%", $3/$2 * 100.0)}')
echo "Memory usage: $MEM_USAGE" >> $LOG_FILE
# Check network restrictions
IPTABLES_RULES=$(sudo iptables -L OUTPUT | wc -l)
echo "Active iptables OUTPUT rules: $IPTABLES_RULES" >> $LOG_FILE
# Check recent logs for errors
ERROR_COUNT=$(journalctl -u openhands --since "15 minutes ago" | grep -i error | wc -l)
echo "Recent errors in OpenHands logs: $ERROR_COUNT" >> $LOG_FILE
echo "" >> $LOG_FILE
EOF
chmod +x /home/openhands/monitor_openhands.sh
chown openhands:openhands /home/openhands/monitor_openhands.sh
# Add monitoring to crontab for openhands user
sudo -u openhands bash -c 'echo "*/15 * * * * /home/openhands/monitor_openhands.sh" | crontab -'
# Configure SSH security
cat >> /etc/ssh/sshd_config << 'EOF'
# OpenHands Security Configuration
AllowUsers openhands ubuntu
PermitRootLogin no
PasswordAuthentication yes
PubkeyAuthentication yes
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
MaxSessions 2
Protocol 2
EOF
systemctl restart sshd
# Setup comprehensive logging
cat > /etc/rsyslog.d/50-openhands-audit.conf << 'EOF'
# OpenHands audit logging
auth,authpriv.* /var/log/openhands-audit.log
local0.* /var/log/openhands-app.log
EOF
systemctl restart rsyslog
# Configure log rotation
cat > /etc/logrotate.d/openhands << 'EOF'
/var/log/openhands*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 0644 openhands openhands
postrotate
systemctl reload rsyslog > /dev/null 2>&1 || true
endscript
}
EOF
# Install CloudWatch agent if in AWS
if command -v aws &> /dev/null; then
wget -q https://s3.amazonaws.com/amazoncloudwatch-agent/ubuntu/amd64/latest/amazon-cloudwatch-agent.deb
dpkg -i amazon-cloudwatch-agent.deb 2>/dev/null || true
rm -f amazon-cloudwatch-agent.deb
fi
# Create helpful aliases for the openhands user
sudo -u openhands bash -c 'cat >> /home/openhands/.bashrc << "EOF"
# OpenHands aliases and functions
alias oh-start="sudo systemctl start openhands"
alias oh-stop="sudo systemctl stop openhands"
alias oh-restart="sudo systemctl restart openhands"
alias oh-status="sudo systemctl status openhands"
alias oh-logs="sudo journalctl -u openhands -f"
alias oh-restrict="./restrict_network.sh"
alias oh-monitor="./monitor_openhands.sh"
# Function to set API key and restart service
oh-setkey() {
if [ -z "$1" ]; then
echo "Usage: oh-setkey <your-api-key>"
return 1
fi
export OPENAI_API_KEY="$1"
sudo sed -i "s/OPENAI_API_KEY=.*/OPENAI_API_KEY=$1/" /etc/systemd/system/openhands.service
sudo systemctl daemon-reload
sudo systemctl restart openhands
echo "API key updated and service restarted"
}
# Function to check OpenHands health
oh-health() {
echo "=== OpenHands Health Check ==="
echo "Service Status: $(systemctl is-active openhands)"
echo "Port 3000: $(netstat -tlnp | grep :3000 | wc -l) listeners"
echo "Memory Usage: $(free | grep Mem | awk '{printf("%.1f%%", $3/$2 * 100.0)}')"
echo "Disk Usage: $(df -h /home/openhands | awk 'NR==2 {print $5}')"
echo "Recent Errors: $(journalctl -u openhands --since '1 hour ago' | grep -i error | wc -l)"
echo "Network Rules: $(sudo iptables -L OUTPUT | wc -l) iptables rules"
}
echo "OpenHands shortcuts loaded!"
echo "Available commands: oh-start, oh-stop, oh-restart, oh-status, oh-logs"
echo " oh-restrict, oh-monitor, oh-setkey, oh-health"
EOF'
# Create comprehensive setup log
cat > /var/log/setup.log << EOF
=== OpenHands Server Setup Complete ===
Date: $(date)
Project: $PROJECT_NAME
LLM Endpoint: $LLM_ENDPOINT
User Account:
- Username: openhands
- Password: $OPENHANDS_PASSWORD
Service Management:
- Start: sudo systemctl start openhands
- Stop: sudo systemctl stop openhands
- Status: sudo systemctl status openhands
- Logs: sudo journalctl -u openhands -f
Configuration:
- Config file: /home/openhands/.openhands/config.toml
- Workspace: /home/openhands/workspace
- Service file: /etc/systemd/system/openhands.service
Network Security:
- Firewall: UFW enabled with restricted rules
- Network isolation: Run ./restrict_network.sh for LLM-only access
- Monitoring: ./monitor_openhands.sh
Setup Steps Required:
1. Set API key: export OPENAI_API_KEY='your-key-here'
2. Update service: sudo sed -i "s/your-api-key-here/\$OPENAI_API_KEY/" /etc/systemd/system/openhands.service
3. Reload daemon: sudo systemctl daemon-reload
4. Start service: sudo systemctl start openhands
5. Apply restrictions: ./restrict_network.sh
6. Enable service: sudo systemctl enable openhands
Access:
- Web interface will be available on port 3000
- Access via web proxy at https://<proxy-public-ip>
Logs:
- Application: /var/log/openhands.log
- System: journalctl -u openhands
- Audit: /var/log/openhands-audit.log
- Monitor: /var/log/openhands-monitor.log
EOF
chmod 600 /var/log/setup.log
# Final system hardening
# Disable unnecessary services
systemctl disable snapd 2>/dev/null || true
systemctl stop snapd 2>/dev/null || true
# Set up automatic security updates
apt-get install -y unattended-upgrades
echo 'Unattended-Upgrade::Automatic-Reboot "false";' >> /etc/apt/apt.conf.d/50unattended-upgrades
echo "============================================"
echo "OpenHands server setup completed successfully!"
echo "============================================"
echo "Next steps:"
echo "1. Set your API key: export OPENAI_API_KEY='your-key'"
echo "2. Update the systemd service with your API key"
echo "3. Start the OpenHands service"
echo "4. Apply network restrictions"
echo "5. Access via web proxy"
echo ""
echo "Check /var/log/setup.log for detailed information"
echo "============================================"