l2tp.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. "time"
  12. "github.com/vishvananda/netlink"
  13. )
  14. const (
  15. L2TPInstancesStorePath = "/etc/proxmox-router/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. go m.connectInstance(inst.Name)
  90. } else {
  91. go m.disconnectInstance(inst.Name)
  92. }
  93. return nil
  94. }
  95. func (m *L2TPManager) Delete(name string) error {
  96. m.mu.Lock()
  97. defer m.mu.Unlock()
  98. _ = m.disconnectInstance(name)
  99. updated := make([]L2TPInstance, 0)
  100. for _, inst := range m.instances {
  101. if inst.Name != name {
  102. updated = append(updated, inst)
  103. }
  104. }
  105. m.instances = updated
  106. _ = m.save()
  107. return m.regenerateXl2tpdConf()
  108. }
  109. func (m *L2TPManager) SetEnabled(name string, enabled bool) error {
  110. m.mu.Lock()
  111. defer m.mu.Unlock()
  112. for i, inst := range m.instances {
  113. if inst.Name == name {
  114. m.instances[i].Disabled = !enabled
  115. _ = m.save()
  116. if enabled {
  117. go m.connectInstance(name)
  118. } else {
  119. go m.disconnectInstance(name)
  120. }
  121. return nil
  122. }
  123. }
  124. return fmt.Errorf("instance %q not found", name)
  125. }
  126. func (m *L2TPManager) Connect(name string) error {
  127. m.mu.Lock()
  128. defer m.mu.Unlock()
  129. return m.connectInstance(name)
  130. }
  131. func (m *L2TPManager) Disconnect(name string) error {
  132. m.mu.Lock()
  133. defer m.mu.Unlock()
  134. return m.disconnectInstance(name)
  135. }
  136. func (m *L2TPManager) regenerateXl2tpdConf() error {
  137. _ = os.MkdirAll("/etc/xl2tpd", 0755)
  138. _ = os.MkdirAll("/var/run/xl2tpd", 0755)
  139. var sb strings.Builder
  140. sb.WriteString("[global]\n")
  141. sb.WriteString("port = 1701\n\n")
  142. for _, inst := range m.instances {
  143. prof := inst.Profile
  144. if prof == "" {
  145. prof = "default-encryption"
  146. }
  147. var profObj *PPPProfile
  148. if m.pppServer != nil {
  149. profObj = m.pppServer.GetProfile(prof)
  150. }
  151. optFile := fmt.Sprintf("/etc/ppp/options.l2tpd.%s", inst.Name)
  152. sb.WriteString(fmt.Sprintf("[lac %s]\n", inst.Name))
  153. sb.WriteString(fmt.Sprintf("lns = %s\n", inst.ConnectTo))
  154. sb.WriteString("ppp debug = yes\n")
  155. sb.WriteString(fmt.Sprintf("pppoptfile = %s\n", optFile))
  156. sb.WriteString("length bit = yes\n")
  157. sb.WriteString("redial = yes\n\n")
  158. // Create individual options file
  159. var optSb strings.Builder
  160. optSb.WriteString(fmt.Sprintf("# L2TP Client: %s (Profile: %s)\n", inst.Name, prof))
  161. optSb.WriteString(fmt.Sprintf("name %q\n", inst.Username))
  162. optSb.WriteString(fmt.Sprintf("password %q\n", inst.Password))
  163. optSb.WriteString("ipcp-accept-local\n")
  164. optSb.WriteString("ipcp-accept-remote\n")
  165. optSb.WriteString("refuse-eap\n")
  166. optSb.WriteString("require-mschap-v2\n")
  167. if profObj != nil {
  168. switch strings.ToLower(profObj.UseEncryption) {
  169. case "no":
  170. optSb.WriteString("nomppe\n")
  171. case "yes":
  172. optSb.WriteString("mppe-128\n")
  173. default:
  174. optSb.WriteString("require-mppe-128\n")
  175. }
  176. if profObj.DNSServers != "" {
  177. for _, dns := range strings.Split(profObj.DNSServers, ",") {
  178. dns = strings.TrimSpace(dns)
  179. if dns != "" {
  180. optSb.WriteString(fmt.Sprintf("ms-dns %s\n", dns))
  181. }
  182. }
  183. }
  184. if profObj.LocalAddress != "" && profObj.RemoteAddress != "" {
  185. local := strings.TrimSpace(profObj.LocalAddress)
  186. remote := strings.TrimSpace(profObj.RemoteAddress)
  187. if strings.Contains(remote, "-") {
  188. remote = strings.TrimSpace(strings.Split(remote, "-")[0])
  189. }
  190. if local != "" && remote != "" {
  191. optSb.WriteString(fmt.Sprintf("%s:%s\n", local, remote))
  192. }
  193. }
  194. } else {
  195. if strings.EqualFold(prof, "default") {
  196. optSb.WriteString("nomppe\n")
  197. } else {
  198. optSb.WriteString("require-mppe-128\n")
  199. }
  200. }
  201. optSb.WriteString("noccp\n")
  202. optSb.WriteString("noauth\n")
  203. optSb.WriteString("mtu 1410\n")
  204. optSb.WriteString("mru 1410\n")
  205. if inst.DefaultRoute {
  206. optSb.WriteString("defaultroute\n")
  207. optSb.WriteString("replacedefaultroute\n")
  208. }
  209. _ = os.WriteFile(optFile, []byte(optSb.String()), 0600)
  210. }
  211. if err := os.WriteFile(Xl2tpdConfigPath, []byte(sb.String()), 0600); err != nil {
  212. return err
  213. }
  214. _ = exec.Command("systemctl", "restart", "xl2tpd").Run()
  215. return nil
  216. }
  217. func (m *L2TPManager) connectInstance(name string) error {
  218. time.Sleep(300 * time.Millisecond)
  219. if _, err := os.Stat(L2TPControlFIFO); err == nil {
  220. f, err := os.OpenFile(L2TPControlFIFO, os.O_WRONLY, 0600)
  221. if err == nil {
  222. _, _ = f.WriteString(fmt.Sprintf("c %s\n", name))
  223. _ = f.Close()
  224. }
  225. }
  226. return nil
  227. }
  228. func (m *L2TPManager) disconnectInstance(name string) error {
  229. if _, err := os.Stat(L2TPControlFIFO); err == nil {
  230. f, err := os.OpenFile(L2TPControlFIFO, os.O_WRONLY, 0600)
  231. if err == nil {
  232. _, _ = f.WriteString(fmt.Sprintf("d %s\n", name))
  233. _ = f.Close()
  234. }
  235. }
  236. return nil
  237. }
  238. func (m *L2TPManager) refreshRuntimeStatus() {
  239. psOut, _ := exec.Command("ps", "-ef").Output()
  240. psStr := string(psOut)
  241. links, _ := netlink.LinkList()
  242. for i := range m.instances {
  243. name := m.instances[i].Name
  244. if strings.Contains(psStr, name) || strings.Contains(psStr, "xl2tpd") {
  245. m.instances[i].Running = true
  246. } else {
  247. m.instances[i].Running = false
  248. }
  249. m.instances[i].AssignedIP = ""
  250. m.instances[i].PPPDevice = ""
  251. for _, l := range links {
  252. if strings.HasPrefix(l.Attrs().Name, "ppp") && l.Attrs().Flags&net.FlagUp != 0 {
  253. addrs, _ := netlink.AddrList(l, netlink.FAMILY_V4)
  254. if len(addrs) > 0 {
  255. m.instances[i].AssignedIP = addrs[0].IPNet.String()
  256. m.instances[i].PPPDevice = l.Attrs().Name
  257. m.instances[i].Running = true
  258. break
  259. }
  260. }
  261. }
  262. }
  263. }