ppp_server.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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) SaveProfile(p *PPPProfile) error {
  229. m.mu.Lock()
  230. defer m.mu.Unlock()
  231. if p.Name == "" {
  232. return fmt.Errorf("profile name is required")
  233. }
  234. if p.LocalAddress == "" {
  235. p.LocalAddress = "10.10.10.1"
  236. }
  237. if p.RemoteAddress == "" {
  238. p.RemoteAddress = "10.10.10.10-10.10.10.50"
  239. }
  240. if p.ID == "" {
  241. p.ID = p.Name
  242. }
  243. m.profiles[p.Name] = p
  244. var list []*PPPProfile
  245. for _, pr := range m.profiles {
  246. list = append(list, pr)
  247. }
  248. return m.save("ppp_profiles.json", list)
  249. }
  250. func (m *PPPServerManager) DeleteProfile(name string) error {
  251. m.mu.Lock()
  252. defer m.mu.Unlock()
  253. if name == "default" || name == "default-encryption" {
  254. return fmt.Errorf("cannot delete default profile")
  255. }
  256. delete(m.profiles, name)
  257. var list []*PPPProfile
  258. for _, pr := range m.profiles {
  259. list = append(list, pr)
  260. }
  261. return m.save("ppp_profiles.json", list)
  262. }
  263. // ======================== PPP Secrets CRUD ========================
  264. func (m *PPPServerManager) ListSecrets() []*PPPSecret {
  265. m.mu.RLock()
  266. defer m.mu.RUnlock()
  267. list := make([]*PPPSecret, 0)
  268. for _, s := range m.secrets {
  269. list = append(list, s)
  270. }
  271. return list
  272. }
  273. func (m *PPPServerManager) SaveSecret(s *PPPSecret) error {
  274. m.mu.Lock()
  275. defer m.mu.Unlock()
  276. if s.Name == "" || s.Password == "" {
  277. return fmt.Errorf("username and password are required")
  278. }
  279. if s.Service == "" {
  280. s.Service = "any"
  281. }
  282. if s.Profile == "" {
  283. s.Profile = "default"
  284. }
  285. if s.ID == "" {
  286. s.ID = fmt.Sprintf("secret-%d", time.Now().UnixNano())
  287. }
  288. m.secrets[s.ID] = s
  289. var list []*PPPSecret
  290. for _, sc := range m.secrets {
  291. list = append(list, sc)
  292. }
  293. if err := m.save("ppp_secrets.json", list); err != nil {
  294. return err
  295. }
  296. return m.SyncSecretsToSystem()
  297. }
  298. func (m *PPPServerManager) SetSecretState(id string, disabled bool) error {
  299. m.mu.Lock()
  300. defer m.mu.Unlock()
  301. s, ok := m.secrets[id]
  302. if !ok {
  303. return fmt.Errorf("secret not found")
  304. }
  305. s.Disabled = disabled
  306. var list []*PPPSecret
  307. for _, sc := range m.secrets {
  308. list = append(list, sc)
  309. }
  310. _ = m.save("ppp_secrets.json", list)
  311. return m.SyncSecretsToSystem()
  312. }
  313. func (m *PPPServerManager) DeleteSecret(id string) error {
  314. m.mu.Lock()
  315. defer m.mu.Unlock()
  316. delete(m.secrets, id)
  317. var list []*PPPSecret
  318. for _, sc := range m.secrets {
  319. list = append(list, sc)
  320. }
  321. _ = m.save("ppp_secrets.json", list)
  322. return m.SyncSecretsToSystem()
  323. }
  324. // SyncSecretsToSystem synchronizes all enabled secrets into /etc/ppp/chap-secrets and /etc/ppp/pap-secrets
  325. func (m *PPPServerManager) SyncSecretsToSystem() error {
  326. var lines []string
  327. lines = append(lines, "# Autogenerated by Proxmox RouterOS - DO NOT EDIT MANUALLY")
  328. lines = append(lines, "# client\tserver\tsecret\tIP addresses")
  329. for _, s := range m.secrets {
  330. if s.Disabled {
  331. continue
  332. }
  333. serviceName := "*"
  334. if s.Service != "any" && s.Service != "" {
  335. serviceName = s.Service
  336. }
  337. ipAddr := "*"
  338. if s.RemoteAddress != "" {
  339. ipAddr = s.RemoteAddress
  340. }
  341. lines = append(lines, fmt.Sprintf("\"%s\"\t%s\t\"%s\"\t%s", s.Name, serviceName, s.Password, ipAddr))
  342. }
  343. content := strings.Join(lines, "\n") + "\n"
  344. _ = os.WriteFile("/etc/ppp/chap-secrets", []byte(content), 0600)
  345. _ = os.WriteFile("/etc/ppp/pap-secrets", []byte(content), 0600)
  346. return nil
  347. }
  348. // ======================== PPPoE Server Management ========================
  349. func (m *PPPServerManager) GetPPPoEServer() PPPoEServerConfig {
  350. m.mu.Lock()
  351. defer m.mu.Unlock()
  352. // Check if running
  353. m.pppoeServer.Running = m.isProcessRunning(m.pppoePIDFile)
  354. m.pppoeServer.ActiveSessions = m.countPPPSessions("pppoe")
  355. return m.pppoeServer
  356. }
  357. func (m *PPPServerManager) SetPPPoEServer(cfg PPPoEServerConfig) error {
  358. m.mu.Lock()
  359. defer m.mu.Unlock()
  360. m.pppoeServer.Enabled = cfg.Enabled
  361. if cfg.ServiceName != "" {
  362. m.pppoeServer.ServiceName = cfg.ServiceName
  363. }
  364. if cfg.Interface != "" {
  365. m.pppoeServer.Interface = cfg.Interface
  366. }
  367. if cfg.DefaultProfile != "" {
  368. m.pppoeServer.DefaultProfile = cfg.DefaultProfile
  369. }
  370. m.pppoeServer.OneSessionPerHost = cfg.OneSessionPerHost
  371. if cfg.MaxMTU > 0 {
  372. m.pppoeServer.MaxMTU = cfg.MaxMTU
  373. }
  374. if cfg.MaxMRU > 0 {
  375. m.pppoeServer.MaxMRU = cfg.MaxMRU
  376. }
  377. _ = m.save("pppoe_server.json", m.pppoeServer)
  378. return m.applyPPPoEServer()
  379. }
  380. func (m *PPPServerManager) applyPPPoEServer() error {
  381. m.stopPPPoEServer()
  382. if !m.pppoeServer.Enabled {
  383. m.pppoeServer.Running = false
  384. m.pppoeServer.LastError = ""
  385. return nil
  386. }
  387. // Prepare pppoe-server-options
  388. profile := m.profiles[m.pppoeServer.DefaultProfile]
  389. if profile == nil {
  390. profile = m.profiles["default"]
  391. }
  392. localIP := "10.10.10.1"
  393. if profile != nil && profile.LocalAddress != "" {
  394. localIP = profile.LocalAddress
  395. }
  396. startIP := "10.10.10.10"
  397. poolCount := 50
  398. if profile != nil && profile.RemoteAddress != "" {
  399. if strings.Contains(profile.RemoteAddress, "-") {
  400. parts := strings.Split(profile.RemoteAddress, "-")
  401. startIP = strings.TrimSpace(parts[0])
  402. } else {
  403. startIP = profile.RemoteAddress
  404. }
  405. }
  406. // Write /etc/ppp/pppoe-server-options
  407. dns1 := "1.1.1.1"
  408. dns2 := "8.8.8.8"
  409. if profile != nil && profile.DNSServers != "" {
  410. parts := strings.Split(profile.DNSServers, ",")
  411. if len(parts) > 0 {
  412. dns1 = strings.TrimSpace(parts[0])
  413. }
  414. if len(parts) > 1 {
  415. dns2 = strings.TrimSpace(parts[1])
  416. }
  417. }
  418. opts := fmt.Sprintf(`auth
  419. require-chap
  420. login
  421. lcp-echo-interval 10
  422. lcp-echo-failure 2
  423. ms-dns %s
  424. ms-dns %s
  425. netmask 255.255.255.0
  426. default-mru
  427. default-asyncmap
  428. proxyarp
  429. `, dns1, dns2)
  430. _ = os.WriteFile("/etc/ppp/pppoe-server-options", []byte(opts), 0644)
  431. // Launch pppoe-server
  432. // pppoe-server -I <if> -L <local_ip> -R <start_ip> -N <count> -S <service> -O /etc/ppp/pppoe-server-options -X <pidfile>
  433. args := []string{
  434. "-I", m.pppoeServer.Interface,
  435. "-L", localIP,
  436. "-R", startIP,
  437. "-N", strconv.Itoa(poolCount),
  438. "-S", m.pppoeServer.ServiceName,
  439. "-O", "/etc/ppp/pppoe-server-options",
  440. "-X", m.pppoePIDFile,
  441. }
  442. if m.pppoeServer.OneSessionPerHost {
  443. args = append(args, "-x", "1")
  444. }
  445. cmd := exec.Command("/usr/sbin/pppoe-server", args...)
  446. if out, err := cmd.CombinedOutput(); err != nil {
  447. m.pppoeServer.LastError = fmt.Sprintf("start failed: %s - %v", strings.TrimSpace(string(out)), err)
  448. m.pppoeServer.Running = false
  449. return fmt.Errorf("%s", m.pppoeServer.LastError)
  450. }
  451. time.Sleep(300 * time.Millisecond)
  452. m.pppoeServer.Running = m.isProcessRunning(m.pppoePIDFile)
  453. m.pppoeServer.LastError = ""
  454. return nil
  455. }
  456. func (m *PPPServerManager) stopPPPoEServer() {
  457. if data, err := os.ReadFile(m.pppoePIDFile); err == nil {
  458. pid, _ := strconv.Atoi(strings.TrimSpace(string(data)))
  459. if pid > 0 {
  460. _ = syscall.Kill(pid, syscall.SIGTERM)
  461. time.Sleep(200 * time.Millisecond)
  462. _ = syscall.Kill(pid, syscall.SIGKILL)
  463. }
  464. _ = os.Remove(m.pppoePIDFile)
  465. }
  466. _ = exec.Command("pkill", "-f", "/usr/sbin/pppoe-server").Run()
  467. }
  468. // ======================== PPTP Server Management ========================
  469. func (m *PPPServerManager) GetPPTPServer() PPTPServerConfig {
  470. m.mu.Lock()
  471. defer m.mu.Unlock()
  472. out, _ := exec.Command("systemctl", "is-active", "pptpd").Output()
  473. m.pptpServer.Running = strings.TrimSpace(string(out)) == "active"
  474. m.pptpServer.ActiveSessions = m.countPPPSessions("pptp")
  475. return m.pptpServer
  476. }
  477. func (m *PPPServerManager) SetPPTPServer(cfg PPTPServerConfig) error {
  478. m.mu.Lock()
  479. defer m.mu.Unlock()
  480. m.pptpServer.Enabled = cfg.Enabled
  481. if cfg.Port > 0 {
  482. m.pptpServer.Port = cfg.Port
  483. }
  484. if cfg.DefaultProfile != "" {
  485. m.pptpServer.DefaultProfile = cfg.DefaultProfile
  486. }
  487. m.pptpServer.RequireMPPE = cfg.RequireMPPE
  488. _ = m.save("pptp_server.json", m.pptpServer)
  489. return m.applyPPTPServer()
  490. }
  491. func (m *PPPServerManager) applyPPTPServer() error {
  492. if !m.pptpServer.Enabled {
  493. _ = exec.Command("systemctl", "stop", "pptpd").Run()
  494. m.pptpServer.Running = false
  495. m.pptpServer.LastError = ""
  496. return nil
  497. }
  498. profile := m.profiles[m.pptpServer.DefaultProfile]
  499. if profile == nil {
  500. profile = m.profiles["default-encryption"]
  501. }
  502. localIP := "10.10.20.1"
  503. if profile != nil && profile.LocalAddress != "" {
  504. localIP = profile.LocalAddress
  505. }
  506. remotePool := "10.10.20.10-50"
  507. if profile != nil && profile.RemoteAddress != "" {
  508. remotePool = profile.RemoteAddress
  509. }
  510. // Write /etc/pptpd.conf
  511. pptpdConf := fmt.Sprintf(`option /etc/ppp/pptpd-options
  512. logwtmp
  513. localip %s
  514. remoteip %s
  515. `, localIP, remotePool)
  516. _ = os.WriteFile("/etc/pptpd.conf", []byte(pptpdConf), 0644)
  517. // Write /etc/ppp/pptpd-options
  518. dns1 := "1.1.1.1"
  519. dns2 := "8.8.8.8"
  520. if profile != nil && profile.DNSServers != "" {
  521. parts := strings.Split(profile.DNSServers, ",")
  522. if len(parts) > 0 {
  523. dns1 = strings.TrimSpace(parts[0])
  524. }
  525. if len(parts) > 1 {
  526. dns2 = strings.TrimSpace(parts[1])
  527. }
  528. }
  529. mppeRule := "require-mppe-128"
  530. if !m.pptpServer.RequireMPPE {
  531. mppeRule = "# require-mppe-128"
  532. }
  533. pptpdOpts := fmt.Sprintf(`name pptpd
  534. refuse-pap
  535. refuse-chap
  536. refuse-mschap
  537. require-mschap-v2
  538. %s
  539. ms-dns %s
  540. ms-dns %s
  541. proxyarp
  542. nodefaultroute
  543. lock
  544. nobsdcomp
  545. novj
  546. novjccomp
  547. nologfd
  548. `, mppeRule, dns1, dns2)
  549. _ = os.WriteFile("/etc/ppp/pptpd-options", []byte(pptpdOpts), 0644)
  550. _ = exec.Command("systemctl", "restart", "pptpd").Run()
  551. time.Sleep(300 * time.Millisecond)
  552. out, _ := exec.Command("systemctl", "is-active", "pptpd").Output()
  553. m.pptpServer.Running = strings.TrimSpace(string(out)) == "active"
  554. m.pptpServer.LastError = ""
  555. return nil
  556. }
  557. // ======================== L2TP Server Management ========================
  558. func (m *PPPServerManager) GetL2TPServer() L2TPServerConfig {
  559. m.mu.Lock()
  560. defer m.mu.Unlock()
  561. out, _ := exec.Command("systemctl", "is-active", "xl2tpd").Output()
  562. m.l2tpServer.Running = strings.TrimSpace(string(out)) == "active"
  563. m.l2tpServer.ActiveSessions = m.countPPPSessions("l2tp")
  564. return m.l2tpServer
  565. }
  566. func (m *PPPServerManager) SetL2TPServer(cfg L2TPServerConfig) error {
  567. m.mu.Lock()
  568. defer m.mu.Unlock()
  569. m.l2tpServer.Enabled = cfg.Enabled
  570. if cfg.Port > 0 {
  571. m.l2tpServer.Port = cfg.Port
  572. }
  573. if cfg.DefaultProfile != "" {
  574. m.l2tpServer.DefaultProfile = cfg.DefaultProfile
  575. }
  576. if cfg.UseIPSec != "" {
  577. m.l2tpServer.UseIPSec = cfg.UseIPSec
  578. }
  579. m.l2tpServer.IPSecSecret = cfg.IPSecSecret
  580. _ = m.save("l2tp_server.json", m.l2tpServer)
  581. return m.applyL2TPServer()
  582. }
  583. func (m *PPPServerManager) applyL2TPServer() error {
  584. if !m.l2tpServer.Enabled {
  585. // When disabled, don't stop xl2tpd completely as client may need it, just reload without LNS
  586. _ = os.WriteFile("/etc/ppp/options.xl2tpd.server", []byte("# disabled\n"), 0644)
  587. _ = exec.Command("systemctl", "reload-or-restart", "xl2tpd").Run()
  588. m.l2tpServer.Running = false
  589. m.l2tpServer.LastError = ""
  590. return nil
  591. }
  592. profile := m.profiles[m.l2tpServer.DefaultProfile]
  593. if profile == nil {
  594. profile = m.profiles["default"]
  595. }
  596. localIP := "10.10.40.1"
  597. if profile != nil && profile.LocalAddress != "" {
  598. localIP = profile.LocalAddress
  599. }
  600. remotePool := "10.10.40.10-10.10.40.50"
  601. if profile != nil && profile.RemoteAddress != "" {
  602. remotePool = profile.RemoteAddress
  603. }
  604. // Write /etc/xl2tpd/xl2tpd.conf with [lns default]
  605. _ = os.MkdirAll("/etc/xl2tpd", 0755)
  606. xl2tpdConf := fmt.Sprintf(`[global]
  607. port = %d
  608. [lns default]
  609. ip range = %s
  610. local ip = %s
  611. require chap = yes
  612. refuse pap = yes
  613. require authentication = yes
  614. name = l2tpd
  615. pppoptfile = /etc/ppp/options.xl2tpd.server
  616. length bit = yes
  617. `, m.l2tpServer.Port, remotePool, localIP)
  618. _ = os.WriteFile("/etc/xl2tpd/xl2tpd.conf", []byte(xl2tpdConf), 0644)
  619. // Write /etc/ppp/options.xl2tpd.server
  620. dns1 := "1.1.1.1"
  621. dns2 := "8.8.8.8"
  622. if profile != nil && profile.DNSServers != "" {
  623. parts := strings.Split(profile.DNSServers, ",")
  624. if len(parts) > 0 {
  625. dns1 = strings.TrimSpace(parts[0])
  626. }
  627. if len(parts) > 1 {
  628. dns2 = strings.TrimSpace(parts[1])
  629. }
  630. }
  631. opts := fmt.Sprintf(`require-mschap-v2
  632. ms-dns %s
  633. ms-dns %s
  634. auth
  635. mtu 1400
  636. mru 1400
  637. proxyarp
  638. nodefaultroute
  639. `, dns1, dns2)
  640. _ = os.WriteFile("/etc/ppp/options.xl2tpd.server", []byte(opts), 0644)
  641. _ = exec.Command("systemctl", "restart", "xl2tpd").Run()
  642. time.Sleep(300 * time.Millisecond)
  643. out, _ := exec.Command("systemctl", "is-active", "xl2tpd").Output()
  644. m.l2tpServer.Running = strings.TrimSpace(string(out)) == "active"
  645. m.l2tpServer.LastError = ""
  646. return nil
  647. }
  648. // ======================== IPSec Server Management ========================
  649. func (m *PPPServerManager) GetIPSecServer() IPSecServerConfig {
  650. m.mu.Lock()
  651. defer m.mu.Unlock()
  652. out, _ := exec.Command("swanctl", "--list-conns").Output()
  653. m.ipsecServer.Running = strings.Contains(string(out), "rw-server")
  654. m.ipsecServer.ActiveSessions = m.countIPSecSessions()
  655. return m.ipsecServer
  656. }
  657. func (m *PPPServerManager) SetIPSecServer(cfg IPSecServerConfig) error {
  658. m.mu.Lock()
  659. defer m.mu.Unlock()
  660. m.ipsecServer.Enabled = cfg.Enabled
  661. if cfg.PoolAddress != "" {
  662. m.ipsecServer.PoolAddress = cfg.PoolAddress
  663. }
  664. if cfg.PresharedKey != "" {
  665. m.ipsecServer.PresharedKey = cfg.PresharedKey
  666. }
  667. if cfg.LocalSubnet != "" {
  668. m.ipsecServer.LocalSubnet = cfg.LocalSubnet
  669. }
  670. if cfg.DNSServers != "" {
  671. m.ipsecServer.DNSServers = cfg.DNSServers
  672. }
  673. _ = m.save("ipsec_server.json", m.ipsecServer)
  674. return m.applyIPSecServer()
  675. }
  676. func (m *PPPServerManager) applyIPSecServer() error {
  677. confFile := "/etc/swanctl/conf.d/rw-server.conf"
  678. if !m.ipsecServer.Enabled {
  679. _ = os.Remove(confFile)
  680. _ = exec.Command("swanctl", "--load-all").Run()
  681. m.ipsecServer.Running = false
  682. m.ipsecServer.LastError = ""
  683. return nil
  684. }
  685. _ = os.MkdirAll("/etc/swanctl/conf.d", 0755)
  686. swanConf := fmt.Sprintf(`connections {
  687. rw-server {
  688. local_addrs = %%any
  689. pools = rw-pool
  690. local {
  691. auth = psk
  692. id = %%any
  693. }
  694. remote {
  695. auth = psk
  696. }
  697. children {
  698. rw-net {
  699. local_ts = %s
  700. esp_proposals = aes256gcm128-sha256-modp2048,aes256-sha256-modp2048
  701. }
  702. }
  703. }
  704. }
  705. pools {
  706. rw-pool {
  707. addrs = %s
  708. dns = %s
  709. }
  710. }
  711. secrets {
  712. ike-rw {
  713. secret = "%s"
  714. }
  715. }
  716. `, m.ipsecServer.LocalSubnet, m.ipsecServer.PoolAddress, m.ipsecServer.DNSServers, m.ipsecServer.PresharedKey)
  717. if err := os.WriteFile(confFile, []byte(swanConf), 0600); err != nil {
  718. m.ipsecServer.LastError = err.Error()
  719. return err
  720. }
  721. if out, err := exec.Command("swanctl", "--load-all").CombinedOutput(); err != nil {
  722. m.ipsecServer.LastError = strings.TrimSpace(string(out))
  723. return err
  724. }
  725. m.ipsecServer.Running = true
  726. m.ipsecServer.LastError = ""
  727. return nil
  728. }
  729. // ======================== Active Connections & Kill ========================
  730. func (m *PPPServerManager) ListActiveSessions() []ActivePPPSession {
  731. list := make([]ActivePPPSession, 0)
  732. // Read network interfaces matching ppp*
  733. ifaces, err := net.Interfaces()
  734. if err != nil {
  735. return list
  736. }
  737. for _, iface := range ifaces {
  738. if !strings.HasPrefix(iface.Name, "ppp") {
  739. continue
  740. }
  741. addrs, _ := iface.Addrs()
  742. var assignedIP string
  743. for _, a := range addrs {
  744. if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
  745. assignedIP = ipNet.IP.String()
  746. break
  747. }
  748. }
  749. sess := ActivePPPSession{
  750. ID: iface.Name,
  751. Interface: iface.Name,
  752. Address: assignedIP,
  753. Uptime: "active",
  754. }
  755. // Try to detect service from process or default
  756. sess.Service = "ppp"
  757. sess.Username = "client-" + iface.Name
  758. m.populateIfaceTraffic(iface.Name, &sess)
  759. list = append(list, sess)
  760. }
  761. return list
  762. }
  763. func (m *PPPServerManager) DisconnectSession(ifaceName string) error {
  764. if !strings.HasPrefix(ifaceName, "ppp") {
  765. return fmt.Errorf("invalid ppp interface")
  766. }
  767. _ = exec.Command("ip", "link", "set", ifaceName, "down").Run()
  768. _ = exec.Command("pkill", "-f", ifaceName).Run()
  769. return nil
  770. }
  771. func (m *PPPServerManager) populateIfaceTraffic(ifaceName string, sess *ActivePPPSession) {
  772. file, err := os.Open("/proc/net/dev")
  773. if err != nil {
  774. return
  775. }
  776. defer file.Close()
  777. scanner := bufio.NewScanner(file)
  778. for scanner.Scan() {
  779. line := scanner.Text()
  780. if strings.Contains(line, ifaceName+":") {
  781. parts := strings.Fields(line)
  782. if len(parts) >= 10 {
  783. rxBytes, _ := strconv.ParseUint(parts[1], 10, 64)
  784. txBytes, _ := strconv.ParseUint(parts[9], 10, 64)
  785. sess.RxBytes = rxBytes
  786. sess.TxBytes = txBytes
  787. sess.RxHuman = formatBytes(rxBytes)
  788. sess.TxHuman = formatBytes(txBytes)
  789. }
  790. break
  791. }
  792. }
  793. }
  794. func (m *PPPServerManager) countPPPSessions(service string) int {
  795. ifaces, err := net.Interfaces()
  796. if err != nil {
  797. return 0
  798. }
  799. count := 0
  800. for _, i := range ifaces {
  801. if strings.HasPrefix(i.Name, "ppp") {
  802. count++
  803. }
  804. }
  805. return count
  806. }
  807. func (m *PPPServerManager) countIPSecSessions() int {
  808. out, err := exec.Command("swanctl", "--list-sas").Output()
  809. if err != nil {
  810. return 0
  811. }
  812. return strings.Count(string(out), "ESTABLISHED")
  813. }
  814. func (m *PPPServerManager) isProcessRunning(pidFile string) bool {
  815. data, err := os.ReadFile(pidFile)
  816. if err != nil {
  817. return false
  818. }
  819. pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
  820. if err != nil || pid <= 0 {
  821. return false
  822. }
  823. return syscall.Kill(pid, 0) == nil
  824. }
  825. func (m *PPPServerManager) applyAll() {
  826. if m.pppoeServer.Enabled {
  827. _ = m.applyPPPoEServer()
  828. }
  829. if m.pptpServer.Enabled {
  830. _ = m.applyPPTPServer()
  831. }
  832. if m.l2tpServer.Enabled {
  833. _ = m.applyL2TPServer()
  834. }
  835. if m.ipsecServer.Enabled {
  836. _ = m.applyIPSecServer()
  837. }
  838. }