adguard_glinet.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // adguard_glinet.go — Cliente AdGuard Home en firmware GL.iNet (port EXACTO
  2. // de src/adapters/adguard-glinet.js, SPEC §7.4 — algoritmo gl-ngx-session):
  3. //
  4. // - La API (puerto 3000) exige cookie `Admin-Token` = sesión de la UI GL.
  5. // - Login GL: challenge (nonce+salt+alg) → hash calculado EN el router vía
  6. // SSH root (`openssl passwd -<alg> -salt <salt> <pass>` →
  7. // sha256("<user>:<pw>:<nonce>") → ubus gl-session login) → sid.
  8. // - La contraseña viaja embebida con escaping de comillas simples (BusyBox
  9. // del GL NO tiene base64); NUNCA se incluye el comando en los errores.
  10. // - Cooldown de 15 min tras fallo de login (el GL bloquea tras N intentos).
  11. // - El sid se cachea y se renueva al primer 401.
  12. package adapters
  13. import (
  14. "context"
  15. "encoding/json"
  16. "fmt"
  17. "io"
  18. "math"
  19. "net/http"
  20. "regexp"
  21. "strings"
  22. "sync"
  23. "time"
  24. )
  25. const (
  26. glSSHTimeout = 8 * time.Second
  27. glHTTPTimeout = 4 * time.Second
  28. glLoginCooldown = 15 * time.Minute // el GL bloquea logins tras N fallos
  29. )
  30. // AdGuardGlinetClient es el cliente GL.iNet (host, user, pass + pool SSH).
  31. type AdGuardGlinetClient struct {
  32. Host string
  33. User string
  34. Pass string
  35. pool *SSHPool
  36. mu sync.Mutex
  37. sid string
  38. loginFailUntil time.Time
  39. hc *http.Client
  40. }
  41. // NewAdGuardGlinetClient crea el cliente GL (host, user/pass de la UI GL).
  42. func NewAdGuardGlinetClient(host, user, pass string, pool *SSHPool) *AdGuardGlinetClient {
  43. return &AdGuardGlinetClient{
  44. Host: host, User: user, Pass: pass, pool: pool,
  45. hc: &http.Client{Timeout: glHTTPTimeout},
  46. }
  47. }
  48. // Login ejecuta el flujo gl-ngx-session completo EN el router → sid.
  49. // Literal del JS (adguard-glinet.js:49-81).
  50. func (c *AdGuardGlinetClient) Login() (string, error) {
  51. c.mu.Lock()
  52. defer c.mu.Unlock()
  53. // Cooldown tras fallo: el GL bloquea logins tras N intentos (600 s)
  54. if time.Now().Before(c.loginFailUntil) {
  55. return "", fmt.Errorf("login GL en cooldown (%d s)",
  56. int(math.Ceil(time.Until(c.loginFailUntil).Seconds())))
  57. }
  58. // Contraseña embebida con escaping de comillas simples (BusyBox del GL
  59. // NO tiene base64). El resto del flujo va entre comillas dobles seguro.
  60. esc := strings.ReplaceAll(c.Pass, `'`, `'\''`)
  61. script := strings.Join([]string{
  62. `PASS='` + esc + `'`,
  63. `RESP=$(ubus call gl-session challenge '{"username":"` + c.User + `"}')`,
  64. `NONCE=$(jsonfilter -s "$RESP" -e '@.data.nonce')`,
  65. `SALT=$(jsonfilter -s "$RESP" -e '@.data.salt')`,
  66. `ALG=$(jsonfilter -s "$RESP" -e '@.data.alg')`,
  67. `PW=$(openssl passwd -$ALG -salt "$SALT" "$PASS")`,
  68. `HASH=$(echo -n "` + c.User + `:$PW:$NONCE" | sha256sum | cut -d' ' -f1)`,
  69. `RESP2=$(ubus call gl-session login '{"username":"` + c.User + `","hash":"'$HASH'"}')`,
  70. `SID=$(jsonfilter -s "$RESP2" -e '@.data.sid')`,
  71. `echo "SID:$SID"`,
  72. }, " && ")
  73. out, err := c.pool.Run(c.Host, script, glSSHTimeout)
  74. if err != nil {
  75. // NUNCA incluir el comando (lleva la contraseña embebida)
  76. c.loginFailUntil = time.Now().Add(glLoginCooldown)
  77. return "", err
  78. }
  79. m := regexp.MustCompile(`(?m)^SID:(\S+)$`).FindStringSubmatch(out)
  80. if m == nil {
  81. c.loginFailUntil = time.Now().Add(glLoginCooldown)
  82. return "", fmt.Errorf("GL login failed (check the UI username/password)")
  83. }
  84. c.loginFailUntil = time.Time{}
  85. c.sid = m[1]
  86. return c.sid, nil
  87. }
  88. var errGL401 = fmt.Errorf("401 unauthorized")
  89. // glGet: GET http://<host>:3000/control/<path> con cookie Admin-Token.
  90. func (c *AdGuardGlinetClient) glGet(ctx context.Context, path string, dst any) error {
  91. req, err := http.NewRequestWithContext(ctx, "GET", "http://"+c.Host+":3000/control/"+path, nil)
  92. if err != nil {
  93. return err
  94. }
  95. c.mu.Lock()
  96. sid := c.sid
  97. c.mu.Unlock()
  98. req.Header.Set("Cookie", "Admin-Token="+sid)
  99. res, err := c.hc.Do(req)
  100. if err != nil {
  101. return err
  102. }
  103. defer res.Body.Close()
  104. if res.StatusCode == 401 {
  105. return errGL401
  106. }
  107. if res.StatusCode != 200 {
  108. return fmt.Errorf("HTTP %d", res.StatusCode)
  109. }
  110. return json.NewDecoder(io.LimitReader(res.Body, 4<<20)).Decode(dst)
  111. }
  112. // queryStats: /control/stats con el sid actual.
  113. func (c *AdGuardGlinetClient) queryStats(ctx context.Context) (*AdGuardStats, error) {
  114. var data struct {
  115. NumDNSQueries int64 `json:"num_dns_queries"`
  116. NumBlockedFiltering int64 `json:"num_blocked_filtering"`
  117. AvgProcessingTime float64 `json:"avg_processing_time"`
  118. TopBlockedDomains json.RawMessage `json:"top_blocked_domains"`
  119. TopClients json.RawMessage `json:"top_clients"`
  120. }
  121. if err := c.glGet(ctx, "stats", &data); err != nil {
  122. return nil, err
  123. }
  124. total := data.NumDNSQueries
  125. blocked := data.NumBlockedFiltering
  126. blockedPct := 0.0
  127. if total > 0 {
  128. blockedPct = math.Round(float64(blocked)/float64(total)*100*10) / 10
  129. }
  130. clients := 0
  131. if len(data.TopClients) > 0 {
  132. var tc []any
  133. if json.Unmarshal(data.TopClients, &tc) == nil {
  134. clients = len(tc)
  135. }
  136. }
  137. // GL: top_blocked_domains siempre [{domain: count}] (como el JS)
  138. top := []TopBlocked{}
  139. var arr []json.RawMessage
  140. if json.Unmarshal(data.TopBlockedDomains, &arr) == nil {
  141. for i, item := range arr {
  142. if i >= 5 {
  143. break
  144. }
  145. var m map[string]int64
  146. if json.Unmarshal(item, &m) == nil {
  147. for k, v := range m {
  148. top = append(top, TopBlocked{Domain: k, Count: v})
  149. break
  150. }
  151. }
  152. }
  153. }
  154. return &AdGuardStats{
  155. Host: c.Host, Port: 3000, Status: "active",
  156. Queries24h: total, Blocked24h: blocked, BlockedPct: blockedPct,
  157. TrackersBlocked: 0,
  158. DNSLatencyMs: int(math.Round(data.AvgProcessingTime * 1000)),
  159. ClientsUsing: clients, ClientsTotal: clients,
  160. TopBlocked: top,
  161. FilterLists: 0, Rules: 0,
  162. }, nil
  163. }
  164. // GetStats: stats con login/relogin automático (401 → re-login una vez).
  165. func (c *AdGuardGlinetClient) GetStats(ctx context.Context) (*AdGuardStats, error) {
  166. ctx, cancel := context.WithTimeout(ctx, glHTTPTimeout+glSSHTimeout)
  167. defer cancel()
  168. c.mu.Lock()
  169. hasSid := c.sid != ""
  170. c.mu.Unlock()
  171. if !hasSid {
  172. if _, err := c.Login(); err != nil {
  173. return nil, err
  174. }
  175. }
  176. stats, err := c.queryStats(ctx)
  177. if err == nil {
  178. return stats, nil
  179. }
  180. if err != errGL401 {
  181. return nil, err
  182. }
  183. c.mu.Lock()
  184. c.sid = ""
  185. c.mu.Unlock()
  186. if _, lerr := c.Login(); lerr != nil {
  187. return nil, lerr
  188. }
  189. return c.queryStats(ctx)
  190. }
  191. // QueryClients: /control/clients con login automático (paridad del JS:
  192. // ante 401 re-login y reintento).
  193. func (c *AdGuardGlinetClient) QueryClients(ctx context.Context) ([]AdguardClient, error) {
  194. ctx, cancel := context.WithTimeout(ctx, glHTTPTimeout+glSSHTimeout)
  195. defer cancel()
  196. c.mu.Lock()
  197. hasSid := c.sid != ""
  198. c.mu.Unlock()
  199. if !hasSid {
  200. if _, err := c.Login(); err != nil {
  201. return nil, err
  202. }
  203. }
  204. var data struct {
  205. Clients []struct {
  206. Name string `json:"name"`
  207. IDs []string `json:"ids"`
  208. UseGlobalSettings bool `json:"use_global_settings"`
  209. BlockedServices []string `json:"blocked_services"`
  210. } `json:"clients"`
  211. }
  212. err := c.glGet(ctx, "clients", &data)
  213. if err == errGL401 {
  214. c.mu.Lock()
  215. c.sid = ""
  216. c.mu.Unlock()
  217. if _, lerr := c.Login(); lerr != nil {
  218. return nil, lerr
  219. }
  220. err = c.glGet(ctx, "clients", &data)
  221. }
  222. if err != nil {
  223. return nil, err
  224. }
  225. out := make([]AdguardClient, 0, len(data.Clients))
  226. for _, cl := range data.Clients {
  227. name := cl.Name
  228. ip := ""
  229. if len(cl.IDs) > 0 {
  230. if name == "" {
  231. name = cl.IDs[0]
  232. }
  233. ip = cl.IDs[0]
  234. }
  235. out = append(out, AdguardClient{
  236. Name: name, IP: ip,
  237. UseGlobalSettings: cl.UseGlobalSettings,
  238. BlockedServices: len(cl.BlockedServices),
  239. })
  240. }
  241. return out, nil
  242. }