wireguard.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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 se ejecutan y fallan (un `wg` sin el subcomando `interfaces`),
  58. // cae al default histórico `wg0` para no dejar el panel sin datos (#714). Un
  59. // listado que falle individualmente (p. ej. `awg` no instalado) se trata como
  60. // "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. // #2041: el fallback wg0 es para routers ALCANZABLES cuyo `wg` no
  76. // lista interfaces. Si no se pudo ejecutar el listado (credencial
  77. // rechazada, host en backoff, timeout) no hay ninguna evidencia sobre
  78. // WireGuard en ese router: inventar wg0 creaba una interfaz caída que
  79. // la nota de salud penalizaba -10 para siempre, porque la guarda de
  80. // #1442 solo se salta la penalización con Interface vacío.
  81. if remoteExited(err) || remoteExited(awgErr) {
  82. return []string{"wg0"}
  83. }
  84. return nil
  85. }
  86. seen := map[string]bool{}
  87. out := []string{}
  88. for _, name := range append(parseWGInterfaces(raw), parseWGInterfaces(awgRaw)...) {
  89. if !seen[name] {
  90. seen[name] = true
  91. out = append(out, name)
  92. }
  93. }
  94. return out
  95. }
  96. // splitWGParts separa la salida combinada (dump + marker UCI + marker GL) en
  97. // sus tres partes. Cualquier parte cuyo marker falte queda vacía (los routers
  98. // sin config wireguard_server, es decir, los no-GL.iNet, no emiten nada tras
  99. // el segundo marker).
  100. func splitWGParts(out string) (dump, uci, gl string) {
  101. dump = out
  102. if idx := strings.Index(dump, wgUciMarker); idx >= 0 {
  103. uci = strings.TrimLeft(dump[idx+len(wgUciMarker):], "\n")
  104. dump = dump[:idx]
  105. }
  106. if idx := strings.Index(uci, wgGlMarker); idx >= 0 {
  107. gl = strings.TrimLeft(uci[idx+len(wgGlMarker):], "\n")
  108. uci = strings.TrimRight(uci[:idx], "\n")
  109. }
  110. return dump, uci, gl
  111. }
  112. // WGDumpPeer es un peer parseado del dump (campos numéricos crudos).
  113. type WGDumpPeer struct {
  114. Pubkey string
  115. Endpoint *string // nil si "(none)"
  116. AllowedIPs string
  117. HandshakeSec int64
  118. RxBytes int64
  119. TxBytes int64
  120. }
  121. // ParseWGDump parsea la salida TSV de `wg show <iface> dump` (literal del
  122. // JS: se ignora la línea 1 — interfaz — y las líneas con < 8 campos).
  123. func ParseWGDump(dump string) []WGDumpPeer {
  124. lines := strings.Split(strings.TrimSpace(dump), "\n")
  125. peers := []WGDumpPeer{}
  126. for _, line := range lines[1:] {
  127. f := strings.Split(line, "\t")
  128. if len(f) < 8 {
  129. continue
  130. }
  131. var endpoint *string
  132. if f[2] != "(none)" {
  133. ep := f[2]
  134. endpoint = &ep
  135. }
  136. peers = append(peers, WGDumpPeer{
  137. Pubkey: f[0],
  138. Endpoint: endpoint,
  139. AllowedIPs: f[3],
  140. HandshakeSec: atoiOr(f[4], 0),
  141. RxBytes: atoiOr(f[5], 0),
  142. TxBytes: atoiOr(f[6], 0),
  143. })
  144. }
  145. return peers
  146. }
  147. func atoiOr(s string, def int64) int64 {
  148. n, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64)
  149. if err != nil {
  150. return def
  151. }
  152. return n
  153. }
  154. // WGPeerName etiqueta un peer por tunnelIp o pubkey (peerNames del config).
  155. type WGPeerName struct {
  156. ID string
  157. Name string
  158. Type string
  159. }
  160. // parseWGUciDescs extrae de la salida de `uci show network` las descripciones
  161. // de los peers WireGuard (option description), indexadas por public_key y por
  162. // cada allowed_ip normalizada (sin /32). Devuelve un mapa key → descripción.
  163. // Solo incluye secciones wireguard_peer con descripción no vacía.
  164. func parseWGUciDescs(uci string) map[string]string {
  165. type peerDesc struct {
  166. pub string
  167. allowedIPs string
  168. desc string
  169. }
  170. bySec := map[string]*peerDesc{}
  171. for _, line := range strings.Split(uci, "\n") {
  172. line = strings.TrimSpace(line)
  173. if !strings.HasPrefix(line, "network.") {
  174. continue
  175. }
  176. rest := strings.TrimPrefix(line, "network.")
  177. eq := strings.Index(rest, "=")
  178. if eq < 0 {
  179. continue
  180. }
  181. val := strings.Trim(strings.TrimPrefix(rest[eq:], "="), "'")
  182. path := rest[:eq]
  183. dot := strings.Index(path, ".")
  184. if dot < 0 {
  185. continue
  186. }
  187. sec, opt := path[:dot], path[dot+1:]
  188. p := bySec[sec]
  189. if p == nil {
  190. p = &peerDesc{}
  191. bySec[sec] = p
  192. }
  193. switch opt {
  194. case "public_key":
  195. p.pub = val
  196. case "allowed_ips":
  197. if p.allowedIPs != "" {
  198. p.allowedIPs += ","
  199. }
  200. p.allowedIPs += val
  201. case "description":
  202. p.desc = val
  203. }
  204. }
  205. out := map[string]string{}
  206. for _, p := range bySec {
  207. if p.desc == "" {
  208. continue
  209. }
  210. if p.pub != "" {
  211. out[p.pub] = p.desc
  212. }
  213. for _, cidr := range strings.Split(p.allowedIPs, ",") {
  214. ip := strings.Replace(strings.TrimSpace(cidr), "/32", "", 1)
  215. if ip != "" {
  216. out[ip] = p.desc
  217. }
  218. }
  219. }
  220. return out
  221. }
  222. // parseWGServerNames extrae los nombres de peers del config propietario
  223. // wireguard_server de GL.iNet (issue #1433): secciones `config peers` con
  224. // option name/public_key/client_ip. Indexa por public_key y por client_ip
  225. // normalizada (sin máscara, p.ej. 10.0.0.2/24 → 10.0.0.2), como hace
  226. // parseWGUciDescs con las allowed_ips. Solo secciones con name no vacío.
  227. func parseWGServerNames(gl string) map[string]string {
  228. type glPeer struct {
  229. pub string
  230. name string
  231. ip string
  232. }
  233. bySec := map[string]*glPeer{}
  234. for _, line := range strings.Split(gl, "\n") {
  235. line = strings.TrimSpace(line)
  236. if !strings.HasPrefix(line, "wireguard_server.") {
  237. continue
  238. }
  239. rest := strings.TrimPrefix(line, "wireguard_server.")
  240. eq := strings.Index(rest, "=")
  241. if eq < 0 {
  242. continue
  243. }
  244. val := strings.Trim(strings.TrimPrefix(rest[eq:], "="), "'")
  245. path := rest[:eq]
  246. dot := strings.LastIndex(path, ".")
  247. if dot < 0 {
  248. continue
  249. }
  250. sec, opt := path[:dot], path[dot+1:]
  251. p := bySec[sec]
  252. if p == nil {
  253. p = &glPeer{}
  254. bySec[sec] = p
  255. }
  256. switch opt {
  257. case "public_key":
  258. p.pub = val
  259. case "name":
  260. p.name = val
  261. case "client_ip":
  262. p.ip = val
  263. }
  264. }
  265. out := map[string]string{}
  266. for _, p := range bySec {
  267. if p.name == "" {
  268. continue
  269. }
  270. if p.pub != "" {
  271. out[p.pub] = p.name
  272. }
  273. if ip := p.ip; ip != "" {
  274. if i := strings.Index(ip, "/"); i >= 0 {
  275. ip = ip[:i]
  276. }
  277. if ip != "" {
  278. out[ip] = p.name
  279. }
  280. }
  281. }
  282. return out
  283. }
  284. // WGPeerKey devuelve el identificador ESTABLE y apto para URL de un peer
  285. // WireGuard (#1441): la clave pública en base64url sin padding (43 chars).
  286. // Es el único dato que identifica al peer entre sondeos y reinicios: WGPeer.ID
  287. // sale del device de NetPulse que casó por IP del túnel o, si no hay ninguno,
  288. // del índice del dump ("peer-3"), que cambia al reordenar los peers.
  289. // base64url porque una pubkey WireGuard lleva '+' y '/' (base64 estándar) y
  290. // esos caracteres rompen el path del endpoint de urgencia.
  291. func WGPeerKey(pubkey string) string {
  292. pk := strings.TrimSpace(pubkey)
  293. if pk == "" {
  294. return ""
  295. }
  296. raw, err := base64.StdEncoding.DecodeString(pk)
  297. if err != nil {
  298. // Pubkey no estándar (dump de AmneziaWG o firmware raro): se
  299. // translitera a mano en vez de descartarla.
  300. return strings.NewReplacer("+", "-", "/", "_", "=", "").Replace(pk)
  301. }
  302. return base64.RawURLEncoding.EncodeToString(raw)
  303. }
  304. // buildWGPeer convierte un peer del dump en un WGPeer, resolviendo el nombre
  305. // con la prioridad de siempre (nombre de device NetPulse → description UCI →
  306. // nombre del config wireguard_server (GL.iNet) → tunnelIP → "Peer <pubkey8>",
  307. // issues #659/#1433) y asignando el fallback de ID
  308. // "peer-<idx>" con un contador global (idx) para que los peers de varias
  309. // interfaces no colisionen (#713). urgent (#1441): claves de peer marcadas
  310. // como importantes, por Key y, como cortesía, por ID (las llamadas antiguas y
  311. // los tests construyen WGPeer sin Key).
  312. func buildWGPeer(p WGDumpPeer, peerNames map[string]WGPeerName, descs map[string]string, nowSec int64, idx int, urgent map[string]bool) WGPeer {
  313. tunnelIP := ""
  314. if parts := strings.Split(p.AllowedIPs, ","); len(parts) > 0 {
  315. tunnelIP = strings.Replace(parts[0], "/32", "", 1)
  316. }
  317. named, ok := peerNames[tunnelIP]
  318. if !ok {
  319. named = peerNames[p.Pubkey]
  320. }
  321. id := named.ID
  322. if id == "" {
  323. id = "peer-" + strconv.Itoa(idx)
  324. }
  325. name := named.Name
  326. if name == "" {
  327. name = descs[p.Pubkey]
  328. if name == "" {
  329. name = descs[tunnelIP]
  330. }
  331. if name == "" {
  332. name = tunnelIP
  333. if name == "" {
  334. name = "Peer " + p.Pubkey[:min(len(p.Pubkey), 8)]
  335. }
  336. }
  337. }
  338. typ := named.Type
  339. if typ == "" {
  340. typ = "desconocido"
  341. }
  342. active := p.HandshakeSec > 0 && nowSec-p.HandshakeSec < handshakeActiveSec
  343. lastHandshake := "nunca"
  344. if p.HandshakeSec > 0 {
  345. lastHandshake = relTime(p.HandshakeSec, nowSec)
  346. }
  347. key := WGPeerKey(p.Pubkey)
  348. return WGPeer{
  349. ID: id, Key: key, Name: name, Type: typ, TunnelIP: tunnelIP,
  350. Active: active, LastHandshake: lastHandshake,
  351. Rx: fmtBytes(float64(p.RxBytes)), Tx: fmtBytes(float64(p.TxBytes)),
  352. RxBytes: p.RxBytes, TxBytes: p.TxBytes,
  353. Urgent: urgent[key] || urgent[id],
  354. }
  355. }
  356. // GetWireGuardStats obtiene WireGuardStats del gateway vía SSH, agregando los
  357. // peers de TODAS las interfaces WireGuard del router (issue #713).
  358. // iface: filtro/override de interfaces a sondear ("auto"/vacío → descubrir
  359. // todas con `wg show interfaces`; valor → interfaz o lista separada por
  360. // comas). peerNames: mapa tunnelIp/pubkey → etiqueta opcional (nombre de
  361. // device). El nombre de cada peer se resuelve en este orden: nombre de device
  362. // de NetPulse (peerNames) → description del peer en UCI (OpenWrt) → name del
  363. // config wireguard_server (GL.iNet, issue #1433) → IP del túnel →
  364. // "Peer <pubkey8>" (issue #659).
  365. //
  366. // Tolerancia a fallos (#714): el fallo del dump de UNA interfaz se salta (se
  367. // acumulan los peers de las que responden); si TODAS fallan se devuelve
  368. // Status "inactive" SIN error, para que pollWireGuard no loguee "no
  369. // disponible" en cada tick.
  370. //
  371. // urgent (#1441): conjunto de claves de peer (WGPeer.Key) marcadas como
  372. // importantes por el admin; se estampa en cada WGPeer para que el mapa y las
  373. // alertas sepan a quién tratar distinto. nil = ninguno.
  374. func GetWireGuardStats(pool sshRunner, host, iface, subnet string, peerNames map[string]WGPeerName, urgent map[string]bool) (*WireGuardStats, error) {
  375. ifaces := wgInterfaces(pool, host, iface)
  376. stats := &WireGuardStats{
  377. Interface: strings.Join(ifaces, ", "),
  378. Subnet: subnet,
  379. Status: "active", // quirk: siempre que el comando responda
  380. Peers: []WGPeer{},
  381. }
  382. if len(ifaces) == 0 {
  383. // Sin interfaces WireGuard en el router: no hay túneles que sondear.
  384. stats.Status = "inactive"
  385. return stats, nil
  386. }
  387. nowSec := time.Now().Unix()
  388. descs := map[string]string{}
  389. idx := 1
  390. ok := 0
  391. var sumRx, sumTx int64
  392. for _, ifc := range ifaces {
  393. out, err := pool.Run(host, wgStatsCommand(ifc), 0)
  394. if err != nil {
  395. // La interfaz puede ser AmneziaWG (`wg` no la ve; #776): se
  396. // reintenta con `awg` antes de saltarla.
  397. out, err = pool.Run(host, awgStatsCommand(ifc), 0)
  398. if err != nil {
  399. // Una interfaz caída no tumba el resto: se salta (#714).
  400. continue
  401. }
  402. }
  403. ok++
  404. dump, uci, gl := splitWGParts(out)
  405. // Nombres del config wireguard_server (GL.iNet) como base; la
  406. // description UCI estándar (network.*) pisa a la de GL cuando ambas
  407. // existen para la misma clave.
  408. for k, v := range parseWGServerNames(gl) {
  409. descs[k] = v
  410. }
  411. for k, v := range parseWGUciDescs(uci) {
  412. descs[k] = v
  413. }
  414. for _, p := range ParseWGDump(dump) {
  415. stats.Peers = append(stats.Peers, buildWGPeer(p, peerNames, descs, nowSec, idx, urgent))
  416. // #2017: el total del túnel es la suma de los contadores por peer
  417. // (todas las interfaces), que es el único dato real que expone
  418. // WireGuard. Los contadores de la interfaz en /proc/net/dev no se
  419. // mueven con el tráfico, así que no sirven de fuente.
  420. sumRx += p.RxBytes
  421. sumTx += p.TxBytes
  422. idx++
  423. }
  424. }
  425. if ok == 0 {
  426. // Ninguna interfaz respondió: túnel inactivo, sin error (#714).
  427. stats.Status = "inactive"
  428. }
  429. if len(stats.Peers) > 0 {
  430. stats.Transfer = &WGTransfer{Rx: fmtBytes(float64(sumRx)), Tx: fmtBytes(float64(sumTx))}
  431. }
  432. return stats, nil
  433. }