ppp_server.go 29 KB

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