l2tp.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package vpn
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "strings"
  10. "sync"
  11. "syscall"
  12. "github.com/vishvananda/netlink"
  13. )
  14. const (
  15. L2TPInstancesStorePath = "/etc/debtik/vpn/l2tp_instances.json"
  16. Xl2tpdConfigPath = "/etc/xl2tpd/xl2tpd.conf"
  17. L2TPControlFIFO = "/var/run/xl2tpd/l2tp-control"
  18. )
  19. type L2TPManager struct {
  20. mu sync.Mutex
  21. instances []L2TPInstance
  22. pppServer *PPPServerManager
  23. }
  24. func NewL2TPManager() *L2TPManager {
  25. m := &L2TPManager{
  26. instances: make([]L2TPInstance, 0),
  27. }
  28. m.load()
  29. return m
  30. }
  31. func (m *L2TPManager) SetPPPServer(ps *PPPServerManager) {
  32. m.pppServer = ps
  33. }
  34. func (m *L2TPManager) load() {
  35. data, err := os.ReadFile(L2TPInstancesStorePath)
  36. if err == nil {
  37. _ = json.Unmarshal(data, &m.instances)
  38. }
  39. if m.instances == nil {
  40. m.instances = make([]L2TPInstance, 0)
  41. }
  42. }
  43. func (m *L2TPManager) save() error {
  44. _ = os.MkdirAll(filepath.Dir(L2TPInstancesStorePath), 0755)
  45. data, err := json.MarshalIndent(m.instances, "", " ")
  46. if err != nil {
  47. return err
  48. }
  49. return os.WriteFile(L2TPInstancesStorePath, data, 0600)
  50. }
  51. func (m *L2TPManager) List() []L2TPInstance {
  52. m.mu.Lock()
  53. defer m.mu.Unlock()
  54. m.refreshRuntimeStatus()
  55. res := make([]L2TPInstance, len(m.instances))
  56. copy(res, m.instances)
  57. return res
  58. }
  59. func (m *L2TPManager) Save(inst L2TPInstance) error {
  60. m.mu.Lock()
  61. defer m.mu.Unlock()
  62. if inst.Name == "" {
  63. return fmt.Errorf("instance name is required (e.g. l2tp-out1)")
  64. }
  65. if inst.ConnectTo == "" {
  66. return fmt.Errorf("server address (connect-to) is required")
  67. }
  68. if inst.Profile == "" {
  69. inst.Profile = "default-encryption"
  70. }
  71. found := false
  72. for i, existing := range m.instances {
  73. if existing.Name == inst.Name {
  74. m.instances[i] = inst
  75. found = true
  76. break
  77. }
  78. }
  79. if !found {
  80. m.instances = append(m.instances, inst)
  81. }
  82. if err := m.save(); err != nil {
  83. return err
  84. }
  85. if err := m.regenerateXl2tpdConf(); err != nil {
  86. return err
  87. }
  88. if !inst.Disabled {
  89. return m.connectInstance(inst.Name)
  90. } else {
  91. return m.disconnectInstance(inst.Name)
  92. }
  93. }
  94. func (m *L2TPManager) Delete(name string) error {
  95. m.mu.Lock()
  96. defer m.mu.Unlock()
  97. _ = m.disconnectInstance(name)
  98. updated := make([]L2TPInstance, 0)
  99. for _, inst := range m.instances {
  100. if inst.Name != name {
  101. updated = append(updated, inst)
  102. }
  103. }
  104. m.instances = updated
  105. if err := m.save(); err != nil {
  106. return err
  107. }
  108. return m.regenerateXl2tpdConf()
  109. }
  110. func (m *L2TPManager) SetEnabled(name string, enabled bool) error {
  111. m.mu.Lock()
  112. defer m.mu.Unlock()
  113. for i, inst := range m.instances {
  114. if inst.Name == name {
  115. m.instances[i].Disabled = !enabled
  116. if err := m.save(); err != nil {
  117. return err
  118. }
  119. if enabled {
  120. return m.connectInstance(name)
  121. } else {
  122. return m.disconnectInstance(name)
  123. }
  124. }
  125. }
  126. return fmt.Errorf("instance %q not found", name)
  127. }
  128. func (m *L2TPManager) Connect(name string) error {
  129. m.mu.Lock()
  130. defer m.mu.Unlock()
  131. return m.connectInstance(name)
  132. }
  133. func (m *L2TPManager) Disconnect(name string) error {
  134. m.mu.Lock()
  135. defer m.mu.Unlock()
  136. return m.disconnectInstance(name)
  137. }
  138. func (m *L2TPManager) regenerateXl2tpdConf() error {
  139. _ = os.MkdirAll("/etc/xl2tpd", 0755)
  140. _ = os.MkdirAll("/var/run/xl2tpd", 0755)
  141. var sb strings.Builder
  142. sb.WriteString("[global]\n")
  143. sb.WriteString("port = 1701\n\n")
  144. for _, inst := range m.instances {
  145. prof := inst.Profile
  146. if prof == "" {
  147. prof = "default-encryption"
  148. }
  149. var profObj *PPPProfile
  150. if m.pppServer != nil {
  151. profObj = m.pppServer.GetProfile(prof)
  152. }
  153. optFile := fmt.Sprintf("/etc/ppp/options.l2tpd.%s", inst.Name)
  154. sb.WriteString(fmt.Sprintf("[lac %s]\n", inst.Name))
  155. sb.WriteString(fmt.Sprintf("lns = %s\n", inst.ConnectTo))
  156. sb.WriteString("ppp debug = yes\n")
  157. sb.WriteString(fmt.Sprintf("pppoptfile = %s\n", optFile))
  158. sb.WriteString("length bit = yes\n")
  159. sb.WriteString("redial = yes\n\n")
  160. // Create individual options file
  161. var optSb strings.Builder
  162. optSb.WriteString(fmt.Sprintf("# L2TP Client: %s (Profile: %s)\n", inst.Name, prof))
  163. optSb.WriteString(fmt.Sprintf("name %q\n", inst.Username))
  164. optSb.WriteString(fmt.Sprintf("password %q\n", inst.Password))
  165. optSb.WriteString("ipcp-accept-local\n")
  166. optSb.WriteString("ipcp-accept-remote\n")
  167. optSb.WriteString("refuse-eap\n")
  168. optSb.WriteString("require-mschap-v2\n")
  169. if profObj != nil {
  170. switch strings.ToLower(profObj.UseEncryption) {
  171. case "no":
  172. optSb.WriteString("nomppe\n")
  173. case "yes":
  174. optSb.WriteString("mppe-128\n")
  175. default:
  176. optSb.WriteString("require-mppe-128\n")
  177. }
  178. if profObj.DNSServers != "" {
  179. for _, dns := range strings.Split(profObj.DNSServers, ",") {
  180. dns = strings.TrimSpace(dns)
  181. if dns != "" {
  182. optSb.WriteString(fmt.Sprintf("ms-dns %s\n", dns))
  183. }
  184. }
  185. }
  186. if profObj.LocalAddress != "" && profObj.RemoteAddress != "" {
  187. local := strings.TrimSpace(profObj.LocalAddress)
  188. remote := strings.TrimSpace(profObj.RemoteAddress)
  189. if strings.Contains(remote, "-") {
  190. remote = strings.TrimSpace(strings.Split(remote, "-")[0])
  191. }
  192. if local != "" && remote != "" {
  193. optSb.WriteString(fmt.Sprintf("%s:%s\n", local, remote))
  194. }
  195. }
  196. } else {
  197. if strings.EqualFold(prof, "default") {
  198. optSb.WriteString("nomppe\n")
  199. } else {
  200. optSb.WriteString("require-mppe-128\n")
  201. }
  202. }
  203. optSb.WriteString("noccp\n")
  204. optSb.WriteString("noauth\n")
  205. optSb.WriteString("mtu 1410\n")
  206. optSb.WriteString("mru 1410\n")
  207. if inst.DefaultRoute {
  208. optSb.WriteString("defaultroute\n")
  209. optSb.WriteString("replacedefaultroute\n")
  210. }
  211. _ = os.WriteFile(optFile, []byte(optSb.String()), 0600)
  212. }
  213. if err := os.WriteFile(Xl2tpdConfigPath, []byte(sb.String()), 0600); err != nil {
  214. return err
  215. }
  216. if err := exec.Command("systemctl", "restart", "xl2tpd").Run(); err != nil {
  217. return err
  218. }
  219. return nil
  220. }
  221. func writeL2TPControl(command, name string) error {
  222. f, err := os.OpenFile(L2TPControlFIFO, os.O_WRONLY|syscall.O_NONBLOCK, 0600)
  223. if err != nil {
  224. return fmt.Errorf("L2TP control unavailable: %w", err)
  225. }
  226. defer f.Close()
  227. _, err = fmt.Fprintf(f, "%s %s\n", command, name)
  228. return err
  229. }
  230. func (m *L2TPManager) connectInstance(name string) error { return writeL2TPControl("c", name) }
  231. func (m *L2TPManager) disconnectInstance(name string) error { return writeL2TPControl("d", name) }
  232. func (m *L2TPManager) refreshRuntimeStatus() {
  233. psOut, _ := exec.Command("ps", "-ef").Output()
  234. psStr := string(psOut)
  235. links, _ := netlink.LinkList()
  236. for i := range m.instances {
  237. name := m.instances[i].Name
  238. if strings.Contains(psStr, name) || strings.Contains(psStr, "xl2tpd") {
  239. m.instances[i].Running = true
  240. } else {
  241. m.instances[i].Running = false
  242. }
  243. m.instances[i].AssignedIP = ""
  244. m.instances[i].PPPDevice = ""
  245. for _, l := range links {
  246. if strings.HasPrefix(l.Attrs().Name, "ppp") && l.Attrs().Flags&net.FlagUp != 0 {
  247. addrs, _ := netlink.AddrList(l, netlink.FAMILY_V4)
  248. if len(addrs) > 0 {
  249. m.instances[i].AssignedIP = addrs[0].IPNet.String()
  250. m.instances[i].PPPDevice = l.Attrs().Name
  251. m.instances[i].Running = true
  252. break
  253. }
  254. }
  255. }
  256. }
  257. }