Bläddra i källkod

fix(httpapi): sanitize DHCP reservation hostname before uci/SSH (#693) (#697)

Validate the reservation hostname as a DNS name (letters, digits,
hyphens, dots, max 253 chars) and reject anything else with 400
invalid_hostname; quote every dynamic value interpolated into uci
commands (uciSetCmd escapes single quotes), including rollbacks that
re-read values from the router; send the hostname from the UI only
when the device name is a valid DNS hostname.

Co-authored-by: gnacho <hnacho@proton.me>
Nacho 2 månader sedan
förälder
incheckning
bbf2b01b3f

+ 6 - 0
CHANGELOG.md

@@ -5,6 +5,12 @@ Todos los cambios notables de NetPulse se documentan en este fichero.
 El formato se basa en [Keep a Changelog](https://keepachangelog.com/es/1.1.0/),
 El formato se basa en [Keep a Changelog](https://keepachangelog.com/es/1.1.0/),
 y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/).
 y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/).
 
 
+## [Unreleased]
+
+### Fixed
+
+- **El hostname de las reservas DHCP se valida y se escapa (#693)**: el `hostname` del endpoint `PUT /api/devices/{mac}/reservation` se interpolaba sin sanitizar en el comando `uci set` que corre por SSH como root en el router; una comilla simple rompía el quoting e inyectaba comandos arbitrarios. Ahora solo se aceptan hostnames DNS (letras, dígitos, guiones y puntos, hasta 253 caracteres; el resto recibe 400 `invalid_hostname`) y todos los valores interpolados en comandos uci -incluidos los rollbacks que re-leen config del router- viajan escapados. La UI manda el hostname solo cuando el nombre del dispositivo es un hostname DNS válido.
+
 ## [2.28.21] - 2026-09-10
 ## [2.28.21] - 2026-09-10
 
 
 ### Fixed
 ### Fixed

+ 7 - 1
app/src/components/DeviceEditSheet.tsx

@@ -11,6 +11,12 @@ import {
 import { cn, fetchJson } from '@/lib/utils'
 import { cn, fetchJson } from '@/lib/utils'
 import type { ClientDevice } from '@/pages/devices-data'
 import type { ClientDevice } from '@/pages/devices-data'
 
 
+// #693: el server solo acepta hostnames DNS en la reserva DHCP. Un nombre
+// visible libre ("TV Salón") viaja vacío y la reserva usa la MAC como name.
+const DNS_HOSTNAME_RE = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
+const asDhcpHostname = (name: string) =>
+  name.length > 0 && name.length <= 253 && DNS_HOSTNAME_RE.test(name) ? name : ''
+
 export interface DeviceEditSheetProps {
 export interface DeviceEditSheetProps {
   open: boolean
   open: boolean
   device: ClientDevice | null
   device: ClientDevice | null
@@ -196,7 +202,7 @@ export function DeviceEditSheet({
                     const res = await fetchJson(`/api/devices/${encodeURIComponent(device.mac)}/reservation`, {
                     const res = await fetchJson(`/api/devices/${encodeURIComponent(device.mac)}/reservation`, {
                       method: 'PUT',
                       method: 'PUT',
                       headers: { 'Content-Type': 'application/json' },
                       headers: { 'Content-Type': 'application/json' },
-                      body: JSON.stringify({ ip: reserveDraft, hostname: device.name }),
+                      body: JSON.stringify({ ip: reserveDraft, hostname: asDhcpHostname(device.name) }),
                     })
                     })
                     if (res.ok) {
                     if (res.ok) {
                       setReservation({ reserved: true, ip: reserveDraft, loading: false })
                       setReservation({ reserved: true, ip: reserveDraft, loading: false })

+ 53 - 14
server-go/internal/httpapi/device_actions.go

@@ -27,6 +27,12 @@ const (
 var reUciLine = regexp.MustCompile(`^([a-z0-9_]+)\.([^=]+)=(.*)$`)
 var reUciLine = regexp.MustCompile(`^([a-z0-9_]+)\.([^=]+)=(.*)$`)
 var reUciQuoted = regexp.MustCompile(`^'(.*)'$`)
 var reUciQuoted = regexp.MustCompile(`^'(.*)'$`)
 
 
+// reDhcpHostname: hostname DNS (etiquetas alfanuméricas con guiones internos,
+// separadas por puntos). dnsmasq registra el `name` de la sección host en su
+// DNS local, así que cualquier otra cosa (espacios, acentos, metacaracteres)
+// no es un hostname válido y se rechaza (#693).
+var reDhcpHostname = regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`)
+
 // uciValue devuelve el valor sin comillas de una línea `cfg.sect.opt='val'`.
 // uciValue devuelve el valor sin comillas de una línea `cfg.sect.opt='val'`.
 func uciValue(raw string) string {
 func uciValue(raw string) string {
 	if m := reUciQuoted.FindStringSubmatch(raw); m != nil {
 	if m := reUciQuoted.FindStringSubmatch(raw); m != nil {
@@ -35,6 +41,34 @@ func uciValue(raw string) string {
 	return raw
 	return raw
 }
 }
 
 
+// uciQuote escapa v para incrustarlo sin riesgo entre comillas simples de un
+// comando uci: la única forma de salir de '...' es otra comilla simple, que se
+// neutraliza cerrando, escapándola con backslash y reabriendo (secuencia
+// POSIX clásica de cierre-escape-apertura). Sin esto, un hostname tipo
+// `x'; cmd; echo '` inyecta comandos que corren como root en el router vía
+// SSH (#693).
+func uciQuote(v string) string {
+	return strings.ReplaceAll(v, "'", `'\''`)
+}
+
+// uciSetCmd construye `uci set <cfg>.<sect>.<opt>='<valor escapado>'`. Todo
+// valor dinámico de un comando uci pasa por aquí (#693).
+func uciSetCmd(cfg, sect, opt, value string) string {
+	return fmt.Sprintf("uci set %s.%s.%s='%s'", cfg, sect, opt, uciQuote(value))
+}
+
+// validDHCPHostname acepta vacío (= no tocar el name; el alta usará la MAC) o
+// un hostname DNS de hasta 253 caracteres (#693).
+func validDHCPHostname(h string) bool {
+	if h == "" {
+		return true
+	}
+	if len(h) > 253 {
+		return false
+	}
+	return reDhcpHostname.MatchString(h)
+}
+
 // gatewayHost devuelve el host SSH del gateway (router con is_gateway), o ""
 // gatewayHost devuelve el host SSH del gateway (router con is_gateway), o ""
 // si no hay gateway configurado o es agent-only. El gateway es quien sirve
 // si no hay gateway configurado o es agent-only. El gateway es quien sirve
 // DHCP (dnsmasq), así que es el target por defecto de las reservas de lease.
 // DHCP (dnsmasq), así que es el target por defecto de las reservas de lease.
@@ -251,6 +285,11 @@ func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Reque
 		writeError(w, http.StatusBadRequest, "invalid_ip")
 		writeError(w, http.StatusBadRequest, "invalid_ip")
 		return
 		return
 	}
 	}
+	if !validDHCPHostname(body.Hostname) {
+		writeError(w, http.StatusBadRequest, "invalid_hostname",
+			"el hostname debe ser un nombre DNS válido (letras, dígitos, guiones y puntos)")
+		return
+	}
 	host := s.reservationTargetHost(mac)
 	host := s.reservationTargetHost(mac)
 	if host == "" {
 	if host == "" {
 		writeError(w, http.StatusBadRequest, "no_gateway")
 		writeError(w, http.StatusBadRequest, "no_gateway")
@@ -280,11 +319,11 @@ func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Reque
 	var apply, rollback []string
 	var apply, rollback []string
 	if existing != nil {
 	if existing != nil {
 		oldIP := existing.IP
 		oldIP := existing.IP
-		apply = append(apply, fmt.Sprintf("uci set dhcp.%s.ip='%s'", existing.Section, body.IP))
+		apply = append(apply, uciSetCmd("dhcp", existing.Section, "ip", body.IP))
 		if body.Hostname != "" && body.Hostname != existing.Name {
 		if body.Hostname != "" && body.Hostname != existing.Name {
-			apply = append(apply, fmt.Sprintf("uci set dhcp.%s.name='%s'", existing.Section, body.Hostname))
+			apply = append(apply, uciSetCmd("dhcp", existing.Section, "name", body.Hostname))
 		}
 		}
-		rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s.ip='%s'", existing.Section, oldIP))
+		rollback = append(rollback, uciSetCmd("dhcp", existing.Section, "ip", oldIP))
 	} else {
 	} else {
 		section := dhcpHostSection(mac)
 		section := dhcpHostSection(mac)
 		name := body.Hostname
 		name := body.Hostname
@@ -293,9 +332,9 @@ func (s *server) handleDeviceReservationPut(w http.ResponseWriter, r *http.Reque
 		}
 		}
 		apply = append(apply,
 		apply = append(apply,
 			fmt.Sprintf("uci set dhcp.%s=host", section),
 			fmt.Sprintf("uci set dhcp.%s=host", section),
-			fmt.Sprintf("uci set dhcp.%s.name='%s'", section, name),
-			fmt.Sprintf("uci set dhcp.%s.mac='%s'", section, mac),
-			fmt.Sprintf("uci set dhcp.%s.ip='%s'", section, body.IP),
+			uciSetCmd("dhcp", section, "name", name),
+			uciSetCmd("dhcp", section, "mac", mac),
+			uciSetCmd("dhcp", section, "ip", body.IP),
 		)
 		)
 		rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
 		rollback = append(rollback, fmt.Sprintf("uci delete dhcp.%s", section))
 	}
 	}
@@ -342,13 +381,13 @@ func (s *server) handleDeviceReservationDelete(w http.ResponseWriter, r *http.Re
 	var rollback []string
 	var rollback []string
 	rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s=host", h.Section))
 	rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s=host", h.Section))
 	if h.Name != "" {
 	if h.Name != "" {
-		rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s.name='%s'", h.Section, h.Name))
+		rollback = append(rollback, uciSetCmd("dhcp", h.Section, "name", h.Name))
 	}
 	}
 	if h.MAC != "" {
 	if h.MAC != "" {
-		rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s.mac='%s'", h.Section, h.MAC))
+		rollback = append(rollback, uciSetCmd("dhcp", h.Section, "mac", h.MAC))
 	}
 	}
 	if h.IP != "" {
 	if h.IP != "" {
-		rollback = append(rollback, fmt.Sprintf("uci set dhcp.%s.ip='%s'", h.Section, h.IP))
+		rollback = append(rollback, uciSetCmd("dhcp", h.Section, "ip", h.IP))
 	}
 	}
 
 
 	apply := []string{fmt.Sprintf("uci delete dhcp.%s", h.Section)}
 	apply := []string{fmt.Sprintf("uci delete dhcp.%s", h.Section)}
@@ -451,11 +490,11 @@ func findBlockRule(rules []*firewallRule, mac string) *firewallRule {
 func blockRuleApply(section, mac string) []string {
 func blockRuleApply(section, mac string) []string {
 	return []string{
 	return []string{
 		fmt.Sprintf("uci set firewall.%s=rule", section),
 		fmt.Sprintf("uci set firewall.%s=rule", section),
-		fmt.Sprintf("uci set firewall.%s.name='%s'", section, blockRuleName(mac)),
+		uciSetCmd("firewall", section, "name", blockRuleName(mac)),
 		fmt.Sprintf("uci set firewall.%s.src='lan'", section),
 		fmt.Sprintf("uci set firewall.%s.src='lan'", section),
 		fmt.Sprintf("uci set firewall.%s.dest='*'", section),
 		fmt.Sprintf("uci set firewall.%s.dest='*'", section),
 		fmt.Sprintf("uci set firewall.%s.target='DROP'", section),
 		fmt.Sprintf("uci set firewall.%s.target='DROP'", section),
-		fmt.Sprintf("uci set firewall.%s.src_mac='%s'", section, mac),
+		uciSetCmd("firewall", section, "src_mac", mac),
 	}
 	}
 }
 }
 
 
@@ -575,13 +614,13 @@ func (s *server) handleDeviceBlockDelete(w http.ResponseWriter, r *http.Request)
 	apply := []string{fmt.Sprintf("uci delete firewall.%s", br.Section)}
 	apply := []string{fmt.Sprintf("uci delete firewall.%s", br.Section)}
 	rollback := []string{fmt.Sprintf("uci set firewall.%s=rule", br.Section)}
 	rollback := []string{fmt.Sprintf("uci set firewall.%s=rule", br.Section)}
 	if br.Name != "" {
 	if br.Name != "" {
-		rollback = append(rollback, fmt.Sprintf("uci set firewall.%s.name='%s'", br.Section, br.Name))
+		rollback = append(rollback, uciSetCmd("firewall", br.Section, "name", br.Name))
 	}
 	}
 	if br.SrcMAC != "" {
 	if br.SrcMAC != "" {
-		rollback = append(rollback, fmt.Sprintf("uci set firewall.%s.src_mac='%s'", br.Section, br.SrcMAC))
+		rollback = append(rollback, uciSetCmd("firewall", br.Section, "src_mac", br.SrcMAC))
 	}
 	}
 	if br.Target != "" {
 	if br.Target != "" {
-		rollback = append(rollback, fmt.Sprintf("uci set firewall.%s.target='%s'", br.Section, br.Target))
+		rollback = append(rollback, uciSetCmd("firewall", br.Section, "target", br.Target))
 	}
 	}
 	if err := s.runUCICommands(host, "firewall", apply); err != nil {
 	if err := s.runUCICommands(host, "firewall", apply); err != nil {
 		writeError(w, http.StatusInternalServerError, "apply_error", err.Error())
 		writeError(w, http.StatusInternalServerError, "apply_error", err.Error())

+ 73 - 0
server-go/internal/httpapi/device_actions_internal_test.go

@@ -0,0 +1,73 @@
+// device_actions_internal_test.go — unitarias de los helpers de sanitización
+// uci de device_actions.go (#693): escapado de comillas simples y validación
+// de hostname DNS.
+package httpapi
+
+import (
+	"strings"
+	"testing"
+)
+
+func TestUciQuoteEscapesSingleQuote(t *testing.T) {
+	cases := []struct{ in, want string }{
+		{"tv-salon", "tv-salon"},
+		{"", ""},
+		{"a'b", `a'\''b`},
+		{`x'; reboot; echo '`, `x'\''; reboot; echo '\''`},
+		{"it''s", `it'\'''\''s`},
+	}
+	for _, c := range cases {
+		if got := uciQuote(c.in); got != c.want {
+			t.Errorf("uciQuote(%q) = %q, want %q", c.in, got, c.want)
+		}
+	}
+}
+
+func TestUciSetCmdQuotesValue(t *testing.T) {
+	got := uciSetCmd("dhcp", "np_host_x", "name", "a'b")
+	want := `uci set dhcp.np_host_x.name='a'\''b'`
+	if got != want {
+		t.Errorf("uciSetCmd = %q, want %q", got, want)
+	}
+	// El payload del issue queda inerte: cada comilla simple del valor viaja
+	// como secuencia de escape, nunca como cierre del quoting.
+	raw := uciSetCmd("firewall", "np_block_x", "name", `x'; id; echo '`)
+	wantRaw := `uci set firewall.np_block_x.name='x'\''; id; echo '\'''`
+	if raw != wantRaw {
+		t.Errorf("uciSetCmd con payload hostil = %q, want %q", raw, wantRaw)
+	}
+}
+
+func TestValidDHCPHostname(t *testing.T) {
+	valid := []string{
+		"",            // vacío = no tocar el name
+		"tv-salon",    // clásico
+		"a",           // mínimo
+		"nas.lan",     // multi-etiqueta
+		"n-a-s.l-a-n", // etiquetas con guiones internos
+		strings.Repeat("a", 63) + "." + strings.Repeat("b", 63) + "." + strings.Repeat("c", 63) + "." + strings.Repeat("d", 61), // 253 justo
+	}
+	for _, h := range valid {
+		if !validDHCPHostname(h) {
+			t.Errorf("validDHCPHostname(%q) = false, want true", h)
+		}
+	}
+	invalid := []string{
+		"x'; touch /tmp/poc; echo '", // PoC del issue #693
+		"tv salon",                   // espacio
+		"x$(id)",                     // sustitución
+		"x`id`",                      // backticks
+		"pc_1",                       // underscore (no es DNS)
+		"-lead",                      // guion inicial
+		"trail-",                     // guion final
+		"a..b",                       // etiqueta vacía
+		".a",                         // empieza en punto
+		"télé",                       // acento
+		strings.Repeat("a", 254),     // demasiado largo
+	}
+	for _, h := range invalid {
+		if validDHCPHostname(h) {
+			t.Errorf("validDHCPHostname(%q) = true, want false", h)
+		}
+	}
+}

+ 87 - 0
server-go/internal/httpapi/device_actions_test.go

@@ -75,6 +75,15 @@ func (f *scriptedSSH) saw(substr string) bool {
 	return false
 	return false
 }
 }
 
 
+// cmdsSnapshot copia los comandos vistos (para mensajes de fallo).
+func (f *scriptedSSH) cmdsSnapshot() []string {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	out := make([]string, len(f.cmds))
+	copy(out, f.cmds)
+	return out
+}
+
 // sawHost es como saw pero acotado a un host SSH concreto (issue #537: la
 // sawHost es como saw pero acotado a un host SSH concreto (issue #537: la
 // reserva debe escribirse en el router que sirve DHCP, no siempre en el
 // reserva debe escribirse en el router que sirve DHCP, no siempre en el
 // gateway).
 // gateway).
@@ -599,6 +608,84 @@ func TestReservationInvalidIP(t *testing.T) {
 	}
 	}
 }
 }
 
 
+// --- #693: hostname de la reserva sin superficie de inyección ---
+
+// El PoC del issue (hostname con comilla simple que rompe el quoting del
+// comando uci) debe rechazarse con 400 SIN llegar a abrir sesión SSH.
+func TestReservationHostnameInjectionRejected(t *testing.T) {
+	ssh := newSSH(dhcpEmpty, fwEmpty)
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
+		`{"ip":"192.168.1.60","hostname":"x'; touch /tmp/netpulse_poc; echo '"}`)
+	if res.StatusCode != 400 {
+		t.Fatalf("hostname inyectable: got %d want 400 (body %v)", res.StatusCode, decodeBody(t, res))
+	}
+	body := decodeBody(t, res)
+	if body["error"] != "invalid_hostname" {
+		t.Errorf("error code: %v", body["error"])
+	}
+	if ssh.saw("uci") || ssh.saw("touch") {
+		t.Error("el payload malicioso no debe generar NINGÚN comando SSH")
+	}
+}
+
+// Hostnames válidos (DNS) pasan; el resto (espacios, sustituciones, unicode)
+// se rechaza con 400 invalid_hostname.
+func TestReservationHostnameValidation(t *testing.T) {
+	ssh := newSSH(dhcpEmpty, fwEmpty)
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	valid := []string{"tv-salon", "nas.lan", "a"}
+	for _, h := range valid {
+		res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
+			`{"ip":"192.168.1.60","hostname":"`+h+`"}`)
+		if res.StatusCode != 200 {
+			t.Errorf("hostname válido %q: got %d want 200 (body %v)", h, res.StatusCode, decodeBody(t, res))
+		}
+		res.Body.Close()
+	}
+
+	invalid := []string{"tv salon", "x$(id)", "x`id`", "pc_1", "télé"}
+	for _, h := range invalid {
+		res := deviceReq(t, "PUT", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie,
+			`{"ip":"192.168.1.60","hostname":"`+h+`"}`)
+		if res.StatusCode != 400 {
+			t.Errorf("hostname inválido %q: got %d want 400", h, res.StatusCode)
+		}
+		body := decodeBody(t, res)
+		if body["error"] != "invalid_hostname" {
+			t.Errorf("hostname inválido %q: error code %v", h, body["error"])
+		}
+	}
+}
+
+// Defensa en profundidad: el rollback del DELETE re-interpola valores LEÍDOS
+// del router (name de la sección host). Si el router devolviera un name hostil,
+// el comando de rollback debe llevarlo escapado, no crudo (#693).
+func TestReservationDeleteRollbackEscapesHostileName(t *testing.T) {
+	const dhcpHostile = dhcpEmpty + `dhcp.np_host_aabbccddeeff=host
+dhcp.np_host_aabbccddeeff.name='tv'; ping -c1 evil.example; echo '
+dhcp.np_host_aabbccddeeff.mac='aa:bb:cc:dd:ee:ff'
+dhcp.np_host_aabbccddeeff.ip='192.168.1.60'
+`
+	ssh := newSSH(dhcpHostile, fwEmpty, sshRule{contains: "restart", err: errors.New("reload fail")})
+	ts := makeDeviceActionsTestServer(t, ssh)
+
+	res := deviceReq(t, "DELETE", ts.URL, "/api/devices/"+devMAC+"/reservation", ts.cookie, "")
+	if res.StatusCode != 500 {
+		t.Fatalf("DELETE con reload fallido: got %d want 500", res.StatusCode)
+	}
+	res.Body.Close()
+	// El rollback re-crea la sección: el name hostil debe viajar escapado.
+	if !ssh.saw(`name='tv'\''; ping`) {
+		t.Errorf("el rollback debe escapar la comilla simple del name leído del router; cmds: %v", ssh.cmdsSnapshot())
+	}
+	if ssh.saw(`name='tv'; ping`) {
+		t.Error("el name hostil llegó SIN escapar al comando SSH")
+	}
+}
+
 func TestBlockMissingRouter(t *testing.T) {
 func TestBlockMissingRouter(t *testing.T) {
 	ssh := newSSH(dhcpEmpty, fwEmpty)
 	ssh := newSSH(dhcpEmpty, fwEmpty)
 	ts := makeDeviceActionsTestServer(t, ssh)
 	ts := makeDeviceActionsTestServer(t, ssh)