ppp_server.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. package vpn
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "syscall"
  14. "time"
  15. )
  16. // ======================== PPP Profiles (/ppp profile) ========================
  17. type PPPProfile struct {
  18. ID string `json:"id"`
  19. Name string `json:"name"` // e.g. "default", "default-encryption", "pool-lan"
  20. LocalAddress string `json:"local_address"` // e.g. "10.10.10.1" (server IP on tunnel)
  21. RemoteAddress string `json:"remote_address"` // e.g. "10.10.10.10-10.10.10.50" or "10.10.10.10"
  22. DNSServers string `json:"dns_servers"` // e.g. "1.1.1.1,8.8.8.8"
  23. UseEncryption string `json:"use_encryption"` // "no", "yes", "required" (MPPE-128)
  24. OnlyOne bool `json:"only_one"` // One session per user
  25. Comment string `json:"comment,omitempty"`
  26. }
  27. // ======================== PPP Secrets (/ppp secret) ========================
  28. type PPPSecret struct {
  29. ID string `json:"id"`
  30. Name string `json:"name"` // Username
  31. Password string `json:"password"` // Password
  32. Service string `json:"service"` // "any", "pppoe", "pptp", "l2tp"
  33. Profile string `json:"profile"` // Profile name
  34. LocalAddress string `json:"local_address,omitempty"`
  35. RemoteAddress string `json:"remote_address,omitempty"`
  36. CallerID string `json:"caller_id,omitempty"`
  37. Comment string `json:"comment,omitempty"`
  38. Disabled bool `json:"disabled"`
  39. }
  40. // ======================== PPPoE Server (/interface pppoe-server server) ========================
  41. type PPPoEServerConfig struct {
  42. Enabled bool `json:"enabled"`
  43. ServiceName string `json:"service_name"` // e.g. "isp-service"
  44. Interface string `json:"interface"` // e.g. "eth0", "eth0.10", "br0"
  45. DefaultProfile string `json:"default_profile"`
  46. OneSessionPerHost bool `json:"one_session_per_host"`
  47. MaxMTU int `json:"max_mtu"` // default 1480 / 1492
  48. MaxMRU int `json:"max_mru"` // default 1480 / 1492
  49. Running bool `json:"running"`
  50. ActiveSessions int `json:"active_sessions"`
  51. LastError string `json:"last_error,omitempty"`
  52. }
  53. // ======================== PPTP Server (/interface pptp-server server) ========================
  54. type PPTPServerConfig struct {
  55. Enabled bool `json:"enabled"`
  56. Port int `json:"port"` // default 1723
  57. DefaultProfile string `json:"default_profile"`
  58. RequireMPPE bool `json:"require_mppe"` // 128-bit MPPE
  59. Running bool `json:"running"`
  60. ActiveSessions int `json:"active_sessions"`
  61. LastError string `json:"last_error,omitempty"`
  62. }
  63. // ======================== L2TP Server (/interface l2tp-server server) ========================
  64. type L2TPServerConfig struct {
  65. Enabled bool `json:"enabled"`
  66. Port int `json:"port"` // default 1701
  67. DefaultProfile string `json:"default_profile"`
  68. UseIPSec string `json:"use_ipsec"` // "no", "yes", "required"
  69. IPSecSecret string `json:"ipsec_secret,omitempty"`
  70. Running bool `json:"running"`
  71. ActiveSessions int `json:"active_sessions"`
  72. LastError string `json:"last_error,omitempty"`
  73. }
  74. // ======================== IPSec Roadwarrior Server ========================
  75. type IPSecServerConfig struct {
  76. Enabled bool `json:"enabled"`
  77. PoolAddress string `json:"pool_address"` // e.g. "10.10.30.0/24"
  78. PresharedKey string `json:"preshared_key"`
  79. LocalSubnet string `json:"local_subnet"` // e.g. "0.0.0.0/0"
  80. DNSServers string `json:"dns_servers"` // e.g. "1.1.1.1,8.8.8.8"
  81. Running bool `json:"running"`
  82. ActiveSessions int `json:"active_sessions"`
  83. LastError string `json:"last_error,omitempty"`
  84. }
  85. // ======================== Active PPP Session (/ppp active) ========================
  86. type ActivePPPSession struct {
  87. ID string `json:"id"`
  88. Interface string `json:"interface"` // e.g. "ppp0"
  89. Username string `json:"username"`
  90. Service string `json:"service"` // "pppoe", "pptp", "l2tp"
  91. CallerID string `json:"caller_id,omitempty"`
  92. Address string `json:"address"` // client assigned IP
  93. Uptime string `json:"uptime"`
  94. RxBytes uint64 `json:"rx_bytes"`
  95. TxBytes uint64 `json:"tx_bytes"`
  96. RxHuman string `json:"rx_human,omitempty"`
  97. TxHuman string `json:"tx_human,omitempty"`
  98. }
  99. // ======================== Central PPP & Server Manager ========================
  100. type PPPServerManager struct {
  101. mu sync.RWMutex
  102. baseDir string
  103. profiles map[string]*PPPProfile
  104. secrets map[string]*PPPSecret
  105. pppoeServer PPPoEServerConfig
  106. pptpServer PPTPServerConfig
  107. l2tpServer L2TPServerConfig
  108. ipsecServer IPSecServerConfig
  109. pppoePIDFile string
  110. }
  111. func NewPPPServerManager() *PPPServerManager {
  112. mgr := &PPPServerManager{
  113. baseDir: "/etc/proxmox-router/vpn",
  114. profiles: make(map[string]*PPPProfile),
  115. secrets: make(map[string]*PPPSecret),
  116. pppoePIDFile: "/var/run/proxmox-pppoe-server.pid",
  117. pppoeServer: PPPoEServerConfig{
  118. Enabled: false,
  119. ServiceName: "proxmox-pppoe",
  120. Interface: "eth0",
  121. DefaultProfile: "default",
  122. MaxMTU: 1480,
  123. MaxMRU: 1480,
  124. },
  125. pptpServer: PPTPServerConfig{
  126. Enabled: false,
  127. Port: 1723,
  128. DefaultProfile: "default-encryption",
  129. RequireMPPE: true,
  130. },
  131. l2tpServer: L2TPServerConfig{
  132. Enabled: false,
  133. Port: 1701,
  134. DefaultProfile: "default",
  135. UseIPSec: "no",
  136. },
  137. ipsecServer: IPSecServerConfig{
  138. Enabled: false,
  139. PoolAddress: "10.10.30.0/24",
  140. PresharedKey: "ProxmoxRouterSecret123",
  141. LocalSubnet: "0.0.0.0/0",
  142. DNSServers: "1.1.1.1,8.8.8.8",
  143. },
  144. }
  145. mgr.initDefaults()
  146. mgr.loadAll()
  147. mgr.SyncSecretsToSystem()
  148. mgr.applyAll()
  149. return mgr
  150. }
  151. func (m *PPPServerManager) initDefaults() {
  152. m.profiles["default"] = &PPPProfile{
  153. ID: "default",
  154. Name: "default",
  155. LocalAddress: "10.10.10.1",
  156. RemoteAddress: "10.10.10.10-10.10.10.50",
  157. DNSServers: "1.1.1.1,8.8.8.8",
  158. UseEncryption: "no",
  159. OnlyOne: true,
  160. Comment: "Default PPP profile for unencrypted/standard tunnels",
  161. }
  162. m.profiles["default-encryption"] = &PPPProfile{
  163. ID: "default-encryption",
  164. Name: "default-encryption",
  165. LocalAddress: "10.10.20.1",
  166. RemoteAddress: "10.10.20.10-10.10.20.50",
  167. DNSServers: "1.1.1.1,8.8.8.8",
  168. UseEncryption: "required",
  169. OnlyOne: true,
  170. Comment: "Default PPP profile with required MPPE-128 encryption",
  171. }
  172. }
  173. func (m *PPPServerManager) loadAll() {
  174. _ = os.MkdirAll(m.baseDir, 0755)
  175. // Profiles
  176. if data, err := os.ReadFile(filepath.Join(m.baseDir, "ppp_profiles.json")); err == nil {
  177. var list []*PPPProfile
  178. if err := json.Unmarshal(data, &list); err == nil {
  179. for _, p := range list {
  180. m.profiles[p.Name] = p
  181. }
  182. }
  183. }
  184. // Secrets
  185. if data, err := os.ReadFile(filepath.Join(m.baseDir, "ppp_secrets.json")); err == nil {
  186. var list []*PPPSecret
  187. if err := json.Unmarshal(data, &list); err == nil {
  188. for _, s := range list {
  189. m.secrets[s.ID] = s
  190. }
  191. }
  192. }
  193. // PPPoE Server
  194. if data, err := os.ReadFile(filepath.Join(m.baseDir, "pppoe_server.json")); err == nil {
  195. _ = json.Unmarshal(data, &m.pppoeServer)
  196. }
  197. // PPTP Server
  198. if data, err := os.ReadFile(filepath.Join(m.baseDir, "pptp_server.json")); err == nil {
  199. _ = json.Unmarshal(data, &m.pptpServer)
  200. }
  201. // L2TP Server
  202. if data, err := os.ReadFile(filepath.Join(m.baseDir, "l2tp_server.json")); err == nil {
  203. _ = json.Unmarshal(data, &m.l2tpServer)
  204. }
  205. // IPSec Server
  206. if data, err := os.ReadFile(filepath.Join(m.baseDir, "ipsec_server.json")); err == nil {
  207. _ = json.Unmarshal(data, &m.ipsecServer)
  208. }
  209. }
  210. func (m *PPPServerManager) save(filename string, v any) error {
  211. _ = os.MkdirAll(m.baseDir, 0755)
  212. data, err := json.MarshalIndent(v, "", " ")
  213. if err != nil {
  214. return err
  215. }
  216. return os.WriteFile(filepath.Join(m.baseDir, filename), data, 0644)
  217. }
  218. // ======================== PPP Profiles CRUD ========================
  219. func (m *PPPServerManager) ListProfiles() []*PPPProfile {
  220. m.mu.RLock()
  221. defer m.mu.RUnlock()
  222. list := make([]*PPPProfile, 0)
  223. for _, p := range m.profiles {
  224. list = append(list, p)
  225. }
  226. return list
  227. }
  228. func (m *PPPServerManager) GetProfile(name string) *PPPProfile {
  229. m.mu.RLock()
  230. defer m.mu.RUnlock()
  231. return m.profiles[name]
  232. }
  233. func (m *PPPServerManager) SaveProfile(p *PPPProfile) error {
  234. m.mu.Lock()
  235. defer m.mu.Unlock()
  236. if p.Name == "" {
  237. return fmt.Errorf("profile name is required")
  238. }
  239. if p.LocalAddress == "" {
  240. p.LocalAddress = "10.10.10.1"
  241. }
  242. if p.RemoteAddress == "" {
  243. p.RemoteAddress = "10.10.10.10-10.10.10.50"
  244. }
  245. if p.ID == "" {
  246. p.ID = p.Name
  247. }
  248. m.profiles[p.Name] = p
  249. var list []*PPPProfile
  250. for _, pr := range m.profiles {
  251. list = append(list, pr)
  252. }
  253. return m.save("ppp_profiles.json", list)
  254. }
  255. func (m *PPPServerManager) DeleteProfile(name string) error {
  256. m.mu.Lock()
  257. defer m.mu.Unlock()
  258. if name == "default" || name == "default-encryption" {
  259. return fmt.Errorf("cannot delete default profile")
  260. }
  261. delete(m.profiles, name)
  262. var list []*PPPProfile
  263. for _, pr := range m.profiles {
  264. list = append(list, pr)
  265. }
  266. return m.save("ppp_profiles.json", list)
  267. }
  268. // ======================== PPP Secrets CRUD ========================
  269. func (m *PPPServerManager) ListSecrets() []*PPPSecret {
  270. m.mu.RLock()
  271. defer m.mu.RUnlock()
  272. list := make([]*PPPSecret, 0)
  273. for _, s := range m.secrets {
  274. list = append(list, s)
  275. }
  276. return list
  277. }
  278. func (m *PPPServerManager) SaveSecret(s *PPPSecret) error {
  279. m.mu.Lock()
  280. defer m.mu.Unlock()
  281. if s.Name == "" || s.Password == "" {
  282. return fmt.Errorf("username and password are required")
  283. }
  284. if s.Service == "" {
  285. s.Service = "any"
  286. }
  287. if s.Profile == "" {
  288. s.Profile = "default"
  289. }
  290. if s.ID == "" {
  291. s.ID = fmt.Sprintf("secret-%d", time.Now().UnixNano())
  292. }
  293. m.secrets[s.ID] = s
  294. var list []*PPPSecret
  295. for _, sc := range m.secrets {
  296. list = append(list, sc)
  297. }
  298. if err := m.save("ppp_secrets.json", list); err != nil {
  299. return err
  300. }
  301. return m.SyncSecretsToSystem()
  302. }
  303. func (m *PPPServerManager) SetSecretState(id string, disabled bool) error {
  304. m.mu.Lock()
  305. defer m.mu.Unlock()
  306. s, ok := m.secrets[id]
  307. if !ok {
  308. return fmt.Errorf("secret not found")
  309. }
  310. s.Disabled = disabled
  311. var list []*PPPSecret
  312. for _, sc := range m.secrets {
  313. list = append(list, sc)
  314. }
  315. _ = m.save("ppp_secrets.json", list)
  316. return m.SyncSecretsToSystem()
  317. }
  318. func (m *PPPServerManager) DeleteSecret(id string) error {
  319. m.mu.Lock()
  320. defer m.mu.Unlock()
  321. delete(m.secrets, id)
  322. var list []*PPPSecret
  323. for _, sc := range m.secrets {
  324. list = append(list, sc)
  325. }
  326. _ = m.save("ppp_secrets.json", list)
  327. return m.SyncSecretsToSystem()
  328. }
  329. // SyncSecretsToSystem synchronizes all enabled secrets into /etc/ppp/chap-secrets and /etc/ppp/pap-secrets
  330. func (m *PPPServerManager) SyncSecretsToSystem() error {
  331. var lines []string
  332. lines = append(lines, "# Autogenerated by Proxmox RouterOS - DO NOT EDIT MANUALLY")
  333. lines = append(lines, "# client\tserver\tsecret\tIP addresses")
  334. for _, s := range m.secrets {
  335. if s.Disabled {
  336. continue
  337. }
  338. serviceName := "*"
  339. if s.Service != "any" && s.Service != "" {
  340. serviceName = s.Service
  341. }
  342. ipAddr := "*"
  343. if s.RemoteAddress != "" {
  344. ipAddr = s.RemoteAddress
  345. }
  346. lines = append(lines, fmt.Sprintf("\"%s\"\t%s\t\"%s\"\t%s", s.Name, serviceName, s.Password, ipAddr))
  347. }
  348. content := strings.Join(lines, "\n") + "\n"
  349. _ = os.WriteFile("/etc/ppp/chap-secrets", []byte(content), 0600)
  350. _ = os.WriteFile("/etc/ppp/pap-secrets", []byte(content), 0600)
  351. return nil
  352. }
  353. // ======================== PPPoE Server Management ========================
  354. func (m *PPPServerManager) GetPPPoEServer() PPPoEServerConfig {
  355. m.mu.Lock()
  356. defer m.mu.Unlock()
  357. // Check if running
  358. m.pppoeServer.Running = m.isProcessRunning(m.pppoePIDFile)
  359. m.pppoeServer.ActiveSessions = m.countPPPSessions("pppoe")
  360. return m.pppoeServer
  361. }
  362. func (m *PPPServerManager) SetPPPoEServer(cfg PPPoEServerConfig) error {
  363. m.mu.Lock()
  364. defer m.mu.Unlock()
  365. m.pppoeServer.Enabled = cfg.Enabled
  366. if cfg.ServiceName != "" {
  367. m.pppoeServer.ServiceName = cfg.ServiceName
  368. }
  369. if cfg.Interface != "" {
  370. m.pppoeServer.Interface = cfg.Interface
  371. }
  372. if cfg.DefaultProfile != "" {
  373. m.pppoeServer.DefaultProfile = cfg.DefaultProfile
  374. }
  375. m.pppoeServer.OneSessionPerHost = cfg.OneSessionPerHost
  376. if cfg.MaxMTU > 0 {
  377. m.pppoeServer.MaxMTU = cfg.MaxMTU
  378. }
  379. if cfg.MaxMRU > 0 {
  380. m.pppoeServer.MaxMRU = cfg.MaxMRU
  381. }
  382. _ = m.save("pppoe_server.json", m.pppoeServer)
  383. return m.applyPPPoEServer()
  384. }
  385. func (m *PPPServerManager) applyPPPoEServer() error {
  386. m.stopPPPoEServer()
  387. if !m.pppoeServer.Enabled {
  388. m.pppoeServer.Running = false
  389. m.pppoeServer.LastError = ""
  390. return nil
  391. }
  392. // Prepare pppoe-server-options
  393. profile := m.profiles[m.pppoeServer.DefaultProfile]
  394. if profile == nil {
  395. profile = m.profiles["default"]
  396. }
  397. localIP := "10.10.10.1"
  398. if profile != nil && profile.LocalAddress != "" {
  399. localIP = profile.LocalAddress
  400. }
  401. startIP := "10.10.10.10"
  402. poolCount := 50
  403. if profile != nil && profile.RemoteAddress != "" {
  404. if strings.Contains(profile.RemoteAddress, "-") {
  405. parts := strings.Split(profile.RemoteAddress, "-")
  406. startIP = strings.TrimSpace(parts[0])
  407. } else {
  408. startIP = profile.RemoteAddress
  409. }
  410. }
  411. // Write /etc/ppp/pppoe-server-options
  412. dns1 := "1.1.1.1"
  413. dns2 := "8.8.8.8"
  414. if profile != nil && profile.DNSServers != "" {
  415. parts := strings.Split(profile.DNSServers, ",")
  416. if len(parts) > 0 {
  417. dns1 = strings.TrimSpace(parts[0])
  418. }
  419. if len(parts) > 1 {
  420. dns2 = strings.TrimSpace(parts[1])
  421. }
  422. }
  423. opts := fmt.Sprintf(`auth
  424. require-chap
  425. login
  426. lcp-echo-interval 10
  427. lcp-echo-failure 2
  428. ms-dns %s
  429. ms-dns %s
  430. netmask 255.255.255.0
  431. default-mru
  432. default-asyncmap
  433. proxyarp
  434. `, dns1, dns2)
  435. _ = os.WriteFile("/etc/ppp/pppoe-server-options", []byte(opts), 0644)
  436. // Launch pppoe-server
  437. // pppoe-server -I <if> -L <local_ip> -R <start_ip> -N <count> -S <service> -O /etc/ppp/pppoe-server-options -X <pidfile>
  438. args := []string{
  439. "-I", m.pppoeServer.Interface,
  440. "-L", localIP,
  441. "-R", startIP,
  442. "-N", strconv.Itoa(poolCount),
  443. "-S", m.pppoeServer.ServiceName,
  444. "-O", "/etc/ppp/pppoe-server-options",
  445. "-X", m.pppoePIDFile,
  446. }
  447. if m.pppoeServer.OneSessionPerHost {
  448. args = append(args, "-x", "1")
  449. }
  450. cmd := exec.Command("/usr/sbin/pppoe-server", args...)
  451. if out, err := cmd.CombinedOutput(); err != nil {
  452. m.pppoeServer.LastError = fmt.Sprintf("start failed: %s - %v", strings.TrimSpace(string(out)), err)
  453. m.pppoeServer.Running = false
  454. return fmt.Errorf("%s", m.pppoeServer.LastError)
  455. }
  456. time.Sleep(300 * time.Millisecond)
  457. m.pppoeServer.Running = m.isProcessRunning(m.pppoePIDFile)
  458. m.pppoeServer.LastError = ""
  459. return nil
  460. }
  461. func (m *PPPServerManager) stopPPPoEServer() {
  462. if data, err := os.ReadFile(m.pppoePIDFile); err == nil {
  463. pid, _ := strconv.Atoi(strings.TrimSpace(string(data)))
  464. if pid > 0 {
  465. _ = syscall.Kill(pid, syscall.SIGTERM)
  466. time.Sleep(200 * time.Millisecond)
  467. _ = syscall.Kill(pid, syscall.SIGKILL)
  468. }
  469. _ = os.Remove(m.pppoePIDFile)
  470. }
  471. _ = exec.Command("pkill", "-f", "/usr/sbin/pppoe-server").Run()
  472. }
  473. // ======================== PPTP Server Management ========================
  474. func (m *PPPServerManager) GetPPTPServer() PPTPServerConfig {
  475. m.mu.Lock()
  476. defer m.mu.Unlock()
  477. out, _ := exec.Command("systemctl", "is-active", "pptpd").Output()
  478. m.pptpServer.Running = strings.TrimSpace(string(out)) == "active"
  479. m.pptpServer.ActiveSessions = m.countPPPSessions("pptp")
  480. return m.pptpServer
  481. }
  482. func (m *PPPServerManager) SetPPTPServer(cfg PPTPServerConfig) error {
  483. m.mu.Lock()
  484. defer m.mu.Unlock()
  485. m.pptpServer.Enabled = cfg.Enabled
  486. if cfg.Port > 0 {
  487. m.pptpServer.Port = cfg.Port
  488. }
  489. if cfg.DefaultProfile != "" {
  490. m.pptpServer.DefaultProfile = cfg.DefaultProfile
  491. }
  492. m.pptpServer.RequireMPPE = cfg.RequireMPPE
  493. _ = m.save("pptp_server.json", m.pptpServer)
  494. return m.applyPPTPServer()
  495. }
  496. func (m *PPPServerManager) applyPPTPServer() error {
  497. if !m.pptpServer.Enabled {
  498. _ = exec.Command("systemctl", "stop", "pptpd").Run()
  499. m.pptpServer.Running = false
  500. m.pptpServer.LastError = ""
  501. return nil
  502. }
  503. profile := m.profiles[m.pptpServer.DefaultProfile]
  504. if profile == nil {
  505. profile = m.profiles["default-encryption"]
  506. }
  507. localIP := "10.10.20.1"
  508. if profile != nil && profile.LocalAddress != "" {
  509. localIP = profile.LocalAddress
  510. }
  511. remotePool := "10.10.20.10-50"
  512. if profile != nil && profile.RemoteAddress != "" {
  513. remotePool = profile.RemoteAddress
  514. }
  515. // Write /etc/pptpd.conf
  516. pptpdConf := fmt.Sprintf(`option /etc/ppp/pptpd-options
  517. logwtmp
  518. localip %s
  519. remoteip %s
  520. `, localIP, remotePool)
  521. _ = os.WriteFile("/etc/pptpd.conf", []byte(pptpdConf), 0644)
  522. // Write /etc/ppp/pptpd-options
  523. dns1 := "1.1.1.1"
  524. dns2 := "8.8.8.8"
  525. if profile != nil && profile.DNSServers != "" {
  526. parts := strings.Split(profile.DNSServers, ",")
  527. if len(parts) > 0 {
  528. dns1 = strings.TrimSpace(parts[0])
  529. }
  530. if len(parts) > 1 {
  531. dns2 = strings.TrimSpace(parts[1])
  532. }
  533. }
  534. mppeRule := "require-mppe-128"
  535. if !m.pptpServer.RequireMPPE {
  536. mppeRule = "# require-mppe-128"
  537. }
  538. pptpdOpts := fmt.Sprintf(`name pptpd
  539. refuse-pap
  540. refuse-chap
  541. refuse-mschap
  542. require-mschap-v2
  543. %s
  544. ms-dns %s
  545. ms-dns %s
  546. proxyarp
  547. nodefaultroute
  548. lock
  549. nobsdcomp
  550. novj
  551. novjccomp
  552. nologfd
  553. `, mppeRule, dns1, dns2)
  554. _ = os.WriteFile("/etc/ppp/pptpd-options", []byte(pptpdOpts), 0644)
  555. _ = exec.Command("systemctl", "restart", "pptpd").Run()
  556. time.Sleep(300 * time.Millisecond)
  557. out, _ := exec.Command("systemctl", "is-active", "pptpd").Output()
  558. m.pptpServer.Running = strings.TrimSpace(string(out)) == "active"
  559. m.pptpServer.LastError = ""
  560. return nil
  561. }
  562. // ======================== L2TP Server Management ========================
  563. func (m *PPPServerManager) GetL2TPServer() L2TPServerConfig {
  564. m.mu.Lock()
  565. defer m.mu.Unlock()
  566. out, _ := exec.Command("systemctl", "is-active", "xl2tpd").Output()
  567. m.l2tpServer.Running = strings.TrimSpace(string(out)) == "active"
  568. m.l2tpServer.ActiveSessions = m.countPPPSessions("l2tp")
  569. return m.l2tpServer
  570. }
  571. func (m *PPPServerManager) SetL2TPServer(cfg L2TPServerConfig) error {
  572. m.mu.Lock()
  573. defer m.mu.Unlock()
  574. m.l2tpServer.Enabled = cfg.Enabled
  575. if cfg.Port > 0 {
  576. m.l2tpServer.Port = cfg.Port
  577. }
  578. if cfg.DefaultProfile != "" {
  579. m.l2tpServer.DefaultProfile = cfg.DefaultProfile
  580. }
  581. if cfg.UseIPSec != "" {
  582. m.l2tpServer.UseIPSec = cfg.UseIPSec
  583. }
  584. m.l2tpServer.IPSecSecret = cfg.IPSecSecret
  585. _ = m.save("l2tp_server.json", m.l2tpServer)
  586. return m.applyL2TPServer()
  587. }
  588. func (m *PPPServerManager) applyL2TPServer() error {
  589. if !m.l2tpServer.Enabled {
  590. // When disabled, don't stop xl2tpd completely as client may need it, just reload without LNS
  591. _ = os.WriteFile("/etc/ppp/options.xl2tpd.server", []byte("# disabled\n"), 0644)
  592. _ = exec.Command("systemctl", "reload-or-restart", "xl2tpd").Run()
  593. m.l2tpServer.Running = false
  594. m.l2tpServer.LastError = ""
  595. return nil
  596. }
  597. profile := m.profiles[m.l2tpServer.DefaultProfile]
  598. if profile == nil {
  599. profile = m.profiles["default"]
  600. }
  601. localIP := "10.10.40.1"
  602. if profile != nil && profile.LocalAddress != "" {
  603. localIP = profile.LocalAddress
  604. }
  605. remotePool := "10.10.40.10-10.10.40.50"
  606. if profile != nil && profile.RemoteAddress != "" {
  607. remotePool = profile.RemoteAddress
  608. }
  609. // Write /etc/xl2tpd/xl2tpd.conf with [lns default]
  610. _ = os.MkdirAll("/etc/xl2tpd", 0755)
  611. xl2tpdConf := fmt.Sprintf(`[global]
  612. port = %d
  613. [lns default]
  614. ip range = %s
  615. local ip = %s
  616. require chap = yes
  617. refuse pap = yes
  618. require authentication = yes
  619. name = l2tpd
  620. pppoptfile = /etc/ppp/options.xl2tpd.server
  621. length bit = yes
  622. `, m.l2tpServer.Port, remotePool, localIP)
  623. _ = os.WriteFile("/etc/xl2tpd/xl2tpd.conf", []byte(xl2tpdConf), 0644)
  624. // Write /etc/ppp/options.xl2tpd.server
  625. dns1 := "1.1.1.1"
  626. dns2 := "8.8.8.8"
  627. if profile != nil && profile.DNSServers != "" {
  628. parts := strings.Split(profile.DNSServers, ",")
  629. if len(parts) > 0 {
  630. dns1 = strings.TrimSpace(parts[0])
  631. }
  632. if len(parts) > 1 {
  633. dns2 = strings.TrimSpace(parts[1])
  634. }
  635. }
  636. opts := fmt.Sprintf(`require-mschap-v2
  637. ms-dns %s
  638. ms-dns %s
  639. auth
  640. mtu 1400
  641. mru 1400
  642. proxyarp
  643. nodefaultroute
  644. `, dns1, dns2)
  645. _ = os.WriteFile("/etc/ppp/options.xl2tpd.server", []byte(opts), 0644)
  646. _ = exec.Command("systemctl", "restart", "xl2tpd").Run()
  647. time.Sleep(300 * time.Millisecond)
  648. out, _ := exec.Command("systemctl", "is-active", "xl2tpd").Output()
  649. m.l2tpServer.Running = strings.TrimSpace(string(out)) == "active"
  650. m.l2tpServer.LastError = ""
  651. return nil
  652. }
  653. // ======================== IPSec Server Management ========================
  654. func (m *PPPServerManager) GetIPSecServer() IPSecServerConfig {
  655. m.mu.Lock()
  656. defer m.mu.Unlock()
  657. out, _ := exec.Command("swanctl", "--list-conns").Output()
  658. m.ipsecServer.Running = strings.Contains(string(out), "rw-server")
  659. m.ipsecServer.ActiveSessions = m.countIPSecSessions()
  660. return m.ipsecServer
  661. }
  662. func (m *PPPServerManager) SetIPSecServer(cfg IPSecServerConfig) error {
  663. m.mu.Lock()
  664. defer m.mu.Unlock()
  665. m.ipsecServer.Enabled = cfg.Enabled
  666. if cfg.PoolAddress != "" {
  667. m.ipsecServer.PoolAddress = cfg.PoolAddress
  668. }
  669. if cfg.PresharedKey != "" {
  670. m.ipsecServer.PresharedKey = cfg.PresharedKey
  671. }
  672. if cfg.LocalSubnet != "" {
  673. m.ipsecServer.LocalSubnet = cfg.LocalSubnet
  674. }
  675. if cfg.DNSServers != "" {
  676. m.ipsecServer.DNSServers = cfg.DNSServers
  677. }
  678. _ = m.save("ipsec_server.json", m.ipsecServer)
  679. return m.applyIPSecServer()
  680. }
  681. func (m *PPPServerManager) applyIPSecServer() error {
  682. confFile := "/etc/swanctl/conf.d/rw-server.conf"
  683. if !m.ipsecServer.Enabled {
  684. _ = os.Remove(confFile)
  685. _ = exec.Command("swanctl", "--load-all").Run()
  686. m.ipsecServer.Running = false
  687. m.ipsecServer.LastError = ""
  688. return nil
  689. }
  690. _ = os.MkdirAll("/etc/swanctl/conf.d", 0755)
  691. swanConf := fmt.Sprintf(`connections {
  692. rw-server {
  693. local_addrs = %%any
  694. pools = rw-pool
  695. local {
  696. auth = psk
  697. id = %%any
  698. }
  699. remote {
  700. auth = psk
  701. }
  702. children {
  703. rw-net {
  704. local_ts = %s
  705. esp_proposals = aes256gcm128-sha256-modp2048,aes256-sha256-modp2048
  706. }
  707. }
  708. }
  709. }
  710. pools {
  711. rw-pool {
  712. addrs = %s
  713. dns = %s
  714. }
  715. }
  716. secrets {
  717. ike-rw {
  718. secret = "%s"
  719. }
  720. }
  721. `, m.ipsecServer.LocalSubnet, m.ipsecServer.PoolAddress, m.ipsecServer.DNSServers, m.ipsecServer.PresharedKey)
  722. if err := os.WriteFile(confFile, []byte(swanConf), 0600); err != nil {
  723. m.ipsecServer.LastError = err.Error()
  724. return err
  725. }
  726. if out, err := exec.Command("swanctl", "--load-all").CombinedOutput(); err != nil {
  727. m.ipsecServer.LastError = strings.TrimSpace(string(out))
  728. return err
  729. }
  730. m.ipsecServer.Running = true
  731. m.ipsecServer.LastError = ""
  732. return nil
  733. }
  734. // ======================== Active Connections & Kill ========================
  735. func (m *PPPServerManager) ListActiveSessions() []ActivePPPSession {
  736. list := make([]ActivePPPSession, 0)
  737. // Read network interfaces matching ppp*
  738. ifaces, err := net.Interfaces()
  739. if err != nil {
  740. return list
  741. }
  742. for _, iface := range ifaces {
  743. if !strings.HasPrefix(iface.Name, "ppp") {
  744. continue
  745. }
  746. addrs, _ := iface.Addrs()
  747. var assignedIP string
  748. for _, a := range addrs {
  749. if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
  750. assignedIP = ipNet.IP.String()
  751. break
  752. }
  753. }
  754. sess := ActivePPPSession{
  755. ID: iface.Name,
  756. Interface: iface.Name,
  757. Address: assignedIP,
  758. Uptime: "active",
  759. }
  760. // Try to detect service from process or default
  761. sess.Service = "ppp"
  762. sess.Username = "client-" + iface.Name
  763. m.populateIfaceTraffic(iface.Name, &sess)
  764. list = append(list, sess)
  765. }
  766. return list
  767. }
  768. func (m *PPPServerManager) DisconnectSession(ifaceName string) error {
  769. if !strings.HasPrefix(ifaceName, "ppp") {
  770. return fmt.Errorf("invalid ppp interface")
  771. }
  772. _ = exec.Command("ip", "link", "set", ifaceName, "down").Run()
  773. _ = exec.Command("pkill", "-f", ifaceName).Run()
  774. return nil
  775. }
  776. func (m *PPPServerManager) populateIfaceTraffic(ifaceName string, sess *ActivePPPSession) {
  777. file, err := os.Open("/proc/net/dev")
  778. if err != nil {
  779. return
  780. }
  781. defer file.Close()
  782. scanner := bufio.NewScanner(file)
  783. for scanner.Scan() {
  784. line := scanner.Text()
  785. if strings.Contains(line, ifaceName+":") {
  786. parts := strings.Fields(line)
  787. if len(parts) >= 10 {
  788. rxBytes, _ := strconv.ParseUint(parts[1], 10, 64)
  789. txBytes, _ := strconv.ParseUint(parts[9], 10, 64)
  790. sess.RxBytes = rxBytes
  791. sess.TxBytes = txBytes
  792. sess.RxHuman = formatBytes(rxBytes)
  793. sess.TxHuman = formatBytes(txBytes)
  794. }
  795. break
  796. }
  797. }
  798. }
  799. func (m *PPPServerManager) countPPPSessions(service string) int {
  800. ifaces, err := net.Interfaces()
  801. if err != nil {
  802. return 0
  803. }
  804. count := 0
  805. for _, i := range ifaces {
  806. if strings.HasPrefix(i.Name, "ppp") {
  807. count++
  808. }
  809. }
  810. return count
  811. }
  812. func (m *PPPServerManager) countIPSecSessions() int {
  813. out, err := exec.Command("swanctl", "--list-sas").Output()
  814. if err != nil {
  815. return 0
  816. }
  817. return strings.Count(string(out), "ESTABLISHED")
  818. }
  819. func (m *PPPServerManager) isProcessRunning(pidFile string) bool {
  820. data, err := os.ReadFile(pidFile)
  821. if err != nil {
  822. return false
  823. }
  824. pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
  825. if err != nil || pid <= 0 {
  826. return false
  827. }
  828. return syscall.Kill(pid, 0) == nil
  829. }
  830. func (m *PPPServerManager) applyAll() {
  831. if m.pppoeServer.Enabled {
  832. _ = m.applyPPPoEServer()
  833. }
  834. if m.pptpServer.Enabled {
  835. _ = m.applyPPTPServer()
  836. }
  837. if m.l2tpServer.Enabled {
  838. _ = m.applyL2TPServer()
  839. }
  840. if m.ipsecServer.Enabled {
  841. _ = m.applyIPSecServer()
  842. }
  843. }