manager.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. package firewall
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "sync"
  8. "time"
  9. )
  10. const (
  11. FilterStorePath = "/etc/proxmox-router/firewall/filter.json"
  12. NATStorePath = "/etc/proxmox-router/firewall/nat.json"
  13. MangleStorePath = "/etc/proxmox-router/firewall/mangle.json"
  14. AddressListsStorePath = "/etc/proxmox-router/firewall/address_lists.json"
  15. )
  16. type FirewallManager struct {
  17. mu sync.Mutex
  18. filterRules []FilterRule
  19. natRules []NATRule
  20. mangleRules []MangleRule
  21. addressLists []AddressListEntry
  22. geoIPMgr *GeoIPManager
  23. }
  24. func NewFirewallManager() *FirewallManager {
  25. m := &FirewallManager{
  26. filterRules: make([]FilterRule, 0),
  27. natRules: make([]NATRule, 0),
  28. mangleRules: make([]MangleRule, 0),
  29. addressLists: make([]AddressListEntry, 0),
  30. geoIPMgr: NewGeoIPManager(),
  31. }
  32. m.load()
  33. // If clean installation and no rules exist, initialize default sensible router rules (like RouterOS default firewall)
  34. if len(m.filterRules) == 0 && len(m.natRules) == 0 {
  35. m.initDefaultRules()
  36. }
  37. _ = m.Apply()
  38. return m
  39. }
  40. func (m *FirewallManager) initDefaultRules() {
  41. // Default Masquerade NAT
  42. m.natRules = append(m.natRules, NATRule{
  43. ID: fmt.Sprintf("nat-%d", time.Now().UnixNano()),
  44. Order: 1,
  45. Chain: "srcnat",
  46. Action: "masquerade",
  47. Comment: "defconf: masquerade outgoing traffic",
  48. Disabled: false,
  49. })
  50. // Default Fasttrack / Established,Related Filter
  51. m.filterRules = append(m.filterRules, FilterRule{
  52. ID: fmt.Sprintf("filter-%d-1", time.Now().UnixNano()),
  53. Order: 1,
  54. Chain: "input",
  55. Action: "accept",
  56. ConnectionState: []string{"established", "related"},
  57. Comment: "defconf: accept established,related",
  58. Disabled: false,
  59. })
  60. m.filterRules = append(m.filterRules, FilterRule{
  61. ID: fmt.Sprintf("filter-%d-2", time.Now().UnixNano()),
  62. Order: 2,
  63. Chain: "forward",
  64. Action: "accept",
  65. ConnectionState: []string{"established", "related"},
  66. Comment: "defconf: accept established,related forward",
  67. Disabled: false,
  68. })
  69. _ = m.save()
  70. }
  71. func (m *FirewallManager) load() {
  72. if data, err := os.ReadFile(FilterStorePath); err == nil {
  73. _ = json.Unmarshal(data, &m.filterRules)
  74. }
  75. if data, err := os.ReadFile(NATStorePath); err == nil {
  76. _ = json.Unmarshal(data, &m.natRules)
  77. }
  78. if data, err := os.ReadFile(MangleStorePath); err == nil {
  79. _ = json.Unmarshal(data, &m.mangleRules)
  80. }
  81. if data, err := os.ReadFile(AddressListsStorePath); err == nil {
  82. _ = json.Unmarshal(data, &m.addressLists)
  83. }
  84. }
  85. func (m *FirewallManager) save() error {
  86. _ = os.MkdirAll("/etc/proxmox-router/firewall", 0755)
  87. if d, err := json.MarshalIndent(m.filterRules, "", " "); err == nil {
  88. _ = os.WriteFile(FilterStorePath, d, 0600)
  89. }
  90. if d, err := json.MarshalIndent(m.natRules, "", " "); err == nil {
  91. _ = os.WriteFile(NATStorePath, d, 0600)
  92. }
  93. if d, err := json.MarshalIndent(m.mangleRules, "", " "); err == nil {
  94. _ = os.WriteFile(MangleStorePath, d, 0600)
  95. }
  96. if d, err := json.MarshalIndent(m.addressLists, "", " "); err == nil {
  97. _ = os.WriteFile(AddressListsStorePath, d, 0600)
  98. }
  99. return nil
  100. }
  101. // Apply re-synchronizes AddressLists & GeoIP sets with ipset and applies iptables
  102. func (m *FirewallManager) Apply() error {
  103. // Sync GeoIP country sets
  104. if m.geoIPMgr != nil {
  105. _ = m.geoIPMgr.ApplyAllEnabledSets()
  106. // Also ensure any GeoIP lists explicitly referenced in active rules are loaded into ipset
  107. for _, r := range m.filterRules {
  108. if !r.Disabled {
  109. if r.SrcGeoIP != "" { _ = m.geoIPMgr.EnsureCountryOrPreset(r.SrcGeoIP) }
  110. if r.DstGeoIP != "" { _ = m.geoIPMgr.EnsureCountryOrPreset(r.DstGeoIP) }
  111. }
  112. }
  113. for _, r := range m.natRules {
  114. if !r.Disabled {
  115. if r.SrcGeoIP != "" { _ = m.geoIPMgr.EnsureCountryOrPreset(r.SrcGeoIP) }
  116. if r.DstGeoIP != "" { _ = m.geoIPMgr.EnsureCountryOrPreset(r.DstGeoIP) }
  117. }
  118. }
  119. for _, r := range m.mangleRules {
  120. if !r.Disabled {
  121. if r.SrcGeoIP != "" { _ = m.geoIPMgr.EnsureCountryOrPreset(r.SrcGeoIP) }
  122. if r.DstGeoIP != "" { _ = m.geoIPMgr.EnsureCountryOrPreset(r.DstGeoIP) }
  123. }
  124. }
  125. }
  126. // Collect any custom address lists referenced in active rules
  127. var refLists []string
  128. for _, r := range m.filterRules {
  129. if !r.Disabled {
  130. if r.SrcAddressList != "" { refLists = append(refLists, r.SrcAddressList) }
  131. if r.DstAddressList != "" { refLists = append(refLists, r.DstAddressList) }
  132. if r.AddressList != "" { refLists = append(refLists, r.AddressList) }
  133. }
  134. }
  135. for _, r := range m.natRules {
  136. if !r.Disabled {
  137. if r.SrcAddressList != "" { refLists = append(refLists, r.SrcAddressList) }
  138. if r.DstAddressList != "" { refLists = append(refLists, r.DstAddressList) }
  139. if r.AddressList != "" { refLists = append(refLists, r.AddressList) }
  140. }
  141. }
  142. for _, r := range m.mangleRules {
  143. if !r.Disabled {
  144. if r.SrcAddressList != "" { refLists = append(refLists, r.SrcAddressList) }
  145. if r.DstAddressList != "" { refLists = append(refLists, r.DstAddressList) }
  146. if r.AddressList != "" { refLists = append(refLists, r.AddressList) }
  147. }
  148. }
  149. // Sync custom ipset address lists
  150. _ = SyncAddressLists(m.addressLists, refLists...)
  151. payload := BuildIPTablesRestore(m.filterRules, m.natRules, m.mangleRules)
  152. return ApplyIPTables(payload)
  153. }
  154. func (m *FirewallManager) GeoIP() *GeoIPManager {
  155. return m.geoIPMgr
  156. }
  157. // ==================== Filter Rules ====================
  158. func (m *FirewallManager) ListFilterRules() []FilterRule {
  159. m.mu.Lock()
  160. defer m.mu.Unlock()
  161. counters, _ := ReadRuleCounters(m.filterRules, m.natRules, m.mangleRules)
  162. res := make([]FilterRule, len(m.filterRules))
  163. for i, r := range m.filterRules {
  164. res[i] = r
  165. if c, ok := counters[r.ID]; ok {
  166. res[i].Packets = c[0]
  167. res[i].Bytes = c[1]
  168. }
  169. }
  170. return res
  171. }
  172. func (m *FirewallManager) SaveFilterRule(r FilterRule) error {
  173. m.mu.Lock()
  174. defer m.mu.Unlock()
  175. if r.ID == "" {
  176. r.ID = fmt.Sprintf("filter-%d", time.Now().UnixNano())
  177. }
  178. found := false
  179. for i, existing := range m.filterRules {
  180. if existing.ID == r.ID {
  181. r.Order = existing.Order
  182. m.filterRules[i] = r
  183. found = true
  184. break
  185. }
  186. }
  187. if !found {
  188. r.Order = len(m.filterRules) + 1
  189. m.filterRules = append(m.filterRules, r)
  190. }
  191. _ = m.save()
  192. return m.Apply()
  193. }
  194. func (m *FirewallManager) DeleteFilterRule(id string) error {
  195. m.mu.Lock()
  196. defer m.mu.Unlock()
  197. var updated []FilterRule
  198. for _, r := range m.filterRules {
  199. if r.ID != id {
  200. updated = append(updated, r)
  201. }
  202. }
  203. for i := range updated {
  204. updated[i].Order = i + 1
  205. }
  206. m.filterRules = updated
  207. _ = m.save()
  208. return m.Apply()
  209. }
  210. func (m *FirewallManager) MoveFilterRule(id string, dir string) error {
  211. m.mu.Lock()
  212. defer m.mu.Unlock()
  213. idx := -1
  214. for i, r := range m.filterRules {
  215. if r.ID == id {
  216. idx = i
  217. break
  218. }
  219. }
  220. if idx == -1 {
  221. return fmt.Errorf("rule not found")
  222. }
  223. if dir == "up" && idx > 0 {
  224. m.filterRules[idx], m.filterRules[idx-1] = m.filterRules[idx-1], m.filterRules[idx]
  225. } else if dir == "down" && idx < len(m.filterRules)-1 {
  226. m.filterRules[idx], m.filterRules[idx+1] = m.filterRules[idx+1], m.filterRules[idx]
  227. }
  228. for i := range m.filterRules {
  229. m.filterRules[i].Order = i + 1
  230. }
  231. _ = m.save()
  232. return m.Apply()
  233. }
  234. func (m *FirewallManager) SetFilterRuleState(id string, disabled bool) error {
  235. m.mu.Lock()
  236. defer m.mu.Unlock()
  237. for i := range m.filterRules {
  238. if m.filterRules[i].ID == id {
  239. m.filterRules[i].Disabled = disabled
  240. _ = m.save()
  241. return m.Apply()
  242. }
  243. }
  244. return fmt.Errorf("rule not found")
  245. }
  246. // ==================== NAT Rules ====================
  247. func (m *FirewallManager) ListNATRules() []NATRule {
  248. m.mu.Lock()
  249. defer m.mu.Unlock()
  250. counters, _ := ReadRuleCounters(m.filterRules, m.natRules, m.mangleRules)
  251. res := make([]NATRule, len(m.natRules))
  252. for i, r := range m.natRules {
  253. res[i] = r
  254. if c, ok := counters[r.ID]; ok {
  255. res[i].Packets = c[0]
  256. res[i].Bytes = c[1]
  257. }
  258. }
  259. return res
  260. }
  261. func (m *FirewallManager) SaveNATRule(r NATRule) error {
  262. m.mu.Lock()
  263. defer m.mu.Unlock()
  264. if r.ID == "" {
  265. r.ID = fmt.Sprintf("nat-%d", time.Now().UnixNano())
  266. }
  267. found := false
  268. for i, existing := range m.natRules {
  269. if existing.ID == r.ID {
  270. r.Order = existing.Order
  271. m.natRules[i] = r
  272. found = true
  273. break
  274. }
  275. }
  276. if !found {
  277. r.Order = len(m.natRules) + 1
  278. m.natRules = append(m.natRules, r)
  279. }
  280. _ = m.save()
  281. return m.Apply()
  282. }
  283. func (m *FirewallManager) DeleteNATRule(id string) error {
  284. m.mu.Lock()
  285. defer m.mu.Unlock()
  286. var updated []NATRule
  287. for _, r := range m.natRules {
  288. if r.ID != id {
  289. updated = append(updated, r)
  290. }
  291. }
  292. for i := range updated {
  293. updated[i].Order = i + 1
  294. }
  295. m.natRules = updated
  296. _ = m.save()
  297. return m.Apply()
  298. }
  299. func (m *FirewallManager) MoveNATRule(id string, dir string) error {
  300. m.mu.Lock()
  301. defer m.mu.Unlock()
  302. idx := -1
  303. for i, r := range m.natRules {
  304. if r.ID == id {
  305. idx = i
  306. break
  307. }
  308. }
  309. if idx == -1 {
  310. return fmt.Errorf("rule not found")
  311. }
  312. if dir == "up" && idx > 0 {
  313. m.natRules[idx], m.natRules[idx-1] = m.natRules[idx-1], m.natRules[idx]
  314. } else if dir == "down" && idx < len(m.natRules)-1 {
  315. m.natRules[idx], m.natRules[idx+1] = m.natRules[idx+1], m.natRules[idx]
  316. }
  317. for i := range m.natRules {
  318. m.natRules[i].Order = i + 1
  319. }
  320. _ = m.save()
  321. return m.Apply()
  322. }
  323. func (m *FirewallManager) SetNATRuleState(id string, disabled bool) error {
  324. m.mu.Lock()
  325. defer m.mu.Unlock()
  326. for i := range m.natRules {
  327. if m.natRules[i].ID == id {
  328. m.natRules[i].Disabled = disabled
  329. _ = m.save()
  330. return m.Apply()
  331. }
  332. }
  333. return fmt.Errorf("rule not found")
  334. }
  335. // ==================== Mangle Rules ====================
  336. func (m *FirewallManager) ListMangleRules() []MangleRule {
  337. m.mu.Lock()
  338. defer m.mu.Unlock()
  339. counters, _ := ReadRuleCounters(m.filterRules, m.natRules, m.mangleRules)
  340. res := make([]MangleRule, len(m.mangleRules))
  341. for i, r := range m.mangleRules {
  342. res[i] = r
  343. if c, ok := counters[r.ID]; ok {
  344. res[i].Packets = c[0]
  345. res[i].Bytes = c[1]
  346. }
  347. }
  348. return res
  349. }
  350. func (m *FirewallManager) SaveMangleRule(r MangleRule) error {
  351. m.mu.Lock()
  352. defer m.mu.Unlock()
  353. if r.ID == "" {
  354. r.ID = fmt.Sprintf("mangle-%d", time.Now().UnixNano())
  355. }
  356. found := false
  357. for i, existing := range m.mangleRules {
  358. if existing.ID == r.ID {
  359. r.Order = existing.Order
  360. m.mangleRules[i] = r
  361. found = true
  362. break
  363. }
  364. }
  365. if !found {
  366. r.Order = len(m.mangleRules) + 1
  367. m.mangleRules = append(m.mangleRules, r)
  368. }
  369. _ = m.save()
  370. return m.Apply()
  371. }
  372. func (m *FirewallManager) DeleteMangleRule(id string) error {
  373. m.mu.Lock()
  374. defer m.mu.Unlock()
  375. var updated []MangleRule
  376. for _, r := range m.mangleRules {
  377. if r.ID != id {
  378. updated = append(updated, r)
  379. }
  380. }
  381. for i := range updated {
  382. updated[i].Order = i + 1
  383. }
  384. m.mangleRules = updated
  385. _ = m.save()
  386. return m.Apply()
  387. }
  388. func (m *FirewallManager) MoveMangleRule(id string, dir string) error {
  389. m.mu.Lock()
  390. defer m.mu.Unlock()
  391. idx := -1
  392. for i, r := range m.mangleRules {
  393. if r.ID == id {
  394. idx = i
  395. break
  396. }
  397. }
  398. if idx == -1 {
  399. return fmt.Errorf("rule not found")
  400. }
  401. if dir == "up" && idx > 0 {
  402. m.mangleRules[idx], m.mangleRules[idx-1] = m.mangleRules[idx-1], m.mangleRules[idx]
  403. } else if dir == "down" && idx < len(m.mangleRules)-1 {
  404. m.mangleRules[idx], m.mangleRules[idx+1] = m.mangleRules[idx+1], m.mangleRules[idx]
  405. }
  406. for i := range m.mangleRules {
  407. m.mangleRules[i].Order = i + 1
  408. }
  409. _ = m.save()
  410. return m.Apply()
  411. }
  412. func (m *FirewallManager) SetMangleRuleState(id string, disabled bool) error {
  413. m.mu.Lock()
  414. defer m.mu.Unlock()
  415. for i := range m.mangleRules {
  416. if m.mangleRules[i].ID == id {
  417. m.mangleRules[i].Disabled = disabled
  418. _ = m.save()
  419. return m.Apply()
  420. }
  421. }
  422. return fmt.Errorf("rule not found")
  423. }
  424. // ==================== Address Lists ====================
  425. func (m *FirewallManager) ListAddressLists() []AddressListEntry {
  426. m.mu.Lock()
  427. defer m.mu.Unlock()
  428. res := make([]AddressListEntry, len(m.addressLists))
  429. copy(res, m.addressLists)
  430. return res
  431. }
  432. func (m *FirewallManager) SaveAddressListEntry(e AddressListEntry) error {
  433. m.mu.Lock()
  434. defer m.mu.Unlock()
  435. if e.ID == "" {
  436. e.ID = fmt.Sprintf("addrlist-%d", time.Now().UnixNano())
  437. }
  438. found := false
  439. for i, existing := range m.addressLists {
  440. if existing.ID == e.ID {
  441. m.addressLists[i] = e
  442. found = true
  443. break
  444. }
  445. }
  446. if !found {
  447. m.addressLists = append(m.addressLists, e)
  448. }
  449. _ = m.save()
  450. return m.Apply()
  451. }
  452. func (m *FirewallManager) DeleteAddressListEntry(id string) error {
  453. m.mu.Lock()
  454. defer m.mu.Unlock()
  455. var updated []AddressListEntry
  456. for _, e := range m.addressLists {
  457. if e.ID != id {
  458. updated = append(updated, e)
  459. }
  460. }
  461. m.addressLists = updated
  462. _ = m.save()
  463. return m.Apply()
  464. }
  465. func (m *FirewallManager) SetAddressListEntryState(id string, disabled bool) error {
  466. m.mu.Lock()
  467. defer m.mu.Unlock()
  468. for i := range m.addressLists {
  469. if m.addressLists[i].ID == id {
  470. m.addressLists[i].Disabled = disabled
  471. _ = m.save()
  472. return m.Apply()
  473. }
  474. }
  475. return fmt.Errorf("address list entry not found")
  476. }
  477. func (m *FirewallManager) ResetCounters() error {
  478. _ = exec.Command("iptables", "-Z").Run()
  479. return nil
  480. }
  481. func (m *FirewallManager) GetSummary() FirewallSummary {
  482. m.mu.Lock()
  483. defer m.mu.Unlock()
  484. conns, _ := ListActiveConnections()
  485. geoCount := 0
  486. geoSubnets := 0
  487. if m.geoIPMgr != nil {
  488. status := m.geoIPMgr.GetStatus()
  489. if c, ok := status["enabled_count"].(int); ok {
  490. geoCount = c
  491. }
  492. if s, ok := status["total_subnets"].(int); ok {
  493. geoSubnets = s
  494. }
  495. }
  496. return FirewallSummary{
  497. FilterRulesCount: len(m.filterRules),
  498. NATRulesCount: len(m.natRules),
  499. MangleRulesCount: len(m.mangleRules),
  500. AddressListsCount: len(m.addressLists),
  501. GeoCountriesCount: geoCount,
  502. GeoSubnetsCount: geoSubnets,
  503. ActiveConnections: len(conns),
  504. }
  505. }