firewalld.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. //go:build linux
  2. // +build linux
  3. package iptables
  4. import (
  5. "context"
  6. "fmt"
  7. "strings"
  8. "github.com/containerd/containerd/log"
  9. dbus "github.com/godbus/dbus/v5"
  10. )
  11. // IPV defines the table string
  12. type IPV string
  13. const (
  14. // Iptables point ipv4 table
  15. Iptables IPV = "ipv4"
  16. // IP6Tables point to ipv6 table
  17. IP6Tables IPV = "ipv6"
  18. // Ebtables point to bridge table
  19. Ebtables IPV = "eb"
  20. )
  21. const (
  22. dbusInterface = "org.fedoraproject.FirewallD1"
  23. dbusPath = "/org/fedoraproject/FirewallD1"
  24. dbusConfigPath = "/org/fedoraproject/FirewallD1/config"
  25. dockerZone = "docker"
  26. )
  27. // Conn is a connection to firewalld dbus endpoint.
  28. type Conn struct {
  29. sysconn *dbus.Conn
  30. sysObj dbus.BusObject
  31. sysConfObj dbus.BusObject
  32. signal chan *dbus.Signal
  33. }
  34. // ZoneSettings holds the firewalld zone settings, documented in
  35. // https://firewalld.org/documentation/man-pages/firewalld.dbus.html
  36. type ZoneSettings struct {
  37. version string
  38. name string
  39. description string
  40. unused bool
  41. target string
  42. services []string
  43. ports [][]interface{}
  44. icmpBlocks []string
  45. masquerade bool
  46. forwardPorts [][]interface{}
  47. interfaces []string
  48. sourceAddresses []string
  49. richRules []string
  50. protocols []string
  51. sourcePorts [][]interface{}
  52. icmpBlockInversion bool
  53. }
  54. var (
  55. connection *Conn
  56. firewalldRunning bool // is Firewalld service running
  57. onReloaded []*func() // callbacks when Firewalld has been reloaded
  58. )
  59. // FirewalldInit initializes firewalld management code.
  60. func FirewalldInit() error {
  61. var err error
  62. if connection, err = newConnection(); err != nil {
  63. return fmt.Errorf("Failed to connect to D-Bus system bus: %v", err)
  64. }
  65. firewalldRunning = checkRunning()
  66. if !firewalldRunning {
  67. connection.sysconn.Close()
  68. connection = nil
  69. }
  70. if connection != nil {
  71. go signalHandler()
  72. if err := setupDockerZone(); err != nil {
  73. return err
  74. }
  75. }
  76. return nil
  77. }
  78. // New() establishes a connection to the system bus.
  79. func newConnection() (*Conn, error) {
  80. c := new(Conn)
  81. if err := c.initConnection(); err != nil {
  82. return nil, err
  83. }
  84. return c, nil
  85. }
  86. // Initialize D-Bus connection.
  87. func (c *Conn) initConnection() error {
  88. var err error
  89. c.sysconn, err = dbus.SystemBus()
  90. if err != nil {
  91. return err
  92. }
  93. // This never fails, even if the service is not running atm.
  94. c.sysObj = c.sysconn.Object(dbusInterface, dbus.ObjectPath(dbusPath))
  95. c.sysConfObj = c.sysconn.Object(dbusInterface, dbus.ObjectPath(dbusConfigPath))
  96. rule := fmt.Sprintf("type='signal',path='%s',interface='%s',sender='%s',member='Reloaded'",
  97. dbusPath, dbusInterface, dbusInterface)
  98. c.sysconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, rule)
  99. rule = fmt.Sprintf("type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged',path='/org/freedesktop/DBus',sender='org.freedesktop.DBus',arg0='%s'",
  100. dbusInterface)
  101. c.sysconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, rule)
  102. c.signal = make(chan *dbus.Signal, 10)
  103. c.sysconn.Signal(c.signal)
  104. return nil
  105. }
  106. func signalHandler() {
  107. for signal := range connection.signal {
  108. if strings.Contains(signal.Name, "NameOwnerChanged") {
  109. firewalldRunning = checkRunning()
  110. dbusConnectionChanged(signal.Body)
  111. } else if strings.Contains(signal.Name, "Reloaded") {
  112. reloaded()
  113. }
  114. }
  115. }
  116. func dbusConnectionChanged(args []interface{}) {
  117. name := args[0].(string)
  118. oldOwner := args[1].(string)
  119. newOwner := args[2].(string)
  120. if name != dbusInterface {
  121. return
  122. }
  123. if len(newOwner) > 0 {
  124. connectionEstablished()
  125. } else if len(oldOwner) > 0 {
  126. connectionLost()
  127. }
  128. }
  129. func connectionEstablished() {
  130. reloaded()
  131. }
  132. func connectionLost() {
  133. // Doesn't do anything for now. Libvirt also doesn't react to this.
  134. }
  135. // call all callbacks
  136. func reloaded() {
  137. for _, pf := range onReloaded {
  138. (*pf)()
  139. }
  140. }
  141. // OnReloaded add callback
  142. func OnReloaded(callback func()) {
  143. for _, pf := range onReloaded {
  144. if pf == &callback {
  145. return
  146. }
  147. }
  148. onReloaded = append(onReloaded, &callback)
  149. }
  150. // Call some remote method to see whether the service is actually running.
  151. func checkRunning() bool {
  152. var zone string
  153. var err error
  154. if connection != nil {
  155. err = connection.sysObj.Call(dbusInterface+".getDefaultZone", 0).Store(&zone)
  156. return err == nil
  157. }
  158. return false
  159. }
  160. // Passthrough method simply passes args through to iptables/ip6tables
  161. func Passthrough(ipv IPV, args ...string) ([]byte, error) {
  162. var output string
  163. log.G(context.TODO()).Debugf("Firewalld passthrough: %s, %s", ipv, args)
  164. if err := connection.sysObj.Call(dbusInterface+".direct.passthrough", 0, ipv, args).Store(&output); err != nil {
  165. return nil, err
  166. }
  167. return []byte(output), nil
  168. }
  169. // getDockerZoneSettings converts the ZoneSettings struct into a interface slice
  170. func getDockerZoneSettings() []interface{} {
  171. settings := ZoneSettings{
  172. version: "1.0",
  173. name: dockerZone,
  174. description: "zone for docker bridge network interfaces",
  175. target: "ACCEPT",
  176. }
  177. return []interface{}{
  178. settings.version,
  179. settings.name,
  180. settings.description,
  181. settings.unused,
  182. settings.target,
  183. settings.services,
  184. settings.ports,
  185. settings.icmpBlocks,
  186. settings.masquerade,
  187. settings.forwardPorts,
  188. settings.interfaces,
  189. settings.sourceAddresses,
  190. settings.richRules,
  191. settings.protocols,
  192. settings.sourcePorts,
  193. settings.icmpBlockInversion,
  194. }
  195. }
  196. // setupDockerZone creates a zone called docker in firewalld which includes docker interfaces to allow
  197. // container networking
  198. func setupDockerZone() error {
  199. var zones []string
  200. // Check if zone exists
  201. if err := connection.sysObj.Call(dbusInterface+".zone.getZones", 0).Store(&zones); err != nil {
  202. return err
  203. }
  204. if contains(zones, dockerZone) {
  205. log.G(context.TODO()).Infof("Firewalld: %s zone already exists, returning", dockerZone)
  206. return nil
  207. }
  208. log.G(context.TODO()).Debugf("Firewalld: creating %s zone", dockerZone)
  209. settings := getDockerZoneSettings()
  210. // Permanent
  211. if err := connection.sysConfObj.Call(dbusInterface+".config.addZone", 0, dockerZone, settings).Err; err != nil {
  212. return err
  213. }
  214. // Reload for change to take effect
  215. if err := connection.sysObj.Call(dbusInterface+".reload", 0).Err; err != nil {
  216. return err
  217. }
  218. return nil
  219. }
  220. // AddInterfaceFirewalld adds the interface to the trusted zone
  221. func AddInterfaceFirewalld(intf string) error {
  222. var intfs []string
  223. // Check if interface is already added to the zone
  224. if err := connection.sysObj.Call(dbusInterface+".zone.getInterfaces", 0, dockerZone).Store(&intfs); err != nil {
  225. return err
  226. }
  227. // Return if interface is already part of the zone
  228. if contains(intfs, intf) {
  229. log.G(context.TODO()).Infof("Firewalld: interface %s already part of %s zone, returning", intf, dockerZone)
  230. return nil
  231. }
  232. log.G(context.TODO()).Debugf("Firewalld: adding %s interface to %s zone", intf, dockerZone)
  233. // Runtime
  234. if err := connection.sysObj.Call(dbusInterface+".zone.addInterface", 0, dockerZone, intf).Err; err != nil {
  235. return err
  236. }
  237. return nil
  238. }
  239. // DelInterfaceFirewalld removes the interface from the trusted zone
  240. func DelInterfaceFirewalld(intf string) error {
  241. var intfs []string
  242. // Check if interface is part of the zone
  243. if err := connection.sysObj.Call(dbusInterface+".zone.getInterfaces", 0, dockerZone).Store(&intfs); err != nil {
  244. return err
  245. }
  246. // Remove interface if it exists
  247. if !contains(intfs, intf) {
  248. return fmt.Errorf("Firewalld: unable to find interface %s in %s zone", intf, dockerZone)
  249. }
  250. log.G(context.TODO()).Debugf("Firewalld: removing %s interface from %s zone", intf, dockerZone)
  251. // Runtime
  252. if err := connection.sysObj.Call(dbusInterface+".zone.removeInterface", 0, dockerZone, intf).Err; err != nil {
  253. return err
  254. }
  255. return nil
  256. }
  257. func contains(list []string, val string) bool {
  258. for _, v := range list {
  259. if v == val {
  260. return true
  261. }
  262. }
  263. return false
  264. }