socks_config.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package amneziawgnet
  2. import (
  3. "crypto/rand"
  4. "encoding/base64"
  5. "fmt"
  6. "sync"
  7. )
  8. // SOCKSBasePort is the first loopback port used for an AmneziaWG inbound's
  9. // own Xray SOCKS5 relay inbound (see relay.go/SocksInboundSettings).
  10. const SOCKSBasePort = 65100
  11. // SOCKSPortForInbound derives one inbound's loopback SOCKS5 relay port from
  12. // its id, so config generation and the dialing relay never need to negotiate.
  13. func SOCKSPortForInbound(inboundID int) int {
  14. return SOCKSBasePort + inboundID
  15. }
  16. var (
  17. socksPasswordOnce sync.Once
  18. socksPassword string
  19. )
  20. // SocksPassword returns the process-wide password used to authenticate into
  21. // every AmneziaWG SOCKS5 relay inbound, generating and caching it once
  22. // (lazily, on first use) rather than persisting it anywhere: this traffic
  23. // never leaves loopback, both the config generator (SocksInboundSettings'
  24. // caller) and the relay dialer (SocksRelay/UDPRelay) live in this same
  25. // process, and Xray's own generated config is already rebuilt from scratch
  26. // on every reconcile -- there is nothing for a stored value to survive
  27. // across that a fresh one wouldn't equally satisfy. Not a real secret (see
  28. // SocksRelay's own doc comment); this only needs to be unpredictable enough
  29. // that nothing outside this process could plausibly guess it and dial in
  30. // over loopback.
  31. func SocksPassword() string {
  32. socksPasswordOnce.Do(func() {
  33. var b [24]byte
  34. if _, err := rand.Read(b[:]); err != nil {
  35. // crypto/rand failing is effectively unrecoverable for a
  36. // process that generates real WireGuard keys elsewhere too;
  37. // a fixed fallback keeps this from panicking outright.
  38. socksPassword = fmt.Sprintf("amneziawgnet-fallback-%x", b)
  39. return
  40. }
  41. socksPassword = base64.RawURLEncoding.EncodeToString(b[:])
  42. })
  43. return socksPassword
  44. }