ppp_server.go 25 KB

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