ppp_server.go 25 KB

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