ppp_server.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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. if err := m.save("ppp_profiles.json", list); err != nil {
  258. return err
  259. }
  260. // Re-synchronize secrets to system since secrets may inherit IP addresses from this profile
  261. _ = m.syncSecretsToSystemLocked()
  262. // Re-apply servers if their configured DefaultProfile was updated
  263. if m.l2tpServer.Enabled && m.l2tpServer.DefaultProfile == p.Name {
  264. _ = m.applyL2TPServer()
  265. }
  266. if m.pptpServer.Enabled && m.pptpServer.DefaultProfile == p.Name {
  267. _ = m.applyPPTPServer()
  268. }
  269. if m.pppoeServer.Enabled && m.pppoeServer.DefaultProfile == p.Name {
  270. _ = m.applyPPPoEServer()
  271. }
  272. return nil
  273. }
  274. func (m *PPPServerManager) DeleteProfile(name string) error {
  275. m.mu.Lock()
  276. defer m.mu.Unlock()
  277. if name == "default" || name == "default-encryption" {
  278. return fmt.Errorf("cannot delete default profile")
  279. }
  280. delete(m.profiles, name)
  281. var list []*PPPProfile
  282. for _, pr := range m.profiles {
  283. list = append(list, pr)
  284. }
  285. if err := m.save("ppp_profiles.json", list); err != nil {
  286. return err
  287. }
  288. return m.syncSecretsToSystemLocked()
  289. }
  290. // ======================== PPP Secrets CRUD ========================
  291. func (m *PPPServerManager) ListSecrets() []*PPPSecret {
  292. m.mu.RLock()
  293. defer m.mu.RUnlock()
  294. list := make([]*PPPSecret, 0)
  295. for _, s := range m.secrets {
  296. list = append(list, s)
  297. }
  298. sort.Slice(list, func(i, j int) bool {
  299. return list[i].Name < list[j].Name
  300. })
  301. return list
  302. }
  303. func (m *PPPServerManager) SaveSecret(s *PPPSecret) error {
  304. m.mu.Lock()
  305. defer m.mu.Unlock()
  306. if s.Name == "" || s.Password == "" {
  307. return fmt.Errorf("username and password are required")
  308. }
  309. if s.Service == "" {
  310. s.Service = "any"
  311. }
  312. if s.Profile == "" {
  313. s.Profile = "default"
  314. }
  315. if s.ID == "" {
  316. s.ID = fmt.Sprintf("secret-%d", time.Now().UnixNano())
  317. }
  318. m.secrets[s.ID] = s
  319. var list []*PPPSecret
  320. for _, sc := range m.secrets {
  321. list = append(list, sc)
  322. }
  323. if err := m.save("ppp_secrets.json", list); err != nil {
  324. return err
  325. }
  326. return m.syncSecretsToSystemLocked()
  327. }
  328. func (m *PPPServerManager) SetSecretState(id string, disabled bool) error {
  329. m.mu.Lock()
  330. defer m.mu.Unlock()
  331. s, ok := m.secrets[id]
  332. if !ok {
  333. return fmt.Errorf("secret not found")
  334. }
  335. s.Disabled = disabled
  336. var list []*PPPSecret
  337. for _, sc := range m.secrets {
  338. list = append(list, sc)
  339. }
  340. _ = m.save("ppp_secrets.json", list)
  341. return m.syncSecretsToSystemLocked()
  342. }
  343. func (m *PPPServerManager) DeleteSecret(id string) error {
  344. m.mu.Lock()
  345. defer m.mu.Unlock()
  346. delete(m.secrets, id)
  347. var list []*PPPSecret
  348. for _, sc := range m.secrets {
  349. list = append(list, sc)
  350. }
  351. _ = m.save("ppp_secrets.json", list)
  352. return m.syncSecretsToSystemLocked()
  353. }
  354. // Helper IP math utilities for dynamic pool allocation per profile
  355. func parseIPRange(r string) (net.IP, net.IP, error) {
  356. r = strings.TrimSpace(r)
  357. parts := strings.Split(r, "-")
  358. if len(parts) != 2 {
  359. return nil, nil, fmt.Errorf("invalid range format")
  360. }
  361. startIP := net.ParseIP(strings.TrimSpace(parts[0])).To4()
  362. endIP := net.ParseIP(strings.TrimSpace(parts[1])).To4()
  363. if startIP == nil || endIP == nil {
  364. return nil, nil, fmt.Errorf("invalid IP in range")
  365. }
  366. return startIP, endIP, nil
  367. }
  368. func firstAvailableIPFromRange(r string, used map[string]bool) string {
  369. startIP, endIP, err := parseIPRange(r)
  370. if err != nil {
  371. return ""
  372. }
  373. startInt := ipToUint32(startIP)
  374. endInt := ipToUint32(endIP)
  375. if startInt > endInt {
  376. startInt, endInt = endInt, startInt
  377. }
  378. for cur := startInt; cur <= endInt; cur++ {
  379. ipStr := uint32ToIP(cur).String()
  380. if !used[ipStr] {
  381. return ipStr
  382. }
  383. }
  384. return startIP.String()
  385. }
  386. func ipToUint32(ip net.IP) uint32 {
  387. return uint32(ip[0])<<24 | uint32(ip[1])<<16 | uint32(ip[2])<<8 | uint32(ip[3])
  388. }
  389. func uint32ToIP(n uint32) net.IP {
  390. return net.IPv4(byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
  391. }
  392. // SyncSecretsToSystem synchronizes all enabled secrets into /etc/ppp/chap-secrets and /etc/ppp/pap-secrets
  393. func (m *PPPServerManager) SyncSecretsToSystem() error {
  394. m.mu.Lock()
  395. defer m.mu.Unlock()
  396. return m.syncSecretsToSystemLocked()
  397. }
  398. func (m *PPPServerManager) syncSecretsToSystemLocked() error {
  399. var lines []string
  400. lines = append(lines, "# Autogenerated by DebTik - DO NOT EDIT MANUALLY")
  401. lines = append(lines, "# client\tserver\tsecret\tIP addresses")
  402. // Track allocated IPs to avoid assigning duplicate static IPs from pools
  403. allocatedIPs := make(map[string]bool)
  404. for _, s := range m.secrets {
  405. if !s.Disabled && s.RemoteAddress != "" && !strings.Contains(s.RemoteAddress, "-") {
  406. allocatedIPs[strings.TrimSpace(s.RemoteAddress)] = true
  407. }
  408. }
  409. var secretList []*PPPSecret
  410. for _, s := range m.secrets {
  411. secretList = append(secretList, s)
  412. }
  413. sort.Slice(secretList, func(i, j int) bool {
  414. return secretList[i].Name < secretList[j].Name
  415. })
  416. for _, s := range secretList {
  417. if s.Disabled {
  418. continue
  419. }
  420. // In Linux pppd, the second field is the system name of the server (e.g. "l2tpd" from xl2tpd).
  421. // Setting this to "*" allows pppd to authenticate the user across L2TP, PPTP, and PPPoE daemons.
  422. serviceName := "*"
  423. ipAddr := "*"
  424. if s.RemoteAddress != "" {
  425. trimmed := strings.TrimSpace(s.RemoteAddress)
  426. if strings.Contains(trimmed, "-") {
  427. avail := firstAvailableIPFromRange(trimmed, allocatedIPs)
  428. if avail != "" {
  429. ipAddr = avail
  430. allocatedIPs[avail] = true
  431. }
  432. } else {
  433. ipAddr = trimmed
  434. }
  435. } else if s.Profile != "" {
  436. if prof, ok := m.profiles[s.Profile]; ok && prof != nil && prof.RemoteAddress != "" {
  437. trimmed := strings.TrimSpace(prof.RemoteAddress)
  438. if !strings.Contains(trimmed, "-") {
  439. // Single static IP defined in profile
  440. ipAddr = trimmed
  441. allocatedIPs[trimmed] = true
  442. } else {
  443. // Range defined in profile (e.g. 192.168.133.2-192.168.133.254)
  444. avail := firstAvailableIPFromRange(trimmed, allocatedIPs)
  445. if avail != "" {
  446. ipAddr = avail
  447. allocatedIPs[avail] = true
  448. }
  449. }
  450. }
  451. }
  452. if ipAddr == "" {
  453. ipAddr = "*"
  454. }
  455. lines = append(lines, fmt.Sprintf("\"%s\"\t%s\t\"%s\"\t%s", s.Name, serviceName, s.Password, ipAddr))
  456. }
  457. content := strings.Join(lines, "\n") + "\n"
  458. _ = os.WriteFile("/etc/ppp/chap-secrets", []byte(content), 0600)
  459. _ = os.WriteFile("/etc/ppp/pap-secrets", []byte(content), 0600)
  460. return nil
  461. }
  462. // ======================== PPPoE Server Management ========================
  463. func (m *PPPServerManager) GetPPPoEServer() PPPoEServerConfig {
  464. m.mu.Lock()
  465. defer m.mu.Unlock()
  466. // Check if running
  467. m.pppoeServer.Running = m.isProcessRunning(m.pppoePIDFile)
  468. m.pppoeServer.ActiveSessions = m.countPPPSessions("pppoe")
  469. return m.pppoeServer
  470. }
  471. func (m *PPPServerManager) SetPPPoEServer(cfg PPPoEServerConfig) error {
  472. m.mu.Lock()
  473. defer m.mu.Unlock()
  474. m.pppoeServer.Enabled = cfg.Enabled
  475. if cfg.ServiceName != "" {
  476. m.pppoeServer.ServiceName = cfg.ServiceName
  477. }
  478. if cfg.Interface != "" {
  479. m.pppoeServer.Interface = cfg.Interface
  480. }
  481. if cfg.DefaultProfile != "" {
  482. m.pppoeServer.DefaultProfile = cfg.DefaultProfile
  483. }
  484. m.pppoeServer.OneSessionPerHost = cfg.OneSessionPerHost
  485. if cfg.MaxMTU > 0 {
  486. m.pppoeServer.MaxMTU = cfg.MaxMTU
  487. }
  488. if cfg.MaxMRU > 0 {
  489. m.pppoeServer.MaxMRU = cfg.MaxMRU
  490. }
  491. _ = m.save("pppoe_server.json", m.pppoeServer)
  492. return m.applyPPPoEServer()
  493. }
  494. func (m *PPPServerManager) applyPPPoEServer() error {
  495. m.stopPPPoEServer()
  496. if !m.pppoeServer.Enabled {
  497. m.pppoeServer.Running = false
  498. m.pppoeServer.LastError = ""
  499. return nil
  500. }
  501. // Prepare pppoe-server-options
  502. profile := m.profiles[m.pppoeServer.DefaultProfile]
  503. if profile == nil {
  504. profile = m.profiles["default"]
  505. }
  506. localIP := "10.10.10.1"
  507. if profile != nil && profile.LocalAddress != "" {
  508. localIP = profile.LocalAddress
  509. }
  510. startIP := "10.10.10.10"
  511. poolCount := 50
  512. if profile != nil && profile.RemoteAddress != "" {
  513. if strings.Contains(profile.RemoteAddress, "-") {
  514. parts := strings.Split(profile.RemoteAddress, "-")
  515. startIP = strings.TrimSpace(parts[0])
  516. } else {
  517. startIP = profile.RemoteAddress
  518. }
  519. }
  520. // Write /etc/ppp/pppoe-server-options
  521. dns1 := "1.1.1.1"
  522. dns2 := "8.8.8.8"
  523. if profile != nil && profile.DNSServers != "" {
  524. parts := strings.Split(profile.DNSServers, ",")
  525. if len(parts) > 0 {
  526. dns1 = strings.TrimSpace(parts[0])
  527. }
  528. if len(parts) > 1 {
  529. dns2 = strings.TrimSpace(parts[1])
  530. }
  531. }
  532. opts := fmt.Sprintf(`auth
  533. require-chap
  534. login
  535. lcp-echo-interval 10
  536. lcp-echo-failure 2
  537. ms-dns %s
  538. ms-dns %s
  539. netmask 255.255.255.0
  540. default-mru
  541. default-asyncmap
  542. proxyarp
  543. `, dns1, dns2)
  544. _ = os.WriteFile("/etc/ppp/pppoe-server-options", []byte(opts), 0644)
  545. // Launch pppoe-server
  546. // pppoe-server -I <if> -L <local_ip> -R <start_ip> -N <count> -S <service> -O /etc/ppp/pppoe-server-options -X <pidfile>
  547. args := []string{
  548. "-I", m.pppoeServer.Interface,
  549. "-L", localIP,
  550. "-R", startIP,
  551. "-N", strconv.Itoa(poolCount),
  552. "-S", m.pppoeServer.ServiceName,
  553. "-O", "/etc/ppp/pppoe-server-options",
  554. "-X", m.pppoePIDFile,
  555. }
  556. if m.pppoeServer.OneSessionPerHost {
  557. args = append(args, "-x", "1")
  558. }
  559. cmd := exec.Command("/usr/sbin/pppoe-server", args...)
  560. if out, err := cmd.CombinedOutput(); err != nil {
  561. m.pppoeServer.LastError = fmt.Sprintf("start failed: %s - %v", strings.TrimSpace(string(out)), err)
  562. m.pppoeServer.Running = false
  563. return fmt.Errorf("%s", m.pppoeServer.LastError)
  564. }
  565. time.Sleep(300 * time.Millisecond)
  566. m.pppoeServer.Running = m.isProcessRunning(m.pppoePIDFile)
  567. m.pppoeServer.LastError = ""
  568. return nil
  569. }
  570. func (m *PPPServerManager) stopPPPoEServer() {
  571. if data, err := os.ReadFile(m.pppoePIDFile); err == nil {
  572. pid, _ := strconv.Atoi(strings.TrimSpace(string(data)))
  573. if pid > 0 {
  574. _ = syscall.Kill(pid, syscall.SIGTERM)
  575. time.Sleep(200 * time.Millisecond)
  576. _ = syscall.Kill(pid, syscall.SIGKILL)
  577. }
  578. _ = os.Remove(m.pppoePIDFile)
  579. }
  580. _ = exec.Command("pkill", "-f", "/usr/sbin/pppoe-server").Run()
  581. }
  582. // ======================== PPTP Server Management ========================
  583. func (m *PPPServerManager) GetPPTPServer() PPTPServerConfig {
  584. m.mu.Lock()
  585. defer m.mu.Unlock()
  586. out, _ := exec.Command("systemctl", "is-active", "pptpd").Output()
  587. m.pptpServer.Running = strings.TrimSpace(string(out)) == "active"
  588. m.pptpServer.ActiveSessions = m.countPPPSessions("pptp")
  589. return m.pptpServer
  590. }
  591. func (m *PPPServerManager) SetPPTPServer(cfg PPTPServerConfig) error {
  592. m.mu.Lock()
  593. defer m.mu.Unlock()
  594. m.pptpServer.Enabled = cfg.Enabled
  595. if cfg.Port > 0 {
  596. m.pptpServer.Port = cfg.Port
  597. }
  598. if cfg.DefaultProfile != "" {
  599. m.pptpServer.DefaultProfile = cfg.DefaultProfile
  600. }
  601. m.pptpServer.RequireMPPE = cfg.RequireMPPE
  602. _ = m.save("pptp_server.json", m.pptpServer)
  603. return m.applyPPTPServer()
  604. }
  605. func (m *PPPServerManager) applyPPTPServer() error {
  606. if !m.pptpServer.Enabled {
  607. _ = exec.Command("systemctl", "stop", "pptpd").Run()
  608. m.pptpServer.Running = false
  609. m.pptpServer.LastError = ""
  610. return nil
  611. }
  612. profile := m.profiles[m.pptpServer.DefaultProfile]
  613. if profile == nil {
  614. profile = m.profiles["default-encryption"]
  615. }
  616. localIP := "10.10.20.1"
  617. if profile != nil && profile.LocalAddress != "" {
  618. localIP = profile.LocalAddress
  619. }
  620. remotePool := "10.10.20.10-50"
  621. if profile != nil && profile.RemoteAddress != "" {
  622. remotePool = profile.RemoteAddress
  623. }
  624. // Write /etc/pptpd.conf
  625. pptpdConf := fmt.Sprintf(`option /etc/ppp/pptpd-options
  626. logwtmp
  627. delegate
  628. localip %s
  629. remoteip %s
  630. `, localIP, remotePool)
  631. _ = os.WriteFile("/etc/pptpd.conf", []byte(pptpdConf), 0644)
  632. // Write /etc/ppp/pptpd-options
  633. dns1 := "1.1.1.1"
  634. dns2 := "8.8.8.8"
  635. if profile != nil && profile.DNSServers != "" {
  636. parts := strings.Split(profile.DNSServers, ",")
  637. if len(parts) > 0 {
  638. dns1 = strings.TrimSpace(parts[0])
  639. }
  640. if len(parts) > 1 {
  641. dns2 = strings.TrimSpace(parts[1])
  642. }
  643. }
  644. mppeRule := "require-mppe-128"
  645. if !m.pptpServer.RequireMPPE {
  646. mppeRule = "# require-mppe-128"
  647. }
  648. pptpdOpts := fmt.Sprintf(`name pptpd
  649. refuse-pap
  650. refuse-chap
  651. refuse-mschap
  652. require-mschap-v2
  653. %s
  654. ms-dns %s
  655. ms-dns %s
  656. proxyarp
  657. nodefaultroute
  658. lock
  659. nobsdcomp
  660. novj
  661. novjccomp
  662. nologfd
  663. `, mppeRule, dns1, dns2)
  664. _ = os.WriteFile("/etc/ppp/pptpd-options", []byte(pptpdOpts), 0644)
  665. _ = exec.Command("systemctl", "restart", "pptpd").Run()
  666. time.Sleep(300 * time.Millisecond)
  667. out, _ := exec.Command("systemctl", "is-active", "pptpd").Output()
  668. m.pptpServer.Running = strings.TrimSpace(string(out)) == "active"
  669. m.pptpServer.LastError = ""
  670. return nil
  671. }
  672. // ======================== L2TP Server Management ========================
  673. func (m *PPPServerManager) GetL2TPServer() L2TPServerConfig {
  674. m.mu.Lock()
  675. defer m.mu.Unlock()
  676. out, _ := exec.Command("systemctl", "is-active", "xl2tpd").Output()
  677. m.l2tpServer.Running = strings.TrimSpace(string(out)) == "active"
  678. m.l2tpServer.ActiveSessions = m.countPPPSessions("l2tp")
  679. return m.l2tpServer
  680. }
  681. func (m *PPPServerManager) SetL2TPServer(cfg L2TPServerConfig) error {
  682. m.mu.Lock()
  683. defer m.mu.Unlock()
  684. m.l2tpServer.Enabled = cfg.Enabled
  685. if cfg.Port > 0 {
  686. m.l2tpServer.Port = cfg.Port
  687. }
  688. if cfg.DefaultProfile != "" {
  689. m.l2tpServer.DefaultProfile = cfg.DefaultProfile
  690. }
  691. if cfg.UseIPSec != "" {
  692. m.l2tpServer.UseIPSec = cfg.UseIPSec
  693. }
  694. m.l2tpServer.IPSecSecret = cfg.IPSecSecret
  695. _ = m.save("l2tp_server.json", m.l2tpServer)
  696. return m.applyL2TPServer()
  697. }
  698. func (m *PPPServerManager) applyL2TPServer() error {
  699. if !m.l2tpServer.Enabled {
  700. // When disabled, don't stop xl2tpd completely as client may need it, just reload without LNS
  701. _ = os.WriteFile("/etc/ppp/options.xl2tpd.server", []byte("# disabled\n"), 0644)
  702. _ = exec.Command("systemctl", "reload-or-restart", "xl2tpd").Run()
  703. m.l2tpServer.Running = false
  704. m.l2tpServer.LastError = ""
  705. return nil
  706. }
  707. profile := m.profiles[m.l2tpServer.DefaultProfile]
  708. if profile == nil {
  709. profile = m.profiles["default"]
  710. }
  711. localIP := "10.10.40.1"
  712. if profile != nil && profile.LocalAddress != "" {
  713. localIP = profile.LocalAddress
  714. }
  715. remotePool := "10.10.40.10-10.10.40.50"
  716. if profile != nil && profile.RemoteAddress != "" {
  717. remotePool = strings.TrimSpace(profile.RemoteAddress)
  718. }
  719. // xl2tpd requires range format A-B. If a single IP is provided, convert to IP-IP
  720. if !strings.Contains(remotePool, "-") {
  721. remotePool = fmt.Sprintf("%s-%s", remotePool, remotePool)
  722. }
  723. // Write /etc/xl2tpd/xl2tpd.conf with [lns default]
  724. _ = os.MkdirAll("/etc/xl2tpd", 0755)
  725. xl2tpdConf := fmt.Sprintf(`[global]
  726. port = %d
  727. [lns default]
  728. ip range = %s
  729. local ip = %s
  730. require chap = yes
  731. refuse pap = yes
  732. require authentication = yes
  733. name = l2tpd
  734. pppoptfile = /etc/ppp/options.xl2tpd.server
  735. length bit = yes
  736. `, m.l2tpServer.Port, remotePool, localIP)
  737. _ = os.WriteFile("/etc/xl2tpd/xl2tpd.conf", []byte(xl2tpdConf), 0644)
  738. // Write /etc/ppp/options.xl2tpd.server
  739. dns1 := "1.1.1.1"
  740. dns2 := "8.8.8.8"
  741. if profile != nil && profile.DNSServers != "" {
  742. parts := strings.Split(profile.DNSServers, ",")
  743. if len(parts) > 0 {
  744. dns1 = strings.TrimSpace(parts[0])
  745. }
  746. if len(parts) > 1 {
  747. dns2 = strings.TrimSpace(parts[1])
  748. }
  749. }
  750. opts := fmt.Sprintf(`require-mschap-v2
  751. ms-dns %s
  752. ms-dns %s
  753. auth
  754. ipcp-accept-local
  755. ipcp-accept-remote
  756. mtu 1400
  757. mru 1400
  758. proxyarp
  759. nodefaultroute
  760. `, dns1, dns2)
  761. _ = os.WriteFile("/etc/ppp/options.xl2tpd.server", []byte(opts), 0644)
  762. // Clean restart of xl2tpd to avoid stale PID locks
  763. _ = exec.Command("systemctl", "stop", "xl2tpd").Run()
  764. time.Sleep(100 * time.Millisecond)
  765. _ = exec.Command("pkill", "-9", "-x", "xl2tpd").Run()
  766. _ = os.Remove("/var/run/xl2tpd.pid")
  767. _ = os.Remove("/run/xl2tpd.pid")
  768. _ = exec.Command("systemctl", "start", "xl2tpd").Run()
  769. time.Sleep(300 * time.Millisecond)
  770. out, _ := exec.Command("systemctl", "is-active", "xl2tpd").Output()
  771. m.l2tpServer.Running = strings.TrimSpace(string(out)) == "active"
  772. m.l2tpServer.LastError = ""
  773. return nil
  774. }
  775. // ======================== IPSec Server Management ========================
  776. func (m *PPPServerManager) GetIPSecServer() IPSecServerConfig {
  777. m.mu.Lock()
  778. defer m.mu.Unlock()
  779. out, _ := exec.Command("swanctl", "--list-conns").Output()
  780. m.ipsecServer.Running = strings.Contains(string(out), "rw-server")
  781. m.ipsecServer.ActiveSessions = m.countIPSecSessions()
  782. return m.ipsecServer
  783. }
  784. func (m *PPPServerManager) SetIPSecServer(cfg IPSecServerConfig) error {
  785. m.mu.Lock()
  786. defer m.mu.Unlock()
  787. m.ipsecServer.Enabled = cfg.Enabled
  788. if cfg.PoolAddress != "" {
  789. m.ipsecServer.PoolAddress = cfg.PoolAddress
  790. }
  791. if cfg.PresharedKey != "" {
  792. m.ipsecServer.PresharedKey = cfg.PresharedKey
  793. }
  794. if cfg.LocalSubnet != "" {
  795. m.ipsecServer.LocalSubnet = cfg.LocalSubnet
  796. }
  797. if cfg.DNSServers != "" {
  798. m.ipsecServer.DNSServers = cfg.DNSServers
  799. }
  800. _ = m.save("ipsec_server.json", m.ipsecServer)
  801. return m.applyIPSecServer()
  802. }
  803. func (m *PPPServerManager) applyIPSecServer() error {
  804. confFile := "/etc/swanctl/conf.d/rw-server.conf"
  805. if !m.ipsecServer.Enabled {
  806. _ = os.Remove(confFile)
  807. _ = exec.Command("swanctl", "--load-all").Run()
  808. m.ipsecServer.Running = false
  809. m.ipsecServer.LastError = ""
  810. return nil
  811. }
  812. _ = os.MkdirAll("/etc/swanctl/conf.d", 0755)
  813. swanConf := fmt.Sprintf(`connections {
  814. rw-server {
  815. local_addrs = %%any
  816. pools = rw-pool
  817. local {
  818. auth = psk
  819. id = %%any
  820. }
  821. remote {
  822. auth = psk
  823. }
  824. children {
  825. rw-net {
  826. local_ts = %s
  827. esp_proposals = aes256gcm128-sha256-modp2048,aes256-sha256-modp2048
  828. }
  829. }
  830. }
  831. }
  832. pools {
  833. rw-pool {
  834. addrs = %s
  835. dns = %s
  836. }
  837. }
  838. secrets {
  839. ike-rw {
  840. secret = "%s"
  841. }
  842. }
  843. `, m.ipsecServer.LocalSubnet, m.ipsecServer.PoolAddress, m.ipsecServer.DNSServers, m.ipsecServer.PresharedKey)
  844. if err := os.WriteFile(confFile, []byte(swanConf), 0600); err != nil {
  845. m.ipsecServer.LastError = err.Error()
  846. return err
  847. }
  848. if out, err := exec.Command("swanctl", "--load-all").CombinedOutput(); err != nil {
  849. m.ipsecServer.LastError = strings.TrimSpace(string(out))
  850. return err
  851. }
  852. m.ipsecServer.Running = true
  853. m.ipsecServer.LastError = ""
  854. return nil
  855. }
  856. // ======================== Active Connections & Kill ========================
  857. func (m *PPPServerManager) ListActiveSessions() []ActivePPPSession {
  858. list := make([]ActivePPPSession, 0)
  859. // Read network interfaces matching ppp*
  860. ifaces, err := net.Interfaces()
  861. if err != nil {
  862. return list
  863. }
  864. for _, iface := range ifaces {
  865. if !strings.HasPrefix(iface.Name, "ppp") {
  866. continue
  867. }
  868. addrs, _ := iface.Addrs()
  869. var assignedIP string
  870. for _, a := range addrs {
  871. if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
  872. assignedIP = ipNet.IP.String()
  873. break
  874. }
  875. }
  876. sess := ActivePPPSession{
  877. ID: iface.Name,
  878. Interface: iface.Name,
  879. Address: assignedIP,
  880. Uptime: "active",
  881. }
  882. // Try to detect service from process or default
  883. sess.Service = "ppp"
  884. sess.Username = "client-" + iface.Name
  885. m.populateIfaceTraffic(iface.Name, &sess)
  886. list = append(list, sess)
  887. }
  888. sort.Slice(list, func(i, j int) bool {
  889. return list[i].Interface < list[j].Interface
  890. })
  891. return list
  892. }
  893. func (m *PPPServerManager) DisconnectSession(ifaceName string) error {
  894. if !strings.HasPrefix(ifaceName, "ppp") {
  895. return fmt.Errorf("invalid ppp interface")
  896. }
  897. _ = exec.Command("ip", "link", "set", ifaceName, "down").Run()
  898. _ = exec.Command("pkill", "-f", ifaceName).Run()
  899. return nil
  900. }
  901. func (m *PPPServerManager) populateIfaceTraffic(ifaceName string, sess *ActivePPPSession) {
  902. file, err := os.Open("/proc/net/dev")
  903. if err != nil {
  904. return
  905. }
  906. defer file.Close()
  907. scanner := bufio.NewScanner(file)
  908. for scanner.Scan() {
  909. line := scanner.Text()
  910. if strings.Contains(line, ifaceName+":") {
  911. parts := strings.Fields(line)
  912. if len(parts) >= 10 {
  913. rxBytes, _ := strconv.ParseUint(parts[1], 10, 64)
  914. txBytes, _ := strconv.ParseUint(parts[9], 10, 64)
  915. sess.RxBytes = rxBytes
  916. sess.TxBytes = txBytes
  917. sess.RxHuman = formatBytes(rxBytes)
  918. sess.TxHuman = formatBytes(txBytes)
  919. }
  920. break
  921. }
  922. }
  923. }
  924. func (m *PPPServerManager) countPPPSessions(service string) int {
  925. ifaces, err := net.Interfaces()
  926. if err != nil {
  927. return 0
  928. }
  929. count := 0
  930. for _, i := range ifaces {
  931. if strings.HasPrefix(i.Name, "ppp") {
  932. count++
  933. }
  934. }
  935. return count
  936. }
  937. func (m *PPPServerManager) countIPSecSessions() int {
  938. out, err := exec.Command("swanctl", "--list-sas").Output()
  939. if err != nil {
  940. return 0
  941. }
  942. return strings.Count(string(out), "ESTABLISHED")
  943. }
  944. func (m *PPPServerManager) isProcessRunning(pidFile string) bool {
  945. data, err := os.ReadFile(pidFile)
  946. if err != nil {
  947. return false
  948. }
  949. pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
  950. if err != nil || pid <= 0 {
  951. return false
  952. }
  953. return syscall.Kill(pid, 0) == nil
  954. }
  955. func (m *PPPServerManager) applyAll() {
  956. if m.pppoeServer.Enabled {
  957. _ = m.applyPPPoEServer()
  958. }
  959. if m.pptpServer.Enabled {
  960. _ = m.applyPPTPServer()
  961. }
  962. if m.l2tpServer.Enabled {
  963. _ = m.applyL2TPServer()
  964. }
  965. if m.ipsecServer.Enabled {
  966. _ = m.applyIPSecServer()
  967. }
  968. }