wireguard.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. // wireguard.go — Adapter live para WireGuard (port de
  2. // src/adapters/wireguard.js, SPEC §7.5): parsea `wg show <iface> dump` vía
  3. // SSH en el gateway. Quirk preservado: status 'active' siempre que el
  4. // comando responda (peers.length >= 0 ⇒ true).
  5. package adapters
  6. import (
  7. "encoding/base64"
  8. "fmt"
  9. "strconv"
  10. "strings"
  11. "time"
  12. )
  13. const handshakeActiveSec = 180 // handshake < 3 min ⇒ peer activo
  14. // wgUciMarker separa el dump `wg show` de la config `uci show network` en una
  15. // única sesión SSH. Permite resolver el nombre del peer (option description de
  16. // los wireguard_peer) sin un segundo roundtrip (issue #659).
  17. const wgUciMarker = "===NETPULSE_UCI==="
  18. // wgGlMarker separa, tras el UCI de network, el volcado filtrado del config
  19. // propietario wireguard_server de GL.iNet (firmware GL: el servidor WG no usa
  20. // proto 'wireguard', así que los clientes NO aparecen en uci show network;
  21. // viven en secciones config peers con option name, issue #1433).
  22. const wgGlMarker = "===NETPULSE_GL==="
  23. // wgGlNamesCommand vuelca SOLO name/public_key/client_ip de
  24. // wireguard_server. El grep corre EN EL ROUTER: las private_key de los peers
  25. // (que GL.iNet guarda en ese mismo config) jamás salen del equipo.
  26. const wgGlNamesCommand = "uci show wireguard_server 2>/dev/null | grep -E '\\.(name|public_key|client_ip)='"
  27. // wgStatsCommand devuelve el comando que emite el dump de `wg show <iface>`,
  28. // a continuación la config WireGuard UCI y, tras el segundo marker, los
  29. // nombres de peers del config wireguard_server (GL.iNet). El exit code es el
  30. // de `wg show` (si el túnel está caído, la llamada falla y GetWireGuardStats
  31. // salta esa interfaz sin tumbar el resto, issue #714).
  32. func wgStatsCommand(iface string) string {
  33. return fmt.Sprintf("wg show %s dump; rc=$?; echo '%s'; uci show network 2>/dev/null; echo '%s'; %s; exit $rc", iface, wgUciMarker, wgGlMarker, wgGlNamesCommand)
  34. }
  35. // awgStatsCommand es la variante AmneziaWG de wgStatsCommand: mismo contrato
  36. // (dump + markers + UCI, exit del dump) pero con la herramienta `awg`, la
  37. // única que puede leer interfaces de la familia amneziawg (issue #776).
  38. func awgStatsCommand(iface string) string {
  39. return fmt.Sprintf("awg show %s dump; rc=$?; echo '%s'; uci show network 2>/dev/null; echo '%s'; %s; exit $rc", iface, wgUciMarker, wgGlMarker, wgGlNamesCommand)
  40. }
  41. // wgListCommand lista las interfaces WireGuard presentes en el router
  42. // (`wg show interfaces`): nombres separados por espacios en una sola línea.
  43. const wgListCommand = "wg show interfaces"
  44. // awgListCommand lista las interfaces AmneziaWG (`awg show interfaces`).
  45. // AmneziaWG (luci-proto-amneziawg) usa su propia familia netlink y su
  46. // herramienta `awg`: `wg` NO ve sus interfaces (issue #776).
  47. const awgListCommand = "awg show interfaces"
  48. // parseWGInterfaces parsea la salida de `wg show interfaces` en una lista de
  49. // nombres. Salida vacía → lista vacía (sin interfaces).
  50. func parseWGInterfaces(out string) []string {
  51. return strings.Fields(strings.TrimSpace(out))
  52. }
  53. // wgInterfaces resuelve qué interfaces sondear. iface vacío o "auto" →
  54. // descubre todas con `wg show interfaces` y `awg show interfaces` (AmneziaWG,
  55. // #776); un valor explícito (una interfaz o una lista separada por comas)
  56. // actúa como filtro/override sin tocar el router para listarlas (#713). Si
  57. // AMBOS listados fallan en modo auto (p. ej. un `wg` sin el subcomando
  58. // `interfaces`), cae al default histórico `wg0` para no dejar el panel sin
  59. // datos (#714). Un listado que falle individualmente (p. ej. `awg` no
  60. // instalado) se trata como "sin interfaces de ese tipo".
  61. func wgInterfaces(pool sshRunner, host, iface string) []string {
  62. v := strings.TrimSpace(iface)
  63. if v != "" && v != "auto" {
  64. out := []string{}
  65. for _, part := range strings.Split(v, ",") {
  66. if s := strings.TrimSpace(part); s != "" {
  67. out = append(out, s)
  68. }
  69. }
  70. return out
  71. }
  72. raw, err := pool.Run(host, wgListCommand, 0)
  73. awgRaw, awgErr := pool.Run(host, awgListCommand, 0)
  74. if err != nil && awgErr != nil {
  75. return []string{"wg0"}
  76. }
  77. seen := map[string]bool{}
  78. out := []string{}
  79. for _, name := range append(parseWGInterfaces(raw), parseWGInterfaces(awgRaw)...) {
  80. if !seen[name] {
  81. seen[name] = true
  82. out = append(out, name)
  83. }
  84. }
  85. return out
  86. }
  87. // splitWGParts separa la salida combinada (dump + marker UCI + marker GL) en
  88. // sus tres partes. Cualquier parte cuyo marker falte queda vacía (los routers
  89. // sin config wireguard_server, es decir, los no-GL.iNet, no emiten nada tras
  90. // el segundo marker).
  91. func splitWGParts(out string) (dump, uci, gl string) {
  92. dump = out
  93. if idx := strings.Index(dump, wgUciMarker); idx >= 0 {
  94. uci = strings.TrimLeft(dump[idx+len(wgUciMarker):], "\n")
  95. dump = dump[:idx]
  96. }
  97. if idx := strings.Index(uci, wgGlMarker); idx >= 0 {
  98. gl = strings.TrimLeft(uci[idx+len(wgGlMarker):], "\n")
  99. uci = strings.TrimRight(uci[:idx], "\n")
  100. }
  101. return dump, uci, gl
  102. }
  103. // WGDumpPeer es un peer parseado del dump (campos numéricos crudos).
  104. type WGDumpPeer struct {
  105. Pubkey string
  106. Endpoint *string // nil si "(none)"
  107. AllowedIPs string
  108. HandshakeSec int64
  109. RxBytes int64
  110. TxBytes int64
  111. }
  112. // ParseWGDump parsea la salida TSV de `wg show <iface> dump` (literal del
  113. // JS: se ignora la línea 1 — interfaz — y las líneas con < 8 campos).
  114. func ParseWGDump(dump string) []WGDumpPeer {
  115. lines := strings.Split(strings.TrimSpace(dump), "\n")
  116. peers := []WGDumpPeer{}
  117. for _, line := range lines[1:] {
  118. f := strings.Split(line, "\t")
  119. if len(f) < 8 {
  120. continue
  121. }
  122. var endpoint *string
  123. if f[2] != "(none)" {
  124. ep := f[2]
  125. endpoint = &ep
  126. }
  127. peers = append(peers, WGDumpPeer{
  128. Pubkey: f[0],
  129. Endpoint: endpoint,
  130. AllowedIPs: f[3],
  131. HandshakeSec: atoiOr(f[4], 0),
  132. RxBytes: atoiOr(f[5], 0),
  133. TxBytes: atoiOr(f[6], 0),
  134. })
  135. }
  136. return peers
  137. }
  138. func atoiOr(s string, def int64) int64 {
  139. n, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
  140. if err != nil {
  141. return def
  142. }
  143. return n
  144. }
  145. // WGPeerName etiqueta un peer por tunnelIp o pubkey (peerNames del config).
  146. type WGPeerName struct {
  147. ID string
  148. Name string
  149. Type string
  150. }
  151. // parseWGUciDescs extrae de la salida de `uci show network` las descripciones
  152. // de los peers WireGuard (option description), indexadas por public_key y por
  153. // cada allowed_ip normalizada (sin /32). Devuelve un mapa key → descripción.
  154. // Solo incluye secciones wireguard_peer con descripción no vacía.
  155. func parseWGUciDescs(uci string) map[string]string {
  156. type peerDesc struct {
  157. pub string
  158. allowedIPs string
  159. desc string
  160. }
  161. bySec := map[string]*peerDesc{}
  162. for _, line := range strings.Split(uci, "\n") {
  163. line = strings.TrimSpace(line)
  164. if !strings.HasPrefix(line, "network.") {
  165. continue
  166. }
  167. rest := strings.TrimPrefix(line, "network.")
  168. eq := strings.Index(rest, "=")
  169. if eq < 0 {
  170. continue
  171. }
  172. val := strings.Trim(strings.TrimPrefix(rest[eq:], "="), "'")
  173. path := rest[:eq]
  174. dot := strings.Index(path, ".")
  175. if dot < 0 {
  176. continue
  177. }
  178. sec, opt := path[:dot], path[dot+1:]
  179. p := bySec[sec]
  180. if p == nil {
  181. p = &peerDesc{}
  182. bySec[sec] = p
  183. }
  184. switch opt {
  185. case "public_key":
  186. p.pub = val
  187. case "allowed_ips":
  188. if p.allowedIPs != "" {
  189. p.allowedIPs += ","
  190. }
  191. p.allowedIPs += val
  192. case "description":
  193. p.desc = val
  194. }
  195. }
  196. out := map[string]string{}
  197. for _, p := range bySec {
  198. if p.desc == "" {
  199. continue
  200. }
  201. if p.pub != "" {
  202. out[p.pub] = p.desc
  203. }
  204. for _, cidr := range strings.Split(p.allowedIPs, ",") {
  205. ip := strings.Replace(strings.TrimSpace(cidr), "/32", "", 1)
  206. if ip != "" {
  207. out[ip] = p.desc
  208. }
  209. }
  210. }
  211. return out
  212. }
  213. // parseWGServerNames extrae los nombres de peers del config propietario
  214. // wireguard_server de GL.iNet (issue #1433): secciones `config peers` con
  215. // option name/public_key/client_ip. Indexa por public_key y por client_ip
  216. // normalizada (sin máscara, p.ej. 10.0.0.2/24 → 10.0.0.2), como hace
  217. // parseWGUciDescs con las allowed_ips. Solo secciones con name no vacío.
  218. func parseWGServerNames(gl string) map[string]string {
  219. type glPeer struct {
  220. pub string
  221. name string
  222. ip string
  223. }
  224. bySec := map[string]*glPeer{}
  225. for _, line := range strings.Split(gl, "\n") {
  226. line = strings.TrimSpace(line)
  227. if !strings.HasPrefix(line, "wireguard_server.") {
  228. continue
  229. }
  230. rest := strings.TrimPrefix(line, "wireguard_server.")
  231. eq := strings.Index(rest, "=")
  232. if eq < 0 {
  233. continue
  234. }
  235. val := strings.Trim(strings.TrimPrefix(rest[eq:], "="), "'")
  236. path := rest[:eq]
  237. dot := strings.LastIndex(path, ".")
  238. if dot < 0 {
  239. continue
  240. }
  241. sec, opt := path[:dot], path[dot+1:]
  242. p := bySec[sec]
  243. if p == nil {
  244. p = &glPeer{}
  245. bySec[sec] = p
  246. }
  247. switch opt {
  248. case "public_key":
  249. p.pub = val
  250. case "name":
  251. p.name = val
  252. case "client_ip":
  253. p.ip = val
  254. }
  255. }
  256. out := map[string]string{}
  257. for _, p := range bySec {
  258. if p.name == "" {
  259. continue
  260. }
  261. if p.pub != "" {
  262. out[p.pub] = p.name
  263. }
  264. if ip := p.ip; ip != "" {
  265. if i := strings.Index(ip, "/"); i >= 0 {
  266. ip = ip[:i]
  267. }
  268. if ip != "" {
  269. out[ip] = p.name
  270. }
  271. }
  272. }
  273. return out
  274. }
  275. // WGPeerKey devuelve el identificador ESTABLE y apto para URL de un peer
  276. // WireGuard (#1441): la clave pública en base64url sin padding (43 chars).
  277. // Es el único dato que identifica al peer entre sondeos y reinicios: WGPeer.ID
  278. // sale del device de NetPulse que casó por IP del túnel o, si no hay ninguno,
  279. // del índice del dump ("peer-3"), que cambia al reordenar los peers.
  280. // base64url porque una pubkey WireGuard lleva '+' y '/' (base64 estándar) y
  281. // esos caracteres rompen el path del endpoint de urgencia.
  282. func WGPeerKey(pubkey string) string {
  283. pk := strings.TrimSpace(pubkey)
  284. if pk == "" {
  285. return ""
  286. }
  287. raw, err := base64.StdEncoding.DecodeString(pk)
  288. if err != nil {
  289. // Pubkey no estándar (dump de AmneziaWG o firmware raro): se
  290. // translitera a mano en vez de descartarla.
  291. return strings.NewReplacer("+", "-", "/", "_", "=", "").Replace(pk)
  292. }
  293. return base64.RawURLEncoding.EncodeToString(raw)
  294. }
  295. // buildWGPeer convierte un peer del dump en un WGPeer, resolviendo el nombre
  296. // con la prioridad de siempre (nombre de device NetPulse → description UCI →
  297. // nombre del config wireguard_server (GL.iNet) → tunnelIP → "Peer <pubkey8>",
  298. // issues #659/#1433) y asignando el fallback de ID
  299. // "peer-<idx>" con un contador global (idx) para que los peers de varias
  300. // interfaces no colisionen (#713). urgent (#1441): claves de peer marcadas
  301. // como importantes, por Key y, como cortesía, por ID (las llamadas antiguas y
  302. // los tests construyen WGPeer sin Key).
  303. func buildWGPeer(p WGDumpPeer, peerNames map[string]WGPeerName, descs map[string]string, nowSec int64, idx int, urgent map[string]bool) WGPeer {
  304. tunnelIP := ""
  305. if parts := strings.Split(p.AllowedIPs, ","); len(parts) > 0 {
  306. tunnelIP = strings.Replace(parts[0], "/32", "", 1)
  307. }
  308. named, ok := peerNames[tunnelIP]
  309. if !ok {
  310. named = peerNames[p.Pubkey]
  311. }
  312. id := named.ID
  313. if id == "" {
  314. id = "peer-" + strconv.Itoa(idx)
  315. }
  316. name := named.Name
  317. if name == "" {
  318. name = descs[p.Pubkey]
  319. if name == "" {
  320. name = descs[tunnelIP]
  321. }
  322. if name == "" {
  323. name = tunnelIP
  324. if name == "" {
  325. name = "Peer " + p.Pubkey[:min(len(p.Pubkey), 8)]
  326. }
  327. }
  328. }
  329. typ := named.Type
  330. if typ == "" {
  331. typ = "desconocido"
  332. }
  333. active := p.HandshakeSec > 0 && nowSec-p.HandshakeSec < handshakeActiveSec
  334. lastHandshake := "nunca"
  335. if p.HandshakeSec > 0 {
  336. lastHandshake = relTime(p.HandshakeSec, nowSec)
  337. }
  338. key := WGPeerKey(p.Pubkey)
  339. return WGPeer{
  340. ID: id, Key: key, Name: name, Type: typ, TunnelIP: tunnelIP,
  341. Active: active, LastHandshake: lastHandshake,
  342. Rx: fmtBytes(float64(p.RxBytes)), Tx: fmtBytes(float64(p.TxBytes)),
  343. Urgent: urgent[key] || urgent[id],
  344. }
  345. }
  346. // GetWireGuardStats obtiene WireGuardStats del gateway vía SSH, agregando los
  347. // peers de TODAS las interfaces WireGuard del router (issue #713).
  348. // iface: filtro/override de interfaces a sondear ("auto"/vacío → descubrir
  349. // todas con `wg show interfaces`; valor → interfaz o lista separada por
  350. // comas). peerNames: mapa tunnelIp/pubkey → etiqueta opcional (nombre de
  351. // device). El nombre de cada peer se resuelve en este orden: nombre de device
  352. // de NetPulse (peerNames) → description del peer en UCI (OpenWrt) → name del
  353. // config wireguard_server (GL.iNet, issue #1433) → IP del túnel →
  354. // "Peer <pubkey8>" (issue #659).
  355. //
  356. // Tolerancia a fallos (#714): el fallo del dump de UNA interfaz se salta (se
  357. // acumulan los peers de las que responden); si TODAS fallan se devuelve
  358. // Status "inactive" SIN error, para que pollWireGuard no loguee "no
  359. // disponible" en cada tick.
  360. //
  361. // urgent (#1441): conjunto de claves de peer (WGPeer.Key) marcadas como
  362. // importantes por el admin; se estampa en cada WGPeer para que el mapa y las
  363. // alertas sepan a quién tratar distinto. nil = ninguno.
  364. func GetWireGuardStats(pool sshRunner, host, iface, subnet string, peerNames map[string]WGPeerName, urgent map[string]bool) (*WireGuardStats, error) {
  365. ifaces := wgInterfaces(pool, host, iface)
  366. stats := &WireGuardStats{
  367. Interface: strings.Join(ifaces, ", "),
  368. Subnet: subnet,
  369. Status: "active", // quirk: siempre que el comando responda
  370. Peers: []WGPeer{},
  371. }
  372. if len(ifaces) == 0 {
  373. // Sin interfaces WireGuard en el router: no hay túneles que sondear.
  374. stats.Status = "inactive"
  375. return stats, nil
  376. }
  377. nowSec := time.Now().Unix()
  378. descs := map[string]string{}
  379. idx := 1
  380. ok := 0
  381. for _, ifc := range ifaces {
  382. out, err := pool.Run(host, wgStatsCommand(ifc), 0)
  383. if err != nil {
  384. // La interfaz puede ser AmneziaWG (`wg` no la ve; #776): se
  385. // reintenta con `awg` antes de saltarla.
  386. out, err = pool.Run(host, awgStatsCommand(ifc), 0)
  387. if err != nil {
  388. // Una interfaz caída no tumba el resto: se salta (#714).
  389. continue
  390. }
  391. }
  392. ok++
  393. dump, uci, gl := splitWGParts(out)
  394. // Nombres del config wireguard_server (GL.iNet) como base; la
  395. // description UCI estándar (network.*) pisa a la de GL cuando ambas
  396. // existen para la misma clave.
  397. for k, v := range parseWGServerNames(gl) {
  398. descs[k] = v
  399. }
  400. for k, v := range parseWGUciDescs(uci) {
  401. descs[k] = v
  402. }
  403. for _, p := range ParseWGDump(dump) {
  404. stats.Peers = append(stats.Peers, buildWGPeer(p, peerNames, descs, nowSec, idx, urgent))
  405. idx++
  406. }
  407. }
  408. if ok == 0 {
  409. // Ninguna interfaz respondió: túnel inactivo, sin error (#714).
  410. stats.Status = "inactive"
  411. }
  412. return stats, nil
  413. }