wireguard.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. // wireguard.go - módulo de orquestación "WireGuard peers" (Fase 10.3).
  2. //
  3. // Reconoce los peers de un túnel WireGuard contra el estado deseado: crea la
  4. // interfaz network.wg0 (si no existe), añade/actualiza/borra las secciones
  5. // network.wgpeer<N> (public_key + allowed_ips) y termina con un reload de red
  6. // más healthcheck `wg show`. Si el túnel que estaba arriba no levanta tras el
  7. // apply, el executor revierte el plan (rollback real).
  8. //
  9. // Anti-lockout: un peer cuyo public_key coincide con
  10. // WireGuardDesired.AdminPeerPublicKey NUNCA se borra (el admin gestiona el
  11. // túnel desde ese peer; borrarlo aislaría al admin del túnel).
  12. package orchestr
  13. import (
  14. "fmt"
  15. "strings"
  16. "time"
  17. "github.com/gnacho/netpulse/agent/executor"
  18. )
  19. // WireGuardPeer es un peer del túnel WireGuard.
  20. type WireGuardPeer struct {
  21. Name string `json:"name"`
  22. // PublicKey: clave pública base64 del peer (wireguard pubkey).
  23. PublicKey string `json:"publicKey"`
  24. // AllowedIPs: CIDRs permitidos del peer, separados por coma
  25. // (p. ej. "10.0.0.2/32" o "10.0.0.2/32,10.0.1.0/24").
  26. AllowedIPs string `json:"allowedIps"`
  27. }
  28. // WireGuardDesired es el estado deseado del módulo WireGuard.
  29. type WireGuardDesired struct {
  30. // Interface: nombre de la interfaz del túnel (default "wg0").
  31. Interface string `json:"interface"`
  32. // Peers: conjunto declarativo de peers. Los peers presentes en el router
  33. // que NO estén en esta lista se borran (salvo el del admin).
  34. Peers []WireGuardPeer `json:"peers"`
  35. // AdminPeerPublicKey: pubkey del peer del admin. Protección anti-lockout:
  36. // ese peer nunca se borra, aunque no esté en Peers.
  37. AdminPeerPublicKey string `json:"adminPeerPubkey,omitempty"`
  38. }
  39. // WireGuardScenario describe el estado de WireGuard en el router.
  40. type WireGuardScenario struct {
  41. // WGInstalled: /usr/bin/wg existe (wireguard-tools instalado).
  42. WGInstalled bool
  43. // WGActive: `wg show` reporta al menos una interfaz arriba.
  44. WGActive bool
  45. // WGIfaces: interfaces WireGuard presentes en UCI
  46. // (network.<name>.proto='wireguard').
  47. WGIfaces []string
  48. // ActiveIfaces: interfaces activas en el kernel según `wg show`.
  49. ActiveIfaces []string
  50. // Peers: secciones wgpeer existentes (public_key + allowed_ips).
  51. Peers []WireGuardPeer
  52. }
  53. // probeWireGuardCmd detecta instalación, estado del túnel y secciones UCI.
  54. // `|| true` tras wg show para no abortar la sesión si wg no está instalado.
  55. const probeWireGuardCmd = `echo '===WG_BIN==='
  56. [ -x /usr/bin/wg ] && echo yes || echo no
  57. echo '===WG==='
  58. wg show 2>/dev/null
  59. echo '===NETWORK==='
  60. uci show network 2>/dev/null
  61. echo '===END==='`
  62. // DetectWireGuard ejecuta el probe y devuelve el escenario.
  63. func DetectWireGuard(run CommandRunner, host string) (WireGuardScenario, error) {
  64. out, err := run.Run(host, probeWireGuardCmd, 8*time.Second)
  65. if err != nil {
  66. return WireGuardScenario{}, err
  67. }
  68. return parseWireGuard(out), nil
  69. }
  70. // parseWireGuard extrae el escenario del output del probe. Función pura.
  71. func parseWireGuard(out string) WireGuardScenario {
  72. sc := WireGuardScenario{}
  73. sections := splitSections(out)
  74. sc.WGInstalled = strings.TrimSpace(firstNonEmpty(sections["WG_BIN"])) == "yes"
  75. // `wg show`: líneas "interface: <nombre>".
  76. for _, line := range sections["WG"] {
  77. line = strings.TrimSpace(line)
  78. if strings.HasPrefix(line, "interface:") {
  79. if name := strings.TrimSpace(strings.TrimPrefix(line, "interface:")); name != "" {
  80. sc.ActiveIfaces = append(sc.ActiveIfaces, name)
  81. }
  82. }
  83. }
  84. sc.WGActive = len(sc.ActiveIfaces) > 0
  85. // `uci show network`: secciones interface (proto wireguard) y peers.
  86. uci := strings.Join(sections["NETWORK"], "\n")
  87. for _, line := range strings.Split(uci, "\n") {
  88. line = strings.TrimSpace(line)
  89. if !strings.HasPrefix(line, "network.") {
  90. continue
  91. }
  92. rest := strings.TrimPrefix(line, "network.")
  93. switch {
  94. case strings.HasSuffix(rest, "=interface"):
  95. sec := strings.TrimSuffix(rest, "=interface")
  96. if wireguardSectionProto(uci, sec) {
  97. sc.WGIfaces = append(sc.WGIfaces, sec)
  98. }
  99. case strings.Contains(rest, "=wireguard_"):
  100. sec := rest[:strings.Index(rest, "=")]
  101. peer := WireGuardPeer{
  102. Name: sec,
  103. PublicKey: wireguardOption(uci, sec, "public_key"),
  104. }
  105. peer.AllowedIPs = normalizeAllowedIPs(wireguardOptionList(uci, sec, "allowed_ips"))
  106. sc.Peers = append(sc.Peers, peer)
  107. }
  108. }
  109. return sc
  110. }
  111. // wireguardSectionProto devuelve true si la sección interface tiene
  112. // proto='wireguard' ("network.<sec>.proto='wireguard'").
  113. func wireguardSectionProto(uci, sec string) bool {
  114. prefix := "network." + sec + ".proto="
  115. for _, line := range strings.Split(uci, "\n") {
  116. line = strings.TrimSpace(line)
  117. if strings.HasPrefix(line, prefix) {
  118. return strings.Contains(line, "'wireguard'")
  119. }
  120. }
  121. return false
  122. }
  123. // wireguardOption lee una option de una sección ("network.<sec>.<opt>='v'").
  124. func wireguardOption(uci, sec, option string) string {
  125. prefix := "network." + sec + "." + option + "="
  126. for _, line := range strings.Split(uci, "\n") {
  127. line = strings.TrimSpace(line)
  128. if strings.HasPrefix(line, prefix) {
  129. return strings.Trim(strings.TrimPrefix(line, prefix), "'")
  130. }
  131. }
  132. return ""
  133. }
  134. // wireguardOptionList une los valores de una option tipo lista
  135. // ("network.<sec>.allowed_ips='v'" por cada entrada).
  136. func wireguardOptionList(uci, sec, option string) string {
  137. prefix := "network." + sec + "." + option + "="
  138. var vals []string
  139. for _, line := range strings.Split(uci, "\n") {
  140. line = strings.TrimSpace(line)
  141. if strings.HasPrefix(line, prefix) {
  142. vals = append(vals, strings.Trim(strings.TrimPrefix(line, prefix), "'"))
  143. }
  144. }
  145. return strings.Join(vals, ",")
  146. }
  147. // WireGuardOps genera las Ops para reconciliar los peers del túnel.
  148. func WireGuardOps(desired WireGuardDesired, sc WireGuardScenario) []executor.Op {
  149. iface := desired.Interface
  150. if iface == "" {
  151. iface = "wg0"
  152. }
  153. var ops []executor.Op
  154. // 1. Interfaz: crear la sección si no existe.
  155. if !wgInterfaceExists(sc, iface) {
  156. ops = append(ops,
  157. executor.Op{Kind: "uci_set_named", Args: map[string]string{"config": "network", "section": iface, "type": "interface"}, Desc: "Create wireguard interface " + iface},
  158. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "network", "section": iface, "option": "proto", "value": "wireguard"}, Desc: "Set wireguard proto on " + iface},
  159. )
  160. }
  161. // 2. Peers del desired: crear los nuevos, actualizar los existentes.
  162. for _, p := range desired.Peers {
  163. pub := strings.TrimSpace(p.PublicKey)
  164. if pub == "" {
  165. continue // fila vacía de la UI
  166. }
  167. existing := wgPeerByPubkey(sc, pub)
  168. if existing != nil {
  169. // public_key igual por construcción (match por pubkey): solo
  170. // reconciliar allowed_ips si cambia.
  171. if normalizeAllowedIPs(existing.AllowedIPs) != normalizeAllowedIPs(p.AllowedIPs) {
  172. ops = append(ops, executor.Op{Kind: "uci_delete", Args: map[string]string{"config": "network", "section": existing.Name, "option": "allowed_ips"}, Desc: "Reset allowed_ips on " + existing.Name})
  173. for _, cidr := range splitAllowedIPs(p.AllowedIPs) {
  174. ops = append(ops, executor.Op{Kind: "uci_add_list", Args: map[string]string{"config": "network", "section": existing.Name, "option": "allowed_ips", "value": cidr}, Desc: "Add allowed_ip " + cidr + " to " + existing.Name})
  175. }
  176. }
  177. continue
  178. }
  179. name := nextWgPeerName(sc, iface)
  180. ops = append(ops,
  181. executor.Op{Kind: "uci_set_named", Args: map[string]string{"config": "network", "section": name, "type": "wireguard_" + iface}, Desc: "Create peer section " + name},
  182. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "network", "section": name, "option": "public_key", "value": pub}, Desc: "Set public key on " + name},
  183. )
  184. for _, cidr := range splitAllowedIPs(p.AllowedIPs) {
  185. ops = append(ops, executor.Op{Kind: "uci_add_list", Args: map[string]string{"config": "network", "section": name, "option": "allowed_ips", "value": cidr}, Desc: "Add allowed_ip " + cidr + " to " + name})
  186. }
  187. sc.Peers = append(sc.Peers, WireGuardPeer{Name: name, PublicKey: pub})
  188. }
  189. // 3. Borrar peers que ya no están en el desired. Anti-lockout: el peer
  190. // cuyo public_key es el del admin NUNCA se borra.
  191. for _, p := range sc.Peers {
  192. if wgPeerDesired(desired.Peers, p.PublicKey) {
  193. continue
  194. }
  195. if p.PublicKey != "" && p.PublicKey == desired.AdminPeerPublicKey {
  196. continue // protección anti-lockout
  197. }
  198. ops = append(ops, executor.Op{Kind: "uci_delete_section", Args: map[string]string{"config": "network", "section": p.Name}, Desc: "Remove peer " + p.Name})
  199. }
  200. if len(ops) == 0 {
  201. return nil
  202. }
  203. ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "network"}, Desc: "Commit network config"})
  204. ops = append(ops, executor.Op{Kind: "service", Args: map[string]string{"name": "network", "action": "reload"}, Desc: "Reload network (apply wireguard)"})
  205. if wgCheckNeeded(sc, iface) {
  206. ops = append(ops, executor.Op{Kind: "wg_check", Args: map[string]string{"interface": iface}, Desc: "Check tunnel " + iface + " is up (wg show)"})
  207. }
  208. return ops
  209. }
  210. // WireGuardHealthcheck verifica que el túnel sigue arriba tras el apply:
  211. // `wg show <iface>` falla si la interfaz no existe o está caída. Es el
  212. // healthcheck del módulo (el executor lo ejecuta como op wg_check en el plan).
  213. func WireGuardHealthcheck(run CommandRunner, host, iface string) error {
  214. if iface == "" {
  215. iface = "wg0"
  216. }
  217. out, err := run.Run(host, "wg show "+iface, 8*time.Second)
  218. if err != nil {
  219. return fmt.Errorf("tunnel %s not up: %w", iface, err)
  220. }
  221. if !strings.Contains(out, "interface: "+iface) {
  222. return fmt.Errorf("tunnel %s not up (wg show has no interface)", iface)
  223. }
  224. return nil
  225. }
  226. // wgInterfaceExists: la interfaz deseada está en UCI con proto wireguard.
  227. func wgInterfaceExists(sc WireGuardScenario, iface string) bool {
  228. return wgContains(sc.WGIfaces, iface)
  229. }
  230. // wgPeerByPubkey busca un peer existente por su public_key (nil si no existe).
  231. func wgPeerByPubkey(sc WireGuardScenario, pub string) *WireGuardPeer {
  232. for i := range sc.Peers {
  233. if sc.Peers[i].PublicKey == pub {
  234. return &sc.Peers[i]
  235. }
  236. }
  237. return nil
  238. }
  239. // wgPeerDesired: hay un peer en desired con ese public_key.
  240. func wgPeerDesired(peers []WireGuardPeer, pub string) bool {
  241. for _, p := range peers {
  242. if strings.TrimSpace(p.PublicKey) == pub {
  243. return true
  244. }
  245. }
  246. return false
  247. }
  248. // nextWgPeerName devuelve el nombre libre wgpeer<N> más bajo no usado.
  249. func nextWgPeerName(sc WireGuardScenario, iface string) string {
  250. used := map[string]bool{iface: true}
  251. for _, p := range sc.Peers {
  252. used[p.Name] = true
  253. }
  254. for n := 1; ; n++ {
  255. name := fmt.Sprintf("wgpeer%d", n)
  256. if !used[name] {
  257. return name
  258. }
  259. }
  260. }
  261. // splitAllowedIPs parte un valor "cidr1,cidr2" en CIDRs individuales.
  262. func splitAllowedIPs(val string) []string {
  263. var out []string
  264. for _, part := range strings.Split(val, ",") {
  265. if cidr := strings.TrimSpace(part); cidr != "" {
  266. out = append(out, cidr)
  267. }
  268. }
  269. return out
  270. }
  271. // normalizeAllowedIPs limpia espacios/vacíos de un valor de CIDRs para poder
  272. // comparar listas entre el router y el desired sin depender del formato.
  273. func normalizeAllowedIPs(val string) string {
  274. parts := splitAllowedIPs(val)
  275. if len(parts) == 0 {
  276. return ""
  277. }
  278. return strings.Join(parts, ",")
  279. }
  280. // wgCheckNeeded: solo verificar el túnel si WireGuard está instalado y había
  281. // un túnel activo antes del apply (el healthcheck protege el túnel EXISTENTE).
  282. func wgCheckNeeded(sc WireGuardScenario, iface string) bool {
  283. if !sc.WGInstalled || !sc.WGActive {
  284. return false
  285. }
  286. return wgContains(sc.ActiveIfaces, iface)
  287. }
  288. func wgContains(list []string, want string) bool {
  289. for _, s := range list {
  290. if s == want {
  291. return true
  292. }
  293. }
  294. return false
  295. }
  296. // validateWireGuardOps valida cada op contra el executor (usado en tests).
  297. func validateWireGuardOps(ops []executor.Op) error {
  298. for _, op := range ops {
  299. if err := executor.Validate(op); err != nil {
  300. return fmt.Errorf("%s: %w", op.Desc, err)
  301. }
  302. }
  303. return nil
  304. }