| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247 |
- package vpn
- import (
- "bufio"
- "encoding/json"
- "errors"
- "fmt"
- "log"
- "net"
- "os"
- "os/exec"
- "path/filepath"
- "sort"
- "strconv"
- "strings"
- "sync"
- "syscall"
- "time"
- )
- // ======================== PPP Profiles (/ppp profile) ========================
- type PPPProfile struct {
- ID string `json:"id"`
- Name string `json:"name"` // e.g. "default", "default-encryption", "pool-lan"
- LocalAddress string `json:"local_address"` // e.g. "10.10.10.1" (server IP on tunnel)
- RemoteAddress string `json:"remote_address"` // e.g. "10.10.10.10-10.10.10.50" or "10.10.10.10"
- DNSServers string `json:"dns_servers"` // e.g. "1.1.1.1,8.8.8.8"
- UseEncryption string `json:"use_encryption"` // "no", "yes", "required" (MPPE-128)
- OnlyOne bool `json:"only_one"` // One session per user
- Comment string `json:"comment,omitempty"`
- }
- // ======================== PPP Secrets (/ppp secret) ========================
- type PPPSecret struct {
- ID string `json:"id"`
- Name string `json:"name"` // Username
- Password string `json:"password"` // Password
- Service string `json:"service"` // "any", "pppoe", "pptp", "l2tp"
- Profile string `json:"profile"` // Profile name
- LocalAddress string `json:"local_address,omitempty"`
- RemoteAddress string `json:"remote_address,omitempty"`
- CallerID string `json:"caller_id,omitempty"`
- Comment string `json:"comment,omitempty"`
- Disabled bool `json:"disabled"`
- }
- // ======================== PPPoE Server (/interface pppoe-server server) ========================
- type PPPoEServerConfig struct {
- Enabled bool `json:"enabled"`
- ServiceName string `json:"service_name"` // e.g. "isp-service"
- Interface string `json:"interface"` // e.g. "eth0", "eth0.10", "br0"
- DefaultProfile string `json:"default_profile"`
- OneSessionPerHost bool `json:"one_session_per_host"`
- MaxMTU int `json:"max_mtu"` // default 1480 / 1492
- MaxMRU int `json:"max_mru"` // default 1480 / 1492
- Running bool `json:"running"`
- ActiveSessions int `json:"active_sessions"`
- LastError string `json:"last_error,omitempty"`
- }
- // ======================== PPTP Server (/interface pptp-server server) ========================
- type PPTPServerConfig struct {
- Enabled bool `json:"enabled"`
- Port int `json:"port"` // default 1723
- DefaultProfile string `json:"default_profile"`
- RequireMPPE bool `json:"require_mppe"` // 128-bit MPPE
- Running bool `json:"running"`
- ActiveSessions int `json:"active_sessions"`
- LastError string `json:"last_error,omitempty"`
- }
- // ======================== L2TP Server (/interface l2tp-server server) ========================
- type L2TPServerConfig struct {
- Enabled bool `json:"enabled"`
- Port int `json:"port"` // default 1701
- DefaultProfile string `json:"default_profile"`
- UseIPSec string `json:"use_ipsec"` // "no", "yes", "required"
- IPSecSecret string `json:"ipsec_secret,omitempty"`
- Running bool `json:"running"`
- ActiveSessions int `json:"active_sessions"`
- LastError string `json:"last_error,omitempty"`
- }
- // ======================== IPSec Roadwarrior Server ========================
- type IPSecServerConfig struct {
- Enabled bool `json:"enabled"`
- PoolAddress string `json:"pool_address"` // e.g. "10.10.30.0/24"
- PresharedKey string `json:"preshared_key"`
- LocalSubnet string `json:"local_subnet"` // e.g. "0.0.0.0/0"
- DNSServers string `json:"dns_servers"` // e.g. "1.1.1.1,8.8.8.8"
- Running bool `json:"running"`
- ActiveSessions int `json:"active_sessions"`
- LastError string `json:"last_error,omitempty"`
- }
- // ======================== Active PPP Session (/ppp active) ========================
- type ActivePPPSession struct {
- ID string `json:"id"`
- Interface string `json:"interface"` // e.g. "ppp0"
- Username string `json:"username"`
- Service string `json:"service"` // "pppoe", "pptp", "l2tp"
- CallerID string `json:"caller_id,omitempty"`
- Address string `json:"address"` // client assigned IP
- Uptime string `json:"uptime"`
- RxBytes uint64 `json:"rx_bytes"`
- TxBytes uint64 `json:"tx_bytes"`
- RxHuman string `json:"rx_human,omitempty"`
- TxHuman string `json:"tx_human,omitempty"`
- }
- // ======================== Central PPP & Server Manager ========================
- type PPPServerManager struct {
- mu sync.RWMutex
- baseDir string
- pppDir string
- profiles map[string]*PPPProfile
- secrets map[string]*PPPSecret
- pppoeServer PPPoEServerConfig
- pptpServer PPTPServerConfig
- l2tpServer L2TPServerConfig
- ipsecServer IPSecServerConfig
- pppoePIDFile string
- }
- func NewPPPServerManager() *PPPServerManager {
- mgr := &PPPServerManager{
- baseDir: "/etc/debtik/vpn",
- pppDir: "/etc/ppp",
- profiles: make(map[string]*PPPProfile),
- secrets: make(map[string]*PPPSecret),
- pppoePIDFile: "/var/run/debtik-pppoe-server.pid",
- pppoeServer: PPPoEServerConfig{
- Enabled: false,
- ServiceName: "debtik-pppoe",
- Interface: "eth0",
- DefaultProfile: "default",
- MaxMTU: 1480,
- MaxMRU: 1480,
- },
- pptpServer: PPTPServerConfig{
- Enabled: false,
- Port: 1723,
- DefaultProfile: "default-encryption",
- RequireMPPE: true,
- },
- l2tpServer: L2TPServerConfig{
- Enabled: false,
- Port: 1701,
- DefaultProfile: "default",
- UseIPSec: "no",
- },
- ipsecServer: IPSecServerConfig{
- Enabled: false,
- PoolAddress: "10.10.30.0/24",
- PresharedKey: "DebTikSecret123",
- LocalSubnet: "0.0.0.0/0",
- DNSServers: "1.1.1.1,8.8.8.8",
- },
- }
- mgr.initDefaults()
- mgr.loadAll()
- if err := mgr.SyncSecretsToSystem(); err != nil {
- log.Printf("[PPP] Failed to synchronize secrets: %v", err)
- }
- mgr.applyAll()
- return mgr
- }
- func (m *PPPServerManager) initDefaults() {
- m.profiles["default"] = &PPPProfile{
- ID: "default",
- Name: "default",
- LocalAddress: "10.10.10.1",
- RemoteAddress: "10.10.10.10-10.10.10.50",
- DNSServers: "1.1.1.1,8.8.8.8",
- UseEncryption: "no",
- OnlyOne: true,
- Comment: "Default PPP profile for unencrypted/standard tunnels",
- }
- m.profiles["default-encryption"] = &PPPProfile{
- ID: "default-encryption",
- Name: "default-encryption",
- LocalAddress: "10.10.20.1",
- RemoteAddress: "10.10.20.10-10.10.20.50",
- DNSServers: "1.1.1.1,8.8.8.8",
- UseEncryption: "required",
- OnlyOne: true,
- Comment: "Default PPP profile with required MPPE-128 encryption",
- }
- }
- func (m *PPPServerManager) loadAll() {
- _ = os.MkdirAll(m.baseDir, 0755)
- // Profiles
- if data, err := os.ReadFile(filepath.Join(m.baseDir, "ppp_profiles.json")); err == nil {
- var list []*PPPProfile
- if err := json.Unmarshal(data, &list); err == nil {
- for _, p := range list {
- m.profiles[p.Name] = p
- }
- }
- }
- // Secrets
- if data, err := os.ReadFile(filepath.Join(m.baseDir, "ppp_secrets.json")); err == nil {
- var list []*PPPSecret
- if err := json.Unmarshal(data, &list); err == nil {
- for _, s := range list {
- m.secrets[s.ID] = s
- }
- }
- }
- // PPPoE Server
- if data, err := os.ReadFile(filepath.Join(m.baseDir, "pppoe_server.json")); err == nil {
- _ = json.Unmarshal(data, &m.pppoeServer)
- }
- // PPTP Server
- if data, err := os.ReadFile(filepath.Join(m.baseDir, "pptp_server.json")); err == nil {
- _ = json.Unmarshal(data, &m.pptpServer)
- }
- // L2TP Server
- if data, err := os.ReadFile(filepath.Join(m.baseDir, "l2tp_server.json")); err == nil {
- _ = json.Unmarshal(data, &m.l2tpServer)
- }
- // IPSec Server
- if data, err := os.ReadFile(filepath.Join(m.baseDir, "ipsec_server.json")); err == nil {
- _ = json.Unmarshal(data, &m.ipsecServer)
- }
- }
- func (m *PPPServerManager) save(filename string, v any) error {
- if err := os.MkdirAll(m.baseDir, 0755); err != nil {
- return err
- }
- data, err := json.MarshalIndent(v, "", " ")
- if err != nil {
- return err
- }
- f, err := os.CreateTemp(m.baseDir, ".ppp-*.tmp")
- if err != nil {
- return err
- }
- name := f.Name()
- defer os.Remove(name)
- if err = f.Chmod(0600); err == nil {
- _, err = f.Write(data)
- }
- if err == nil {
- err = f.Sync()
- }
- if closeErr := f.Close(); err == nil {
- err = closeErr
- }
- if err != nil {
- return err
- }
- return os.Rename(name, filepath.Join(m.baseDir, filename))
- }
- // ======================== PPP Profiles CRUD ========================
- func (m *PPPServerManager) ListProfiles() []*PPPProfile {
- m.mu.RLock()
- defer m.mu.RUnlock()
- list := make([]*PPPProfile, 0)
- for _, p := range m.profiles {
- list = append(list, p)
- }
- sort.Slice(list, func(i, j int) bool {
- return list[i].Name < list[j].Name
- })
- return list
- }
- func (m *PPPServerManager) GetProfile(name string) *PPPProfile {
- m.mu.RLock()
- defer m.mu.RUnlock()
- return m.profiles[name]
- }
- func (m *PPPServerManager) SaveProfile(p *PPPProfile) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- if p.Name == "" {
- return fmt.Errorf("profile name is required")
- }
- if p.LocalAddress == "" {
- p.LocalAddress = "10.10.10.1"
- }
- if p.RemoteAddress == "" {
- p.RemoteAddress = "10.10.10.10-10.10.10.50"
- }
- if p.ID == "" {
- p.ID = p.Name
- }
- m.profiles[p.Name] = p
- var list []*PPPProfile
- for _, pr := range m.profiles {
- list = append(list, pr)
- }
- if err := m.save("ppp_profiles.json", list); err != nil {
- return err
- }
- // Re-synchronize secrets to system since secrets may inherit IP addresses from this profile
- if err := m.syncSecretsToSystemLocked(); err != nil {
- return fmt.Errorf("profile saved, but PPP secrets could not be applied: %w", err)
- }
- // Re-apply servers if their configured DefaultProfile was updated
- var applyErrors []error
- if m.l2tpServer.Enabled && m.l2tpServer.DefaultProfile == p.Name {
- if err := m.applyL2TPServer(); err != nil {
- applyErrors = append(applyErrors, fmt.Errorf("L2TP: %w", err))
- }
- }
- if m.pptpServer.Enabled && m.pptpServer.DefaultProfile == p.Name {
- if err := m.applyPPTPServer(); err != nil {
- applyErrors = append(applyErrors, fmt.Errorf("PPTP: %w", err))
- }
- }
- if m.pppoeServer.Enabled && m.pppoeServer.DefaultProfile == p.Name {
- if err := m.applyPPPoEServer(); err != nil {
- applyErrors = append(applyErrors, fmt.Errorf("PPPoE: %w", err))
- }
- }
- if err := errors.Join(applyErrors...); err != nil {
- return fmt.Errorf("profile saved but server reapply failed: %w", err)
- }
- return nil
- }
- func (m *PPPServerManager) DeleteProfile(name string) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- if name == "default" || name == "default-encryption" {
- return fmt.Errorf("cannot delete default profile")
- }
- delete(m.profiles, name)
- var list []*PPPProfile
- for _, pr := range m.profiles {
- list = append(list, pr)
- }
- if err := m.save("ppp_profiles.json", list); err != nil {
- return err
- }
- return m.syncSecretsToSystemLocked()
- }
- // ======================== PPP Secrets CRUD ========================
- func (m *PPPServerManager) ListSecrets() []*PPPSecret {
- m.mu.RLock()
- defer m.mu.RUnlock()
- list := make([]*PPPSecret, 0)
- for _, s := range m.secrets {
- list = append(list, s)
- }
- sort.Slice(list, func(i, j int) bool {
- return list[i].Name < list[j].Name
- })
- return list
- }
- func (m *PPPServerManager) snapshotSecretsLocked() map[string]*PPPSecret {
- before := make(map[string]*PPPSecret, len(m.secrets))
- for id, secret := range m.secrets {
- copy := *secret
- before[id] = ©
- }
- return before
- }
- func (m *PPPServerManager) saveSecretsLocked() error {
- list := make([]*PPPSecret, 0, len(m.secrets))
- for _, secret := range m.secrets {
- list = append(list, secret)
- }
- return m.save("ppp_secrets.json", list)
- }
- func (m *PPPServerManager) commitSecretsLocked(before map[string]*PPPSecret) error {
- if err := m.saveSecretsLocked(); err != nil {
- m.secrets = before
- return fmt.Errorf("saving PPP secrets: %w", err)
- }
- if err := m.syncSecretsToSystemLocked(); err != nil {
- m.secrets = before
- saveErr := m.saveSecretsLocked()
- if saveErr != nil {
- saveErr = fmt.Errorf("restoring saved PPP secrets: %w", saveErr)
- }
- syncErr := m.syncSecretsToSystemLocked()
- if syncErr != nil {
- syncErr = fmt.Errorf("reapplying previous PPP secrets: %w", syncErr)
- }
- return errors.Join(fmt.Errorf("applying PPP secrets: %w", err), saveErr, syncErr)
- }
- return nil
- }
- func (m *PPPServerManager) SaveSecret(s *PPPSecret) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- if s.Name == "" || s.Password == "" {
- return fmt.Errorf("username and password are required")
- }
- if s.Service == "" {
- s.Service = "any"
- }
- if s.Profile == "" {
- s.Profile = "default"
- }
- if s.ID == "" {
- s.ID = fmt.Sprintf("secret-%d", time.Now().UnixNano())
- }
- before := m.snapshotSecretsLocked()
- copy := *s
- m.secrets[s.ID] = ©
- return m.commitSecretsLocked(before)
- }
- func (m *PPPServerManager) SetSecretState(id string, disabled bool) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- secret, ok := m.secrets[id]
- if !ok {
- return fmt.Errorf("secret not found")
- }
- before := m.snapshotSecretsLocked()
- secret.Disabled = disabled
- return m.commitSecretsLocked(before)
- }
- func (m *PPPServerManager) DeleteSecret(id string) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- if _, ok := m.secrets[id]; !ok {
- return fmt.Errorf("secret not found")
- }
- before := m.snapshotSecretsLocked()
- delete(m.secrets, id)
- return m.commitSecretsLocked(before)
- }
- // Helper IP math utilities for dynamic pool allocation per profile
- func parseIPRange(r string) (net.IP, net.IP, error) {
- r = strings.TrimSpace(r)
- parts := strings.Split(r, "-")
- if len(parts) != 2 {
- return nil, nil, fmt.Errorf("invalid range format")
- }
- startIP := net.ParseIP(strings.TrimSpace(parts[0])).To4()
- endIP := net.ParseIP(strings.TrimSpace(parts[1])).To4()
- if startIP == nil || endIP == nil {
- return nil, nil, fmt.Errorf("invalid IP in range")
- }
- return startIP, endIP, nil
- }
- func firstAvailableIPFromRange(r string, used map[string]bool) string {
- startIP, endIP, err := parseIPRange(r)
- if err != nil {
- return ""
- }
- startInt := ipToUint32(startIP)
- endInt := ipToUint32(endIP)
- if startInt > endInt {
- startInt, endInt = endInt, startInt
- }
- for cur := startInt; cur <= endInt; cur++ {
- ipStr := uint32ToIP(cur).String()
- if !used[ipStr] {
- return ipStr
- }
- }
- return startIP.String()
- }
- func ipToUint32(ip net.IP) uint32 {
- return uint32(ip[0])<<24 | uint32(ip[1])<<16 | uint32(ip[2])<<8 | uint32(ip[3])
- }
- func uint32ToIP(n uint32) net.IP {
- return net.IPv4(byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
- }
- // SyncSecretsToSystem synchronizes all enabled secrets into /etc/ppp/chap-secrets and /etc/ppp/pap-secrets
- func (m *PPPServerManager) SyncSecretsToSystem() error {
- m.mu.Lock()
- defer m.mu.Unlock()
- return m.syncSecretsToSystemLocked()
- }
- func (m *PPPServerManager) syncSecretsToSystemLocked() error {
- var lines []string
- lines = append(lines, "# Autogenerated by DebTik - DO NOT EDIT MANUALLY")
- lines = append(lines, "# client\tserver\tsecret\tIP addresses")
- // Track allocated IPs to avoid assigning duplicate static IPs from pools
- allocatedIPs := make(map[string]bool)
- for _, s := range m.secrets {
- if !s.Disabled && s.RemoteAddress != "" && !strings.Contains(s.RemoteAddress, "-") {
- allocatedIPs[strings.TrimSpace(s.RemoteAddress)] = true
- }
- }
- var secretList []*PPPSecret
- for _, s := range m.secrets {
- secretList = append(secretList, s)
- }
- sort.Slice(secretList, func(i, j int) bool {
- return secretList[i].Name < secretList[j].Name
- })
- for _, s := range secretList {
- if s.Disabled {
- continue
- }
- // In Linux pppd, the second field is the system name of the server (e.g. "l2tpd" from xl2tpd).
- // Setting this to "*" allows pppd to authenticate the user across L2TP, PPTP, and PPPoE daemons.
- serviceName := "*"
- ipAddr := "*"
- if s.RemoteAddress != "" {
- trimmed := strings.TrimSpace(s.RemoteAddress)
- if strings.Contains(trimmed, "-") {
- avail := firstAvailableIPFromRange(trimmed, allocatedIPs)
- if avail != "" {
- ipAddr = avail
- allocatedIPs[avail] = true
- }
- } else {
- ipAddr = trimmed
- }
- } else if s.Profile != "" {
- if prof, ok := m.profiles[s.Profile]; ok && prof != nil && prof.RemoteAddress != "" {
- trimmed := strings.TrimSpace(prof.RemoteAddress)
- if !strings.Contains(trimmed, "-") {
- // Single static IP defined in profile
- ipAddr = trimmed
- allocatedIPs[trimmed] = true
- } else {
- // Range defined in profile (e.g. 192.168.133.2-192.168.133.254)
- avail := firstAvailableIPFromRange(trimmed, allocatedIPs)
- if avail != "" {
- ipAddr = avail
- allocatedIPs[avail] = true
- }
- }
- }
- }
- if ipAddr == "" {
- ipAddr = "*"
- }
- lines = append(lines, fmt.Sprintf("\"%s\"\t%s\t\"%s\"\t%s", s.Name, serviceName, s.Password, ipAddr))
- }
- content := strings.Join(lines, "\n") + "\n"
- dir := m.pppDir
- if dir == "" {
- dir = "/etc/ppp"
- }
- for _, name := range []string{"chap-secrets", "pap-secrets"} {
- if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0600); err != nil {
- return fmt.Errorf("writing %s: %w", name, err)
- }
- }
- return nil
- }
- // ======================== PPPoE Server Management ========================
- func (m *PPPServerManager) GetPPPoEServer() PPPoEServerConfig {
- m.mu.Lock()
- defer m.mu.Unlock()
- // Check if running
- m.pppoeServer.Running = m.isProcessRunning(m.pppoePIDFile)
- m.pppoeServer.ActiveSessions = m.countPPPSessions("pppoe")
- return m.pppoeServer
- }
- func (m *PPPServerManager) SetPPPoEServer(cfg PPPoEServerConfig) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- previous := m.pppoeServer
- m.pppoeServer.Enabled = cfg.Enabled
- if cfg.ServiceName != "" {
- m.pppoeServer.ServiceName = cfg.ServiceName
- }
- if cfg.Interface != "" {
- m.pppoeServer.Interface = cfg.Interface
- }
- if cfg.DefaultProfile != "" {
- m.pppoeServer.DefaultProfile = cfg.DefaultProfile
- }
- m.pppoeServer.OneSessionPerHost = cfg.OneSessionPerHost
- if cfg.MaxMTU > 0 {
- m.pppoeServer.MaxMTU = cfg.MaxMTU
- }
- if cfg.MaxMRU > 0 {
- m.pppoeServer.MaxMRU = cfg.MaxMRU
- }
- if err := m.save("pppoe_server.json", m.pppoeServer); err != nil {
- m.pppoeServer = previous
- return fmt.Errorf("saving PPPoE configuration: %w", err)
- }
- if err := m.applyPPPoEServer(); err != nil {
- return fmt.Errorf("PPPoE configuration saved but could not be applied: %w", err)
- }
- return nil
- }
- func (m *PPPServerManager) applyPPPoEServer() error {
- m.stopPPPoEServer()
- if !m.pppoeServer.Enabled {
- m.pppoeServer.Running = false
- m.pppoeServer.LastError = ""
- return nil
- }
- // Prepare pppoe-server-options
- profile := m.profiles[m.pppoeServer.DefaultProfile]
- if profile == nil {
- profile = m.profiles["default"]
- }
- localIP := "10.10.10.1"
- if profile != nil && profile.LocalAddress != "" {
- localIP = profile.LocalAddress
- }
- startIP := "10.10.10.10"
- poolCount := 50
- if profile != nil && profile.RemoteAddress != "" {
- if strings.Contains(profile.RemoteAddress, "-") {
- parts := strings.Split(profile.RemoteAddress, "-")
- startIP = strings.TrimSpace(parts[0])
- } else {
- startIP = profile.RemoteAddress
- }
- }
- // Write /etc/ppp/pppoe-server-options
- dns1 := "1.1.1.1"
- dns2 := "8.8.8.8"
- if profile != nil && profile.DNSServers != "" {
- parts := strings.Split(profile.DNSServers, ",")
- if len(parts) > 0 {
- dns1 = strings.TrimSpace(parts[0])
- }
- if len(parts) > 1 {
- dns2 = strings.TrimSpace(parts[1])
- }
- }
- opts := fmt.Sprintf(`auth
- require-chap
- login
- lcp-echo-interval 10
- lcp-echo-failure 2
- ms-dns %s
- ms-dns %s
- netmask 255.255.255.0
- default-mru
- default-asyncmap
- proxyarp
- `, dns1, dns2)
- if err := os.WriteFile("/etc/ppp/pppoe-server-options", []byte(opts), 0644); err != nil {
- m.pppoeServer.LastError = err.Error()
- return fmt.Errorf("writing PPPoE options: %w", err)
- }
- // Launch pppoe-server
- // pppoe-server -I <if> -L <local_ip> -R <start_ip> -N <count> -S <service> -O /etc/ppp/pppoe-server-options -X <pidfile>
- args := []string{
- "-I", m.pppoeServer.Interface,
- "-L", localIP,
- "-R", startIP,
- "-N", strconv.Itoa(poolCount),
- "-S", m.pppoeServer.ServiceName,
- "-O", "/etc/ppp/pppoe-server-options",
- "-X", m.pppoePIDFile,
- }
- if m.pppoeServer.OneSessionPerHost {
- args = append(args, "-x", "1")
- }
- cmd := exec.Command("/usr/sbin/pppoe-server", args...)
- if out, err := cmd.CombinedOutput(); err != nil {
- m.pppoeServer.LastError = fmt.Sprintf("start failed: %s - %v", strings.TrimSpace(string(out)), err)
- m.pppoeServer.Running = false
- return fmt.Errorf("%s", m.pppoeServer.LastError)
- }
- time.Sleep(300 * time.Millisecond)
- m.pppoeServer.Running = m.isProcessRunning(m.pppoePIDFile)
- if !m.pppoeServer.Running {
- m.pppoeServer.LastError = "PPPoE server did not become active"
- return errors.New(m.pppoeServer.LastError)
- }
- m.pppoeServer.LastError = ""
- return nil
- }
- func (m *PPPServerManager) stopPPPoEServer() {
- if data, err := os.ReadFile(m.pppoePIDFile); err == nil {
- pid, _ := strconv.Atoi(strings.TrimSpace(string(data)))
- if pid > 0 {
- _ = syscall.Kill(pid, syscall.SIGTERM)
- time.Sleep(200 * time.Millisecond)
- _ = syscall.Kill(pid, syscall.SIGKILL)
- }
- _ = os.Remove(m.pppoePIDFile)
- }
- _ = exec.Command("pkill", "-f", "/usr/sbin/pppoe-server").Run()
- }
- // ======================== PPTP Server Management ========================
- func (m *PPPServerManager) GetPPTPServer() PPTPServerConfig {
- m.mu.Lock()
- defer m.mu.Unlock()
- out, _ := exec.Command("systemctl", "is-active", "pptpd").Output()
- m.pptpServer.Running = strings.TrimSpace(string(out)) == "active"
- m.pptpServer.ActiveSessions = m.countPPPSessions("pptp")
- return m.pptpServer
- }
- func (m *PPPServerManager) SetPPTPServer(cfg PPTPServerConfig) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- previous := m.pptpServer
- m.pptpServer.Enabled = cfg.Enabled
- if cfg.Port > 0 {
- m.pptpServer.Port = cfg.Port
- }
- if cfg.DefaultProfile != "" {
- m.pptpServer.DefaultProfile = cfg.DefaultProfile
- }
- m.pptpServer.RequireMPPE = cfg.RequireMPPE
- if err := m.save("pptp_server.json", m.pptpServer); err != nil {
- m.pptpServer = previous
- return fmt.Errorf("saving PPTP configuration: %w", err)
- }
- if err := m.applyPPTPServer(); err != nil {
- return fmt.Errorf("PPTP configuration saved but could not be applied: %w", err)
- }
- return nil
- }
- func (m *PPPServerManager) applyPPTPServer() error {
- if !m.pptpServer.Enabled {
- if out, err := exec.Command("systemctl", "stop", "pptpd").CombinedOutput(); err != nil {
- m.pptpServer.LastError = strings.TrimSpace(string(out))
- return fmt.Errorf("stopping pptpd: %s: %w", m.pptpServer.LastError, err)
- }
- m.pptpServer.Running = false
- m.pptpServer.LastError = ""
- return nil
- }
- profile := m.profiles[m.pptpServer.DefaultProfile]
- if profile == nil {
- profile = m.profiles["default-encryption"]
- }
- localIP := "10.10.20.1"
- if profile != nil && profile.LocalAddress != "" {
- localIP = profile.LocalAddress
- }
- remotePool := "10.10.20.10-50"
- if profile != nil && profile.RemoteAddress != "" {
- remotePool = profile.RemoteAddress
- }
- // Write /etc/pptpd.conf
- pptpdConf := fmt.Sprintf(`option /etc/ppp/pptpd-options
- logwtmp
- delegate
- localip %s
- remoteip %s
- `, localIP, remotePool)
- if err := os.WriteFile("/etc/pptpd.conf", []byte(pptpdConf), 0644); err != nil {
- m.pptpServer.LastError = err.Error()
- return fmt.Errorf("writing /etc/pptpd.conf: %w", err)
- }
- // Write /etc/ppp/pptpd-options
- dns1 := "1.1.1.1"
- dns2 := "8.8.8.8"
- if profile != nil && profile.DNSServers != "" {
- parts := strings.Split(profile.DNSServers, ",")
- if len(parts) > 0 {
- dns1 = strings.TrimSpace(parts[0])
- }
- if len(parts) > 1 {
- dns2 = strings.TrimSpace(parts[1])
- }
- }
- mppeRule := "require-mppe-128"
- if !m.pptpServer.RequireMPPE {
- mppeRule = "# require-mppe-128"
- }
- pptpdOpts := fmt.Sprintf(`name pptpd
- refuse-pap
- refuse-chap
- refuse-mschap
- require-mschap-v2
- %s
- ms-dns %s
- ms-dns %s
- proxyarp
- nodefaultroute
- lock
- nobsdcomp
- novj
- novjccomp
- nologfd
- `, mppeRule, dns1, dns2)
- if err := os.WriteFile("/etc/ppp/pptpd-options", []byte(pptpdOpts), 0644); err != nil {
- m.pptpServer.LastError = err.Error()
- return fmt.Errorf("writing /etc/ppp/pptpd-options: %w", err)
- }
- if out, err := exec.Command("systemctl", "restart", "pptpd").CombinedOutput(); err != nil {
- m.pptpServer.LastError = strings.TrimSpace(string(out))
- return fmt.Errorf("restarting pptpd: %s: %w", m.pptpServer.LastError, err)
- }
- time.Sleep(300 * time.Millisecond)
- out, _ := exec.Command("systemctl", "is-active", "pptpd").Output()
- m.pptpServer.Running = strings.TrimSpace(string(out)) == "active"
- if !m.pptpServer.Running {
- m.pptpServer.LastError = "pptpd is not active"
- return errors.New(m.pptpServer.LastError)
- }
- m.pptpServer.LastError = ""
- return nil
- }
- // ======================== L2TP Server Management ========================
- func (m *PPPServerManager) GetL2TPServer() L2TPServerConfig {
- m.mu.Lock()
- defer m.mu.Unlock()
- out, _ := exec.Command("systemctl", "is-active", "xl2tpd").Output()
- m.l2tpServer.Running = strings.TrimSpace(string(out)) == "active"
- m.l2tpServer.ActiveSessions = m.countPPPSessions("l2tp")
- return m.l2tpServer
- }
- func (m *PPPServerManager) SetL2TPServer(cfg L2TPServerConfig) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- previous := m.l2tpServer
- m.l2tpServer.Enabled = cfg.Enabled
- if cfg.Port > 0 {
- m.l2tpServer.Port = cfg.Port
- }
- if cfg.DefaultProfile != "" {
- m.l2tpServer.DefaultProfile = cfg.DefaultProfile
- }
- if cfg.UseIPSec != "" {
- m.l2tpServer.UseIPSec = cfg.UseIPSec
- }
- m.l2tpServer.IPSecSecret = cfg.IPSecSecret
- if err := m.save("l2tp_server.json", m.l2tpServer); err != nil {
- m.l2tpServer = previous
- return fmt.Errorf("saving L2TP configuration: %w", err)
- }
- if err := m.applyL2TPServer(); err != nil {
- return fmt.Errorf("L2TP configuration saved but could not be applied: %w", err)
- }
- return nil
- }
- func (m *PPPServerManager) applyL2TPServer() error {
- if !m.l2tpServer.Enabled {
- // When disabled, don't stop xl2tpd completely as client may need it, just reload without LNS
- if err := os.WriteFile("/etc/ppp/options.xl2tpd.server", []byte("# disabled\n"), 0644); err != nil {
- m.l2tpServer.LastError = err.Error()
- return fmt.Errorf("writing L2TP options: %w", err)
- }
- if out, err := exec.Command("systemctl", "reload-or-restart", "xl2tpd").CombinedOutput(); err != nil {
- m.l2tpServer.LastError = strings.TrimSpace(string(out))
- return fmt.Errorf("reloading xl2tpd: %s: %w", m.l2tpServer.LastError, err)
- }
- m.l2tpServer.Running = false
- m.l2tpServer.LastError = ""
- return nil
- }
- profile := m.profiles[m.l2tpServer.DefaultProfile]
- if profile == nil {
- profile = m.profiles["default"]
- }
- localIP := "10.10.40.1"
- if profile != nil && profile.LocalAddress != "" {
- localIP = profile.LocalAddress
- }
- remotePool := "10.10.40.10-10.10.40.50"
- if profile != nil && profile.RemoteAddress != "" {
- remotePool = strings.TrimSpace(profile.RemoteAddress)
- }
- // xl2tpd requires range format A-B. If a single IP is provided, convert to IP-IP
- if !strings.Contains(remotePool, "-") {
- remotePool = fmt.Sprintf("%s-%s", remotePool, remotePool)
- }
- // Write /etc/xl2tpd/xl2tpd.conf with [lns default]
- if err := os.MkdirAll("/etc/xl2tpd", 0755); err != nil {
- m.l2tpServer.LastError = err.Error()
- return fmt.Errorf("creating L2TP directory: %w", err)
- }
- xl2tpdConf := fmt.Sprintf(`[global]
- port = %d
- [lns default]
- ip range = %s
- local ip = %s
- require chap = yes
- refuse pap = yes
- require authentication = yes
- name = l2tpd
- pppoptfile = /etc/ppp/options.xl2tpd.server
- length bit = yes
- `, m.l2tpServer.Port, remotePool, localIP)
- if err := os.WriteFile("/etc/xl2tpd/xl2tpd.conf", []byte(xl2tpdConf), 0644); err != nil {
- m.l2tpServer.LastError = err.Error()
- return fmt.Errorf("writing /etc/xl2tpd/xl2tpd.conf: %w", err)
- }
- // Write /etc/ppp/options.xl2tpd.server
- dns1 := "1.1.1.1"
- dns2 := "8.8.8.8"
- if profile != nil && profile.DNSServers != "" {
- parts := strings.Split(profile.DNSServers, ",")
- if len(parts) > 0 {
- dns1 = strings.TrimSpace(parts[0])
- }
- if len(parts) > 1 {
- dns2 = strings.TrimSpace(parts[1])
- }
- }
- opts := fmt.Sprintf(`require-mschap-v2
- ms-dns %s
- ms-dns %s
- auth
- ipcp-accept-local
- ipcp-accept-remote
- mtu 1400
- mru 1400
- proxyarp
- nodefaultroute
- `, dns1, dns2)
- if err := os.WriteFile("/etc/ppp/options.xl2tpd.server", []byte(opts), 0644); err != nil {
- m.l2tpServer.LastError = err.Error()
- return fmt.Errorf("writing /etc/ppp/options.xl2tpd.server: %w", err)
- }
- // Clean restart of xl2tpd to avoid stale PID locks
- _ = exec.Command("systemctl", "stop", "xl2tpd").Run()
- time.Sleep(100 * time.Millisecond)
- _ = exec.Command("pkill", "-9", "-x", "xl2tpd").Run()
- _ = os.Remove("/var/run/xl2tpd.pid")
- _ = os.Remove("/run/xl2tpd.pid")
- if out, err := exec.Command("systemctl", "start", "xl2tpd").CombinedOutput(); err != nil {
- m.l2tpServer.LastError = strings.TrimSpace(string(out))
- return fmt.Errorf("starting xl2tpd: %s: %w", m.l2tpServer.LastError, err)
- }
- time.Sleep(300 * time.Millisecond)
- out, _ := exec.Command("systemctl", "is-active", "xl2tpd").Output()
- m.l2tpServer.Running = strings.TrimSpace(string(out)) == "active"
- if !m.l2tpServer.Running {
- m.l2tpServer.LastError = "xl2tpd is not active"
- return errors.New(m.l2tpServer.LastError)
- }
- m.l2tpServer.LastError = ""
- return nil
- }
- // ======================== IPSec Server Management ========================
- func (m *PPPServerManager) GetIPSecServer() IPSecServerConfig {
- m.mu.Lock()
- defer m.mu.Unlock()
- out, _ := exec.Command("swanctl", "--list-conns").Output()
- m.ipsecServer.Running = strings.Contains(string(out), "rw-server")
- m.ipsecServer.ActiveSessions = m.countIPSecSessions()
- return m.ipsecServer
- }
- func (m *PPPServerManager) SetIPSecServer(cfg IPSecServerConfig) error {
- m.mu.Lock()
- defer m.mu.Unlock()
- previous := m.ipsecServer
- m.ipsecServer.Enabled = cfg.Enabled
- if cfg.PoolAddress != "" {
- m.ipsecServer.PoolAddress = cfg.PoolAddress
- }
- if cfg.PresharedKey != "" {
- m.ipsecServer.PresharedKey = cfg.PresharedKey
- }
- if cfg.LocalSubnet != "" {
- m.ipsecServer.LocalSubnet = cfg.LocalSubnet
- }
- if cfg.DNSServers != "" {
- m.ipsecServer.DNSServers = cfg.DNSServers
- }
- if err := m.save("ipsec_server.json", m.ipsecServer); err != nil {
- m.ipsecServer = previous
- return fmt.Errorf("saving IPSec configuration: %w", err)
- }
- if err := m.applyIPSecServer(); err != nil {
- return fmt.Errorf("IPSec configuration saved but could not be applied: %w", err)
- }
- return nil
- }
- func (m *PPPServerManager) applyIPSecServer() error {
- confFile := "/etc/swanctl/conf.d/rw-server.conf"
- if !m.ipsecServer.Enabled {
- if err := os.Remove(confFile); err != nil && !os.IsNotExist(err) {
- return fmt.Errorf("removing IPsec server configuration: %w", err)
- }
- if out, err := exec.Command("swanctl", "--load-all").CombinedOutput(); err != nil {
- return fmt.Errorf("reloading IPsec configuration: %w: %s", err, strings.TrimSpace(string(out)))
- }
- out, err := exec.Command("swanctl", "--list-conns").CombinedOutput()
- if err != nil {
- return fmt.Errorf("checking IPsec connections: %w: %s", err, strings.TrimSpace(string(out)))
- }
- for _, line := range strings.Split(string(out), "\n") {
- if strings.HasPrefix(strings.TrimSpace(line), "rw-server:") {
- return fmt.Errorf("IPsec server connection remains loaded after reload")
- }
- }
- m.ipsecServer.Running = false
- m.ipsecServer.LastError = ""
- return nil
- }
- if err := os.MkdirAll("/etc/swanctl/conf.d", 0755); err != nil {
- return fmt.Errorf("creating IPsec configuration directory: %w", err)
- }
- swanConf := fmt.Sprintf(`connections {
- rw-server {
- local_addrs = %%any
- pools = rw-pool
- local {
- auth = psk
- id = %%any
- }
- remote {
- auth = psk
- }
- children {
- rw-net {
- local_ts = %s
- esp_proposals = aes256gcm128-sha256-modp2048,aes256-sha256-modp2048
- }
- }
- }
- }
- pools {
- rw-pool {
- addrs = %s
- dns = %s
- }
- }
- secrets {
- ike-rw {
- secret = "%s"
- }
- }
- `, m.ipsecServer.LocalSubnet, m.ipsecServer.PoolAddress, m.ipsecServer.DNSServers, m.ipsecServer.PresharedKey)
- if err := os.WriteFile(confFile, []byte(swanConf), 0600); err != nil {
- m.ipsecServer.LastError = err.Error()
- return err
- }
- if out, err := exec.Command("swanctl", "--load-all").CombinedOutput(); err != nil {
- m.ipsecServer.LastError = strings.TrimSpace(string(out))
- return err
- }
- m.ipsecServer.Running = true
- m.ipsecServer.LastError = ""
- return nil
- }
- // ======================== Active Connections & Kill ========================
- func (m *PPPServerManager) ListActiveSessions() []ActivePPPSession {
- list := make([]ActivePPPSession, 0)
- // Read network interfaces matching ppp*
- ifaces, err := net.Interfaces()
- if err != nil {
- return list
- }
- for _, iface := range ifaces {
- if !strings.HasPrefix(iface.Name, "ppp") {
- continue
- }
- addrs, _ := iface.Addrs()
- var assignedIP string
- for _, a := range addrs {
- if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
- assignedIP = ipNet.IP.String()
- break
- }
- }
- sess := ActivePPPSession{
- ID: iface.Name,
- Interface: iface.Name,
- Address: assignedIP,
- Uptime: "active",
- }
- // Try to detect service from process or default
- sess.Service = "ppp"
- sess.Username = "client-" + iface.Name
- m.populateIfaceTraffic(iface.Name, &sess)
- list = append(list, sess)
- }
- sort.Slice(list, func(i, j int) bool {
- return list[i].Interface < list[j].Interface
- })
- return list
- }
- func (m *PPPServerManager) DisconnectSession(ifaceName string) error {
- if !strings.HasPrefix(ifaceName, "ppp") {
- return fmt.Errorf("invalid ppp interface")
- }
- _ = exec.Command("ip", "link", "set", ifaceName, "down").Run()
- _ = exec.Command("pkill", "-f", ifaceName).Run()
- return nil
- }
- func (m *PPPServerManager) populateIfaceTraffic(ifaceName string, sess *ActivePPPSession) {
- file, err := os.Open("/proc/net/dev")
- if err != nil {
- return
- }
- defer file.Close()
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- line := scanner.Text()
- if strings.Contains(line, ifaceName+":") {
- parts := strings.Fields(line)
- if len(parts) >= 10 {
- rxBytes, _ := strconv.ParseUint(parts[1], 10, 64)
- txBytes, _ := strconv.ParseUint(parts[9], 10, 64)
- sess.RxBytes = rxBytes
- sess.TxBytes = txBytes
- sess.RxHuman = formatBytes(rxBytes)
- sess.TxHuman = formatBytes(txBytes)
- }
- break
- }
- }
- }
- func (m *PPPServerManager) countPPPSessions(service string) int {
- ifaces, err := net.Interfaces()
- if err != nil {
- return 0
- }
- count := 0
- for _, i := range ifaces {
- if strings.HasPrefix(i.Name, "ppp") {
- count++
- }
- }
- return count
- }
- func (m *PPPServerManager) countIPSecSessions() int {
- out, err := exec.Command("swanctl", "--list-sas").Output()
- if err != nil {
- return 0
- }
- return strings.Count(string(out), "ESTABLISHED")
- }
- func (m *PPPServerManager) isProcessRunning(pidFile string) bool {
- data, err := os.ReadFile(pidFile)
- if err != nil {
- return false
- }
- pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
- if err != nil || pid <= 0 {
- return false
- }
- return syscall.Kill(pid, 0) == nil
- }
- func (m *PPPServerManager) applyAll() {
- if m.pppoeServer.Enabled {
- _ = m.applyPPPoEServer()
- }
- if m.pptpServer.Enabled {
- _ = m.applyPPTPServer()
- }
- if m.l2tpServer.Enabled {
- _ = m.applyL2TPServer()
- }
- if m.ipsecServer.Enabled {
- _ = m.applyIPSecServer()
- }
- }
|