manager.go 15 KB

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