mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-06 04:14:15 +00:00
Introduce the sandbox MVP architecture separating panel credentials and
PostgreSQL access from model-controlled tool execution:
- Runner service (cmd/artex-runner, sandbox/) owning /var/run/docker.sock
behind bearer-token auth (ARTEX_RUNNER_TOKEN) with POST /v1/tasks/{id}/exec,
POST /v1/tasks/{id}/kill, DELETE /v1/tasks/{id}, and GET /v1/health.
- Strict input and env validation (400 on forbidden secret/DB/cloud env
patterns or values > 8192 bytes, strict task ID and /workspace workdir).
- Hardened per-task worker containers (Dockerfile.worker, artex-worker:local,
cmd/artex-exec-wrap): uid/gid 10001, artex-exec-wrap --init PID 1 zombie
reaper, read-only rootfs, cap-drop ALL, no-new-privileges, pids/mem/cpu
limits, tmpfs /tmp and /home/exec, only /app/data/tasks/<id>:/workspace:rw,
only verified internal=true runner-labeled network artex-task-<id>.
- Kernel-backed kill-switch (zero agent-writable state): Kill executes
artex-exec-wrap --kill-uid 10001 as uid 10001 scanning /proc directly
(defeating setsid, nohup, nested double-forked trap-TERM daemons, and /tmp
tampering), verifies zero non-PID-1 uid-10001 processes remain, and falls
back to force-removing the worker container if any check fails. Dead
workers/proxies are recreated automatically when startContainer fails.
- Operator-only scope approval (migration 0023_task_scope_operator_approval.sql):
adds task_scope.approved_by_operator BOOLEAN NOT NULL DEFAULT FALSE, set
true exclusively by operator API/UI (AddOperatorScope) and operator-selected
TaskCreateOptions.CompanyIDs (insertTaskCompanies). AddAgentScope and
AddAutoScope leave it false (coverage-only). taskSandboxRunInfo reads only
approved, non-expanded rows (and expands company scope only for approved
company rows); tasks with no approved scope deny all egress.
- Per-task egress proxy (cmd/artex-egress-proxy, Dockerfile.egress-proxy,
artex-egress-proxy:local): HTTP/HTTPS CONNECT (:3128) and SOCKS5 (:1080),
deny-by-default allowlist with strict domain suffix enforcement, blocks
RFC1918/loopback/link-local/IMDS and IPv6 unless in scope CIDRs, DNS
pinning, and tamper-proof JSONL audit logging to a proxy-only mount
(/app/data/egress-audit/<id>:/audit:rw) never mounted into the worker.
- Panel integration (agent/sandbox.go, agent/webfetch.go, server/sandbox.go,
server/sharedbrowser_guard.go, server/assembly.go, server/customtool.go,
docker-compose.sandbox.yml): ARTEX_SANDBOX defaults to required (fail closed,
no local fallback), WebFetch and opt-in shared browser inherit the
operator-approved sandbox.EgressPolicy (with target_gate or explicit proxy
required for shared browser), custom script tools staged via symlink-confined
workspace files (avoiding argv E2BIG), Pause/Stop/Delete wired to runner
Kill/Delete.
- Documented breaking change and hardening details in docs/SANDBOX.md,
README.md, and CHANGELOG.md.
304 lines
7.3 KiB
Go
304 lines
7.3 KiB
Go
package sandbox
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"encoding/binary"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/netip"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// EgressProxy serves both an HTTP/HTTPS CONNECT proxy and a SOCKS5 TCP proxy
|
|
// backed by the same EgressPolicy (allowlist + DNS pinning + JSONL audit log).
|
|
type EgressProxy struct {
|
|
Policy *EgressPolicy
|
|
httpServer *http.Server
|
|
httpLn net.Listener
|
|
socksLn net.Listener
|
|
}
|
|
|
|
// NewEgressProxy creates an EgressProxy bound to Policy.
|
|
func NewEgressProxy(policy *EgressPolicy) *EgressProxy {
|
|
ep := &EgressProxy{Policy: policy}
|
|
ep.httpServer = &http.Server{
|
|
Handler: ep,
|
|
ReadHeaderTimeout: 15 * time.Second,
|
|
}
|
|
return ep
|
|
}
|
|
|
|
// ServeHTTP handles both HTTP CONNECT tunnels and plain HTTP proxy requests.
|
|
func (p *EgressProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodConnect {
|
|
p.handleConnect(w, r)
|
|
return
|
|
}
|
|
p.handlePlainHTTP(w, r)
|
|
}
|
|
|
|
func splitHostPortDefault(raw string, defaultPort int) (string, int, error) {
|
|
if strings.Contains(raw, ":") {
|
|
h, ps, err := net.SplitHostPort(raw)
|
|
if err == nil {
|
|
port, perr := strconv.Atoi(ps)
|
|
if perr != nil {
|
|
return "", 0, perr
|
|
}
|
|
return h, port, nil
|
|
}
|
|
}
|
|
return strings.TrimPrefix(strings.TrimSuffix(raw, "]"), "["), defaultPort, nil
|
|
}
|
|
|
|
func (p *EgressProxy) handleConnect(w http.ResponseWriter, r *http.Request) {
|
|
host, port, err := splitHostPortDefault(r.Host, 443)
|
|
if err != nil {
|
|
http.Error(w, "bad CONNECT host", http.StatusBadRequest)
|
|
return
|
|
}
|
|
up, addr, err := p.Policy.DialPinned(r.Context(), host, port, "https-connect")
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusForbidden)
|
|
return
|
|
}
|
|
defer up.Close()
|
|
|
|
hj, ok := w.(http.Hijacker)
|
|
if !ok {
|
|
http.Error(w, "hijacking unsupported", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
clientConn, buf, err := hj.Hijack()
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer clientConn.Close()
|
|
|
|
_, _ = io.WriteString(clientConn, "HTTP/1.1 200 Connection Established\r\n\r\n")
|
|
n := relayBidirectional(clientConn, buf, up)
|
|
p.Policy.logDecision(host, port, addr.String(), "https-connect", "allow", n)
|
|
}
|
|
|
|
func (p *EgressProxy) handlePlainHTTP(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL == nil || r.URL.Host == "" {
|
|
http.Error(w, "absolute URL required for proxy", http.StatusBadRequest)
|
|
return
|
|
}
|
|
defaultPort := 80
|
|
if strings.EqualFold(r.URL.Scheme, "https") {
|
|
defaultPort = 443
|
|
}
|
|
host, port, err := splitHostPortDefault(r.URL.Host, defaultPort)
|
|
if err != nil {
|
|
http.Error(w, "bad target host", http.StatusBadRequest)
|
|
return
|
|
}
|
|
up, addr, err := p.Policy.DialPinned(r.Context(), host, port, "http")
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusForbidden)
|
|
return
|
|
}
|
|
defer up.Close()
|
|
|
|
outReq := r.Clone(r.Context())
|
|
outReq.RequestURI = ""
|
|
outReq.Header.Del("Proxy-Connection")
|
|
outReq.Header.Del("Proxy-Authorization")
|
|
|
|
tr := &http.Transport{
|
|
DialContext: func(context.Context, string, string) (net.Conn, error) {
|
|
return up, nil
|
|
},
|
|
DisableKeepAlives: true,
|
|
}
|
|
resp, err := tr.RoundTrip(outReq)
|
|
if err != nil {
|
|
p.Policy.logDecision(host, port, addr.String(), "http", "error", 0)
|
|
http.Error(w, err.Error(), http.StatusBadGateway)
|
|
return
|
|
}
|
|
defer resp.Body.Close()
|
|
for k, vals := range resp.Header {
|
|
for _, v := range vals {
|
|
w.Header().Add(k, v)
|
|
}
|
|
}
|
|
w.WriteHeader(resp.StatusCode)
|
|
n, _ := io.Copy(w, resp.Body)
|
|
p.Policy.logDecision(host, port, addr.String(), "http", "allow", n)
|
|
}
|
|
|
|
// ServeSOCKS5 accepts RFC 1928 SOCKS5 TCP CONNECT connections on ln using the same Policy.
|
|
func (p *EgressProxy) ServeSOCKS5(ctx context.Context, ln net.Listener) error {
|
|
p.socksLn = ln
|
|
for {
|
|
conn, err := ln.Accept()
|
|
if err != nil {
|
|
if ctx.Err() != nil || errors.Is(err, net.ErrClosed) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
go p.handleSOCKS5Conn(ctx, conn)
|
|
}
|
|
}
|
|
|
|
func (p *EgressProxy) handleSOCKS5Conn(ctx context.Context, c net.Conn) {
|
|
defer c.Close()
|
|
_ = c.SetDeadline(time.Now().Add(15 * time.Second))
|
|
br := bufio.NewReader(c)
|
|
|
|
// 1) Greeting: VER, NMETHODS, METHODS...
|
|
ver, err := br.ReadByte()
|
|
if err != nil || ver != 0x05 {
|
|
return
|
|
}
|
|
nMethods, err := br.ReadByte()
|
|
if err != nil {
|
|
return
|
|
}
|
|
methods := make([]byte, int(nMethods))
|
|
if _, err := io.ReadFull(br, methods); err != nil {
|
|
return
|
|
}
|
|
// Select NO AUTHENTICATION REQUIRED (0x00)
|
|
if _, err := c.Write([]byte{0x05, 0x00}); err != nil {
|
|
return
|
|
}
|
|
|
|
// 2) Request: VER, CMD, RSV, ATYP, DST.ADDR, DST.PORT
|
|
hdr := make([]byte, 4)
|
|
if _, err := io.ReadFull(br, hdr); err != nil || hdr[0] != 0x05 {
|
|
return
|
|
}
|
|
if hdr[1] != 0x01 { // Only CONNECT (0x01); refuse BIND / UDP ASSOCIATE
|
|
_, _ = c.Write([]byte{0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
|
return
|
|
}
|
|
var host string
|
|
switch hdr[3] {
|
|
case 0x01: // IPv4
|
|
buf := make([]byte, 4)
|
|
if _, err := io.ReadFull(br, buf); err != nil {
|
|
return
|
|
}
|
|
ip, _ := netip.AddrFromSlice(buf)
|
|
host = ip.String()
|
|
case 0x03: // Domain name
|
|
l, err := br.ReadByte()
|
|
if err != nil {
|
|
return
|
|
}
|
|
buf := make([]byte, int(l))
|
|
if _, err := io.ReadFull(br, buf); err != nil {
|
|
return
|
|
}
|
|
host = string(buf)
|
|
case 0x04: // IPv6
|
|
buf := make([]byte, 16)
|
|
if _, err := io.ReadFull(br, buf); err != nil {
|
|
return
|
|
}
|
|
ip, _ := netip.AddrFromSlice(buf)
|
|
host = ip.String()
|
|
default:
|
|
_, _ = c.Write([]byte{0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
|
return
|
|
}
|
|
portBuf := make([]byte, 2)
|
|
if _, err := io.ReadFull(br, portBuf); err != nil {
|
|
return
|
|
}
|
|
port := int(binary.BigEndian.Uint16(portBuf))
|
|
|
|
up, addr, err := p.Policy.DialPinned(ctx, host, port, "socks5")
|
|
if err != nil {
|
|
// 0x02 = connection not allowed by ruleset
|
|
_, _ = c.Write([]byte{0x05, 0x02, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
|
return
|
|
}
|
|
defer up.Close()
|
|
|
|
_ = c.SetDeadline(time.Time{})
|
|
_, _ = c.Write([]byte{0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
|
n := relayBidirectional(c, br, up)
|
|
p.Policy.logDecision(host, port, addr.String(), "socks5", "allow", n)
|
|
}
|
|
|
|
func relayBidirectional(client net.Conn, clientBuf io.Reader, upstream net.Conn) int64 {
|
|
var wg sync.WaitGroup
|
|
var c2u, u2c int64
|
|
wg.Add(2)
|
|
go func() {
|
|
defer wg.Done()
|
|
c2u, _ = io.Copy(upstream, clientBuf)
|
|
if tc, ok := upstream.(*net.TCPConn); ok {
|
|
_ = tc.CloseWrite()
|
|
}
|
|
}()
|
|
go func() {
|
|
defer wg.Done()
|
|
u2c, _ = io.Copy(client, upstream)
|
|
if tc, ok := client.(*net.TCPConn); ok {
|
|
_ = tc.CloseWrite()
|
|
}
|
|
}()
|
|
wg.Wait()
|
|
return c2u + u2c
|
|
}
|
|
|
|
// ListenAndServe starts both the HTTP proxy and SOCKS5 proxy until ctx is cancelled.
|
|
func (p *EgressProxy) ListenAndServe(ctx context.Context, httpAddr, socksAddr string) error {
|
|
hln, err := net.Listen("tcp", httpAddr)
|
|
if err != nil {
|
|
return fmt.Errorf("listen http proxy %s: %w", httpAddr, err)
|
|
}
|
|
p.httpLn = hln
|
|
errCh := make(chan error, 2)
|
|
go func() {
|
|
if err := p.httpServer.Serve(hln); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
errCh <- err
|
|
}
|
|
}()
|
|
if socksAddr != "" {
|
|
sln, err := net.Listen("tcp", socksAddr)
|
|
if err != nil {
|
|
_ = p.Close()
|
|
return fmt.Errorf("listen socks5 proxy %s: %w", socksAddr, err)
|
|
}
|
|
p.socksLn = sln
|
|
go func() {
|
|
if err := p.ServeSOCKS5(ctx, sln); err != nil {
|
|
errCh <- err
|
|
}
|
|
}()
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
_ = p.Close()
|
|
return nil
|
|
case err := <-errCh:
|
|
_ = p.Close()
|
|
return err
|
|
}
|
|
}
|
|
|
|
// Close shuts down both listeners.
|
|
func (p *EgressProxy) Close() error {
|
|
if p.httpServer != nil {
|
|
_ = p.httpServer.Close()
|
|
}
|
|
if p.socksLn != nil {
|
|
_ = p.socksLn.Close()
|
|
}
|
|
return nil
|
|
}
|