| 1 | // Elffuss Bridge — puente local para que Elffuss Code (el navegador) pueda |
| 2 | // ejecutar comandos REALES en tu máquina (node, npm, python…), sin salir de |
| 3 | // tu ordenador. Escucha SOLO en 127.0.0.1 y exige: |
| 4 | // 1) Origin permitido (code.elffuss.com, sus nombres anteriores o localhost |
| 5 | // de desarrollo) |
| 6 | // 2) cabecera Host de loopback (defensa extra contra DNS-rebinding) |
| 7 | // 3) un TOKEN de un solo arranque, que se imprime aquí y se pega en la web |
| 8 | // Sin las tres cosas, ninguna página puede conectarse ni ejecutar nada. |
| 9 | // |
| 10 | // Además, la ejecución está ACOTADA a una carpeta raíz (--root, por defecto el |
| 11 | // directorio desde el que arrancas el bridge): un comando no puede usar como |
| 12 | // cwd nada fuera de esa raíz. Esto NO es un sandbox — «sh -c» puede leer con |
| 13 | // ruta absoluta fuera de la raíz (p.ej. ~/.ssh) —, pero reduce el radio si el |
| 14 | // token se filtra, y evita el viejo comportamiento de correr en el temp global. |
| 15 | // Para aislamiento real, arranca el propio bridge en un contenedor o usuario |
| 16 | // restringido. --allow-any desactiva la restricción de raíz (no recomendado). |
| 17 | package main |
| 18 | |
| 19 | import ( |
| 20 | "crypto/rand" |
| 21 | "crypto/subtle" |
| 22 | "encoding/hex" |
| 23 | "flag" |
| 24 | "fmt" |
| 25 | "io" |
| 26 | "log" |
| 27 | "net" |
| 28 | "net/http" |
| 29 | "os" |
| 30 | "os/exec" |
| 31 | "os/signal" |
| 32 | "path/filepath" |
| 33 | "runtime" |
| 34 | "strings" |
| 35 | "sync" |
| 36 | "time" |
| 37 | |
| 38 | "github.com/gorilla/websocket" |
| 39 | ) |
| 40 | |
| 41 | const version = "1.1.2" |
| 42 | |
| 43 | // Tope de salida por comando: evita que un proceso que escupe sin fin inunde el |
| 44 | // WebSocket (DoS de memoria). Al superarlo se corta y se avisa. |
| 45 | const maxOutputBytes = 8 << 20 // 8 MiB |
| 46 | |
| 47 | // Orígenes EXACTOS, sin comodines: un sufijo como «*.utopiaia.com» dejaría |
| 48 | // conectarse a cualquier web de ese dominio, y esto ejecuta shell real. |
| 49 | // code.elffuss.com es el nombre actual. code.elffuss.utopiaia.com es el |
| 50 | // anterior y se sigue aceptando mientras dure el cambio de dominio; antes |
| 51 | // faltaba aquí, así que desde él la web cargaba pero el bridge la rechazaba. |
| 52 | // elffuss-code.utopiaia.com es el alias más antiguo, por compatibilidad. |
| 53 | var allowedOrigins = map[string]bool{ |
| 54 | "https://code.elffuss.com": true, |
| 55 | "https://code.elffuss.utopiaia.com": true, |
| 56 | "https://elffuss-code.utopiaia.com": true, |
| 57 | "http://localhost:8799": true, |
| 58 | "http://127.0.0.1:8799": true, |
| 59 | } |
| 60 | |
| 61 | func genToken() string { |
| 62 | b := make([]byte, 32) // 256 bits |
| 63 | if _, err := rand.Read(b); err != nil { |
| 64 | // Sin aleatoriedad segura NO se arranca: un token predecible es un |
| 65 | // agujero peor que no tener bridge. Antes esto devolvía un token fijo. |
| 66 | log.Fatal("no hay fuente de aleatoriedad segura; abortando para no exponer un token débil") |
| 67 | } |
| 68 | return hex.EncodeToString(b) |
| 69 | } |
| 70 | |
| 71 | // tokenEqual compara en tiempo constante: evita distinguir el token por el |
| 72 | // tiempo de respuesta (timing attack). Con «==» el corto-circuito filtra cuántos |
| 73 | // bytes iniciales aciertas. |
| 74 | func tokenEqual(a, b string) bool { |
| 75 | return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 |
| 76 | } |
| 77 | |
| 78 | // hostIsLoopback: la cabecera Host debe ser 127.0.0.1/localhost. Un ataque de |
| 79 | // DNS-rebinding llega con Host = dominio del atacante aunque resuelva a 127.0.0.1; |
| 80 | // esto lo rechaza además del Origin. |
| 81 | func hostIsLoopback(host string) bool { |
| 82 | h := host |
| 83 | if i := strings.LastIndex(h, ":"); i != -1 && !strings.Contains(h[i:], "]") { |
| 84 | h = h[:i] |
| 85 | } |
| 86 | h = strings.Trim(h, "[]") |
| 87 | if h == "localhost" { |
| 88 | return true |
| 89 | } |
| 90 | ip := net.ParseIP(h) |
| 91 | return ip != nil && ip.IsLoopback() |
| 92 | } |
| 93 | |
| 94 | // ---- mensajes del protocolo (JSON por el WebSocket) ---- |
| 95 | type inMsg struct { |
| 96 | Type string `json:"type"` // auth | exec | stop |
| 97 | Token string `json:"token,omitempty"` // auth |
| 98 | ID string `json:"id,omitempty"` // exec | stop |
| 99 | Cmd string `json:"cmd,omitempty"` // exec |
| 100 | Cwd string `json:"cwd,omitempty"` // exec (vacío → raíz) |
| 101 | } |
| 102 | type outMsg struct { |
| 103 | Type string `json:"type"` // auth-ok | auth-fail | stdout | stderr | exit | error |
| 104 | ID string `json:"id,omitempty"` |
| 105 | Data string `json:"data,omitempty"` |
| 106 | Code int `json:"code,omitempty"` |
| 107 | } |
| 108 | |
| 109 | type session struct { |
| 110 | conn *websocket.Conn |
| 111 | writeMu sync.Mutex |
| 112 | authed bool |
| 113 | root string // carpeta raíz permitida (absoluta), "" = sin restricción |
| 114 | procsMu sync.Mutex |
| 115 | procs map[string]*job |
| 116 | earlyStops map[string]bool // «stop» de un id que aún no había llegado |
| 117 | } |
| 118 | |
| 119 | // Un comando de la sesión. Se apunta en cuanto llega el «exec», ANTES de |
| 120 | // arrancar el proceso: antes solo se apuntaba tras Start(), en su goroutine, y |
| 121 | // un «stop» que llegaba en ese hueco no encontraba nada y se perdía. El cliente |
| 122 | // ya había dado el comando por parado y el comando corría hasta el final. |
| 123 | type job struct { |
| 124 | cmd *exec.Cmd // nil hasta que arranca |
| 125 | stopped bool // se pidió pararlo (antes o después de arrancar) |
| 126 | } |
| 127 | |
| 128 | // Máximo de «stop» adelantados que se recuerdan; solo protege la memoria. |
| 129 | const maxEarlyStops = 256 |
| 130 | |
| 131 | func (s *session) send(m outMsg) { |
| 132 | s.writeMu.Lock() |
| 133 | defer s.writeMu.Unlock() |
| 134 | _ = s.conn.WriteJSON(m) |
| 135 | } |
| 136 | |
| 137 | func shellFor(cmdline string) *exec.Cmd { |
| 138 | var c *exec.Cmd |
| 139 | if runtime.GOOS == "windows" { |
| 140 | c = exec.Command("cmd", "/C", cmdline) |
| 141 | } else { |
| 142 | c = exec.Command("sh", "-c", cmdline) |
| 143 | } |
| 144 | prepareTree(c) // su propio grupo de procesos, para poder matar el árbol entero |
| 145 | return c |
| 146 | } |
| 147 | |
| 148 | // resolveCwd valida el directorio de trabajo pedido contra la raíz permitida. |
| 149 | // Devuelve (dir, ""), o ("", motivo) si escapa de la raíz. |
| 150 | func (s *session) resolveCwd(reqCwd string) (string, string) { |
| 151 | if s.root == "" { |
| 152 | if reqCwd == "" { |
| 153 | return os.TempDir(), "" |
| 154 | } |
| 155 | return reqCwd, "" |
| 156 | } |
| 157 | dir := reqCwd |
| 158 | if dir == "" { |
| 159 | return s.root, "" |
| 160 | } |
| 161 | if !filepath.IsAbs(dir) { |
| 162 | dir = filepath.Join(s.root, dir) |
| 163 | } |
| 164 | abs, err := filepath.Abs(dir) |
| 165 | if err != nil { |
| 166 | return "", "cwd inválido" |
| 167 | } |
| 168 | rel, err := filepath.Rel(s.root, abs) |
| 169 | if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { |
| 170 | return "", "cwd fuera de la carpeta permitida (" + s.root + ")" |
| 171 | } |
| 172 | return abs, "" |
| 173 | } |
| 174 | |
| 175 | // Código de salida de un comando parado antes de arrancar: el mismo que da una |
| 176 | // shell con Ctrl+C (128 + SIGINT), el que el cliente ya usa para «parado». |
| 177 | const exitStopped = 130 |
| 178 | |
| 179 | // reserve apunta el comando en cuanto llega su «exec», en el mismo bucle de |
| 180 | // lectura que luego procesa su «stop»: así un «stop» siempre lo encuentra. |
| 181 | func (s *session) reserve(id string) { |
| 182 | s.procsMu.Lock() |
| 183 | defer s.procsMu.Unlock() |
| 184 | j := s.procs[id] |
| 185 | if j == nil { |
| 186 | j = &job{} |
| 187 | s.procs[id] = j |
| 188 | } |
| 189 | if s.earlyStops[id] { |
| 190 | j.stopped = true |
| 191 | delete(s.earlyStops, id) |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | func (s *session) forget(id string) { |
| 196 | s.procsMu.Lock() |
| 197 | delete(s.procs, id) |
| 198 | s.procsMu.Unlock() |
| 199 | } |
| 200 | |
| 201 | func (s *session) runExec(m inMsg) { |
| 202 | if strings.TrimSpace(m.Cmd) == "" { |
| 203 | s.forget(m.ID) |
| 204 | s.send(outMsg{Type: "error", ID: m.ID, Data: "comando vacío"}) |
| 205 | s.send(outMsg{Type: "exit", ID: m.ID, Code: -1}) |
| 206 | return |
| 207 | } |
| 208 | cwd, why := s.resolveCwd(strings.TrimSpace(m.Cwd)) |
| 209 | if why != "" { |
| 210 | s.forget(m.ID) |
| 211 | s.send(outMsg{Type: "error", ID: m.ID, Data: why}) |
| 212 | s.send(outMsg{Type: "exit", ID: m.ID, Code: -1}) |
| 213 | return |
| 214 | } |
| 215 | s.procsMu.Lock() |
| 216 | j := s.procs[m.ID] |
| 217 | if j == nil { // llamado sin reserve(): se apunta aquí |
| 218 | j = &job{} |
| 219 | s.procs[m.ID] = j |
| 220 | } |
| 221 | stoppedEarly := j.stopped |
| 222 | s.procsMu.Unlock() |
| 223 | if stoppedEarly { |
| 224 | // Parado antes de arrancar: no se arranca. |
| 225 | s.forget(m.ID) |
| 226 | s.send(outMsg{Type: "exit", ID: m.ID, Code: exitStopped}) |
| 227 | return |
| 228 | } |
| 229 | c := shellFor(m.Cmd) |
| 230 | c.Dir = cwd |
| 231 | stdout, err1 := c.StdoutPipe() |
| 232 | stderr, err2 := c.StderrPipe() |
| 233 | if err1 != nil || err2 != nil { |
| 234 | s.forget(m.ID) |
| 235 | s.send(outMsg{Type: "error", ID: m.ID, Data: "no pude preparar el proceso"}) |
| 236 | return |
| 237 | } |
| 238 | if err := c.Start(); err != nil { |
| 239 | s.forget(m.ID) |
| 240 | s.send(outMsg{Type: "error", ID: m.ID, Data: "no pude arrancar: " + err.Error()}) |
| 241 | return |
| 242 | } |
| 243 | s.procsMu.Lock() |
| 244 | j.cmd = c |
| 245 | stopNow := j.stopped // el «stop» llegó mientras arrancaba |
| 246 | s.procsMu.Unlock() |
| 247 | if stopNow { |
| 248 | killTree(c) |
| 249 | } |
| 250 | |
| 251 | var sent int64 |
| 252 | var sentMu sync.Mutex |
| 253 | capped := false |
| 254 | var wg sync.WaitGroup |
| 255 | wg.Add(2) |
| 256 | pump := func(r io.Reader, kind string) { |
| 257 | defer wg.Done() |
| 258 | buf := make([]byte, 4096) |
| 259 | for { |
| 260 | n, err := r.Read(buf) |
| 261 | if n > 0 { |
| 262 | sentMu.Lock() |
| 263 | if sent < maxOutputBytes { |
| 264 | s.send(outMsg{Type: kind, ID: m.ID, Data: string(buf[:n])}) |
| 265 | sent += int64(n) |
| 266 | if sent >= maxOutputBytes && !capped { |
| 267 | capped = true |
| 268 | s.send(outMsg{Type: "stderr", ID: m.ID, Data: "\n[bridge: salida cortada a 8 MiB — mata el proceso o filtra la salida]\n"}) |
| 269 | // matar el proceso para no seguir consumiendo la máquina |
| 270 | s.stop(m.ID) |
| 271 | } |
| 272 | } |
| 273 | sentMu.Unlock() |
| 274 | } |
| 275 | if err != nil { |
| 276 | return |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | go pump(stdout, "stdout") |
| 281 | go pump(stderr, "stderr") |
| 282 | wg.Wait() |
| 283 | |
| 284 | code := 0 |
| 285 | if err := c.Wait(); err != nil { |
| 286 | if ee, ok := err.(*exec.ExitError); ok { |
| 287 | code = ee.ExitCode() |
| 288 | } else { |
| 289 | code = -1 |
| 290 | } |
| 291 | } |
| 292 | s.forget(m.ID) |
| 293 | s.send(outMsg{Type: "exit", ID: m.ID, Code: code}) |
| 294 | } |
| 295 | |
| 296 | // stop mata el comando con TODO lo que haya lanzado. Antes mataba solo el |
| 297 | // «sh -c» que arranca el bridge: lo que ese sh hubiera lanzado (el node de un |
| 298 | // `npm run dev`, la segunda mitad de `a; b`, los hijos de `npm install`) seguía |
| 299 | // vivo, con su puerto, mientras la web lo daba por parado. |
| 300 | func (s *session) stop(id string) { |
| 301 | s.procsMu.Lock() |
| 302 | j := s.procs[id] |
| 303 | if j == nil { |
| 304 | // Aún no había llegado su «exec»: se recuerda para cuando llegue. |
| 305 | if len(s.earlyStops) < maxEarlyStops { |
| 306 | s.earlyStops[id] = true |
| 307 | } |
| 308 | s.procsMu.Unlock() |
| 309 | return |
| 310 | } |
| 311 | j.stopped = true |
| 312 | c := j.cmd |
| 313 | s.procsMu.Unlock() |
| 314 | if c != nil { |
| 315 | killTree(c) |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | // stopAll mata todo lo de la sesión: al cerrarse el socket ya no queda nadie |
| 320 | // para pararlo, y el cliente ya lo ha dado por terminado («[bridge |
| 321 | // desconectado]»). Antes seguía corriendo. |
| 322 | func (s *session) stopAll() { |
| 323 | for _, c := range s.running(true) { |
| 324 | killTree(c) |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | // running devuelve los procesos arrancados de la sesión (y los marca parados |
| 329 | // si se pide). |
| 330 | func (s *session) running(markStopped bool) []*exec.Cmd { |
| 331 | s.procsMu.Lock() |
| 332 | defer s.procsMu.Unlock() |
| 333 | var cmds []*exec.Cmd |
| 334 | for _, j := range s.procs { |
| 335 | if markStopped { |
| 336 | j.stopped = true |
| 337 | } |
| 338 | if j.cmd != nil { |
| 339 | cmds = append(cmds, j.cmd) |
| 340 | } |
| 341 | } |
| 342 | return cmds |
| 343 | } |
| 344 | |
| 345 | // Las sesiones abiertas, para pararlo todo cuando se cierra el bridge. |
| 346 | var ( |
| 347 | sessionsMu sync.Mutex |
| 348 | sessions = map[*session]bool{} |
| 349 | ) |
| 350 | |
| 351 | // stopOnShutdown: cada comando corre en su propio grupo de procesos, así que el |
| 352 | // Ctrl+C de la ventana del bridge ya no les llega (antes compartían el grupo |
| 353 | // del bridge y caían con él). Al recibir la señal de cierre el bridge para |
| 354 | // todos los comandos, les da el margen para terminar por las buenas, remata lo |
| 355 | // que quede y sale. |
| 356 | func stopOnShutdown() { |
| 357 | sigs := make(chan os.Signal, 1) |
| 358 | signal.Notify(sigs, shutdownSignals...) |
| 359 | go func() { |
| 360 | <-sigs |
| 361 | sessionsMu.Lock() |
| 362 | var all []*session |
| 363 | for s := range sessions { |
| 364 | all = append(all, s) |
| 365 | } |
| 366 | sessionsMu.Unlock() |
| 367 | for _, s := range all { |
| 368 | s.stopAll() |
| 369 | } |
| 370 | quedan := func() bool { |
| 371 | for _, s := range all { |
| 372 | if len(s.running(false)) > 0 { |
| 373 | return true |
| 374 | } |
| 375 | } |
| 376 | return false |
| 377 | } |
| 378 | for limite := time.Now().Add(killGrace); quedan() && time.Now().Before(limite); { |
| 379 | time.Sleep(50 * time.Millisecond) |
| 380 | } |
| 381 | for _, s := range all { |
| 382 | for _, c := range s.running(false) { |
| 383 | forceKill(c) |
| 384 | } |
| 385 | } |
| 386 | os.Exit(130) |
| 387 | }() |
| 388 | } |
| 389 | |
| 390 | func serveWS(token, root string) http.HandlerFunc { |
| 391 | upgrader := websocket.Upgrader{ |
| 392 | CheckOrigin: func(r *http.Request) bool { |
| 393 | // Origin permitido Y Host de loopback: dos gates independientes. |
| 394 | return allowedOrigins[r.Header.Get("Origin")] && hostIsLoopback(r.Host) |
| 395 | }, |
| 396 | } |
| 397 | return func(w http.ResponseWriter, r *http.Request) { |
| 398 | conn, err := upgrader.Upgrade(w, r, nil) |
| 399 | if err != nil { |
| 400 | log.Println("conexión rechazada (origen/host no permitido u otro error):", err) |
| 401 | return |
| 402 | } |
| 403 | defer conn.Close() |
| 404 | s := &session{conn: conn, procs: map[string]*job{}, earlyStops: map[string]bool{}, root: root} |
| 405 | sessionsMu.Lock() |
| 406 | sessions[s] = true |
| 407 | sessionsMu.Unlock() |
| 408 | defer func() { |
| 409 | s.stopAll() |
| 410 | sessionsMu.Lock() |
| 411 | delete(sessions, s) |
| 412 | sessionsMu.Unlock() |
| 413 | }() |
| 414 | log.Println("nueva conexión desde", r.RemoteAddr, "origin:", r.Header.Get("Origin")) |
| 415 | attempts := 0 |
| 416 | for { |
| 417 | var m inMsg |
| 418 | if err := conn.ReadJSON(&m); err != nil { |
| 419 | break |
| 420 | } |
| 421 | switch m.Type { |
| 422 | case "auth": |
| 423 | if tokenEqual(m.Token, token) { |
| 424 | s.authed = true |
| 425 | s.send(outMsg{Type: "auth-ok"}) |
| 426 | log.Println("✔ autenticado") |
| 427 | } else { |
| 428 | attempts++ |
| 429 | s.send(outMsg{Type: "auth-fail"}) |
| 430 | log.Println("✕ token incorrecto — conexión rechazada") |
| 431 | conn.Close() |
| 432 | return |
| 433 | } |
| 434 | case "exec": |
| 435 | if !s.authed { |
| 436 | s.send(outMsg{Type: "error", ID: m.ID, Data: "no autenticado"}) |
| 437 | continue |
| 438 | } |
| 439 | s.reserve(m.ID) |
| 440 | go s.runExec(m) |
| 441 | case "stop": |
| 442 | if s.authed { |
| 443 | s.stop(m.ID) |
| 444 | } |
| 445 | } |
| 446 | _ = attempts |
| 447 | } |
| 448 | log.Println("conexión cerrada") |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | func main() { |
| 453 | port := flag.Int("port", 8765, "puerto local (solo 127.0.0.1)") |
| 454 | tokenFlag := flag.String("token", "", "token fijo (por defecto se genera uno de 256 bits)") |
| 455 | rootFlag := flag.String("root", "", "carpeta raíz a la que se acota la ejecución (por defecto: el directorio actual)") |
| 456 | allowAny := flag.Bool("allow-any", false, "PELIGRO: permite ejecutar en cualquier carpeta (desactiva la restricción de raíz)") |
| 457 | flag.Parse() |
| 458 | |
| 459 | token := *tokenFlag |
| 460 | if token == "" { |
| 461 | token = genToken() |
| 462 | } else if len(token) < 24 { |
| 463 | log.Fatal("el --token fijo es demasiado corto; usa al menos 24 caracteres o deja que se genere uno") |
| 464 | } |
| 465 | |
| 466 | root := "" |
| 467 | if !*allowAny { |
| 468 | root = *rootFlag |
| 469 | if root == "" { |
| 470 | wd, err := os.Getwd() |
| 471 | if err != nil { |
| 472 | log.Fatal("no pude determinar el directorio actual para --root; pásalo explícitamente") |
| 473 | } |
| 474 | root = wd |
| 475 | } |
| 476 | if abs, err := filepath.Abs(root); err == nil { |
| 477 | root = abs |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | fmt.Println("🧝 Elffuss Bridge", version, "—", runtime.GOOS+"/"+runtime.GOARCH) |
| 482 | fmt.Println(" Escuchando SOLO en 127.0.0.1:" + fmt.Sprint(*port) + " (nada sale de tu máquina)") |
| 483 | if root != "" { |
| 484 | fmt.Println(" Ejecución acotada a:", root) |
| 485 | } else { |
| 486 | fmt.Println(" ⚠ --allow-any: la ejecución NO está acotada a ninguna carpeta") |
| 487 | } |
| 488 | fmt.Println() |
| 489 | fmt.Println(" TOKEN (pégalo en Elffuss Code → 🔌 Bridge local):") |
| 490 | fmt.Println(" " + token) |
| 491 | fmt.Println() |
| 492 | fmt.Println(" Ctrl+C para parar. Deja esta ventana abierta mientras lo uses.") |
| 493 | |
| 494 | stopOnShutdown() |
| 495 | |
| 496 | mux := http.NewServeMux() |
| 497 | mux.HandleFunc("/ws", serveWS(token, root)) |
| 498 | mux.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) { |
| 499 | // sondeo ligero SIN token, solo para que la web sepa «hay un bridge aquí». |
| 500 | // Respeta Origin permitido Y Host de loopback, igual que /ws. |
| 501 | if !allowedOrigins[r.Header.Get("Origin")] || !hostIsLoopback(r.Host) { |
| 502 | w.WriteHeader(http.StatusForbidden) |
| 503 | return |
| 504 | } |
| 505 | w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin")) |
| 506 | w.Header().Set("Vary", "Origin") |
| 507 | _, _ = w.Write([]byte(`{"ok":true,"version":"` + version + `"}`)) |
| 508 | }) |
| 509 | |
| 510 | addr := "127.0.0.1:" + fmt.Sprint(*port) |
| 511 | log.Fatal(http.ListenAndServe(addr, mux)) |
| 512 | } |