Class: Yast::SuSEFirewalldClass

Inherits:
SuSEFirewallClass show all
Defined in:
library/network/src/lib/network/susefirewalld.rb

Overview


SuSEFirewalld Class. Trying to provide relevent pieces of SF2 functionality via firewalld.

Constant Summary collapse

ZONE_ATTRIBUTES =

Valid attributes for firewalld zones :interfaces = [Array<String>] :masquerade = Boolean :modified = [Set<Symbols>] :ports = [Array<String>] :protocols = [Array<String>] :services = [Array<String>]

[:interfaces, :masquerade, :modified, :ports, :protocols, :services].freeze
KEY_SETTINGS =

<enable,start>_firewall are “inherited” from SF2 so we can't use symbols there without having to change all the SF2 callers.

["enable_firewall", "logging", "routing", "start_firewall"].freeze
EMPTY_ZONE =
{
  interfaces: [],
  masquerade: false,
  modified:   Set.new,
  ports:      [],
  protocols:  [],
  services:   []
}.freeze

Instance Attribute Summary collapse

Attributes inherited from SuSEFirewallClass

#firewall_service

Instance Method Summary collapse

Methods inherited from SuSEFirewallClass

#AddService, #AddXenSupport, #DisableServices, #EnableServices, #GetAllKnownInterfaces, #GetEnableService, #GetKnownFirewallZones, #GetListOfKnownInterfaces, #GetModified, #GetServices, #GetStartService, #GetZoneFullName, #GetZonesOfInterfaces, #HaveService, #IsEnabled, #IsKnownZone, #IsOtherFirewallRunning, #IsStarted, #IsSupportedProtocol, #RemoveService, #ResetModified, #SaveAndRestartService, #SetAdditionalServices, #SetEnableService, #SetInstallPackagesIfMissing, #SetModified, #SetServices, #SetStartService, #StartServices, #StopServices, #SuSEFirewallIsInstalled, #SuSEFirewallIsSelectedOrInstalled

Constructor Details

#initializeSuSEFirewalldClass

Returns a new instance of SuSEFirewalldClass



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'library/network/src/lib/network/susefirewalld.rb', line 71

def initialize
  textdomain "base"

  # firewalld API interface.
  @fwd_api = Y2Firewall::Firewalld::Api.new
  # firewalld service
  @firewall_service = "firewalld"
  # firewalld package
  @FIREWALL_PACKAGE = "firewalld"
  # flag to indicate that FirewallD configuration has been read
  @configuration_has_been_read = false
  # firewall settings map
  @SETTINGS = {}
  # list of known firewall zones
  @known_firewall_zones = ["block", "dmz", "drop", "external", "home",
                           "internal", "public", "trusted", "work"]
  # map defines zone name for all known firewall zones
  @zone_names = {
    # TRANSLATORS: Firewall zone name - used in combo box or dialog title
    "block"    => _(
      "Block Zone"
    ),
    "dmz"      => _(
      "Demilitarized Zone"
    ),
    "drop"     => _(
      "Drop Zone"
    ),
    "external" => _(
      "External Zone"
    ),
    "home"     => _(
      "Home Zone"
    ),
    "internal" => _(
      "Internal Zone"
    ),
    "public"   => _(
      "Public Zone"
    ),
    "trusted"  => _(
      "Trusted Zone"
    ),
    "work"     => _(
      "Work Zone"
    )
  }

  # Zone which works with the special_all_interface_string string. In our case,
  # we don't want to deal with this just yet. FIXME
  @special_all_interface_zone = ""

  # Initialize the @SETTINGS hash
  KEY_SETTINGS.each { |x| @SETTINGS[x] = nil }
  GetKnownFirewallZones().each { |zone| @SETTINGS[zone] = deep_copy(EMPTY_ZONE) }

  # Are needed packages installed?
  @needed_packages_installed = nil

  # bnc #388773
  # By default needed packages are just checked, not installed
  @check_and_install_package = false

  # internal zone identification - useful for protect-from-internal
  @int_zone_shortname = "internal"

  # list of protocols supported in firewall, use only upper-cases
  @supported_protocols = ["TCP", "UDP", "IP"]
end

Instance Attribute Details

#special_all_interface_zoneObject (readonly)

Returns the value of attribute special_all_interface_zone



42
43
44
# File 'library/network/src/lib/network/susefirewalld.rb', line 42

def special_all_interface_zone
  @special_all_interface_zone
end

Instance Method Details

#ActivateConfigurationBoolean

Function which starts/stops firewall. Then firewall is started immediately when firewall is wanted to be started: SetStartService(boolean). FirewallD needs to be reloaded instead of doing a full-blown restart to get the new configuration up and running.

Returns:

  • (Boolean)

    if successful



371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'library/network/src/lib/network/susefirewalld.rb', line 371

def ActivateConfiguration
  # starting firewall during second stage can cause deadlock in systemd - bnc#798620
  # Moreover, it is not needed. Firewall gets started via dependency on multi-user.target
  # when second stage is over.
  if Mode.installation
    Builtins.y2milestone("Do not touch firewall services during installation")

    return true
  end

  if GetStartService()
    # Not started - start it
    if !IsStarted()
      Builtins.y2milestone("Starting firewall services")
      return StartServices()
      # Started - restart it
    else
      Builtins.y2milestone("Firewall has been started already")
      # Make it real
      @fwd_api.reload
      return true
    end
  # Firewall should stop after Write()
  # started - stop
  elsif IsStarted()
    Builtins.y2milestone("Stopping firewall services")
    return StopServices()
    # stopped - skip stopping
  else
    Builtins.y2milestone("Firewall has been stopped already")
    return true
  end
end

#AddAllowedPortsOrServices(add_ports, protocol, zone) ⇒ Object

Local function allows ports for requested protocol and zone.

Parameters:



954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
# File 'library/network/src/lib/network/susefirewalld.rb', line 954

def AddAllowedPortsOrServices(add_ports, protocol, zone)
  add_ports = deep_copy(add_ports)
  if Ops.less_than(Builtins.size(add_ports), 1)
    Builtins.y2warning(
      "Undefined list of %1 services/ports for service",
      protocol
    )
    return
  end

  SetModified()

  # all allowed ports
  allowed_services = GetAllowedServicesForZoneProto(zone, protocol)

  allowed_services = Convert.convert(
    Builtins.union(allowed_services, add_ports),
    from: "list",
    to:   "list <string>"
  )

  SetAllowedServicesForZoneProto(allowed_services, zone, protocol)

  nil
end

#AddInterfaceIntoZone(interface, zone) ⇒ Object

Functions adds interface into defined zone. All appearances of interface in other zones are removed.

Examples:

AddInterfaceIntoZone (“eth5”, “DMZ”)

Parameters:



535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
# File 'library/network/src/lib/network/susefirewalld.rb', line 535

def AddInterfaceIntoZone(interface, zone)
  return nil if !IsKnownZone(zone)

  SetModified()

  current_zone = GetZoneOfInterface(interface)

  # removing all appearances of interface in zones, excepting current_zone==new_zone
  while !current_zone.nil? && current_zone != zone
    # interface is in any zone already, removing it at first
    RemoveInterfaceFromZone(interface, current_zone) if current_zone != zone
    current_zone = GetZoneOfInterface(interface)
  end

  Builtins.y2milestone(
    "Adding interface '%1' into '%2' zone.",
    interface,
    zone
  )

  add_to_zone_attr(zone, :interfaces, interface)
  add_zone_modified(zone, :interfaces)

  nil
end

#AddSpecialInterfaceIntoZone(interface, zone) ⇒ Object

Functions adds special string into defined zone. For firewalld we return nil.

Parameters:



731
732
733
# File 'library/network/src/lib/network/susefirewalld.rb', line 731

def AddSpecialInterfaceIntoZone(interface, zone)
  AddInterfaceIntoZone(interface, zone)
end

#apiObject

We need that for the tests. Nothing else should access the API directly



67
68
69
# File 'library/network/src/lib/network/susefirewalld.rb', line 67

def api
  @fwd_api
end

#ArePortsOrServicesAllowed(needed_ports, protocol, zone, _check_for_aliases) ⇒ Object



945
946
947
# File 'library/network/src/lib/network/susefirewalld.rb', line 945

def ArePortsOrServicesAllowed(needed_ports, protocol, zone, _check_for_aliases)
  super(needed_ports, protocol, zone, false)
end

#ExportHash{String => Object}

Function for getting exported SuSEFirewall configuration

Returns:

  • (Hash{String => Object})

    with configuration



170
171
172
173
# File 'library/network/src/lib/network/susefirewalld.rb', line 170

def Export
  # FIXME: Temporal export until a new schema is defined for firewalld
  @SETTINGS.select { |k, v| KEY_SETTINGS.include?(k) && !v.nil? }
end

#GetAcceptExpertRules(zone) ⇒ String

Returns list of rules describing protocols and ports that are allowed to be accessed from listed hosts. All is returned as a single string. Zone needs to be defined.

Parameters:

Returns:



988
989
990
991
992
993
994
995
996
997
998
# File 'library/network/src/lib/network/susefirewalld.rb', line 988

def GetAcceptExpertRules(zone)
  zone = Builtins.toupper(zone)

  # Check for zone
  if !Builtins.contains(GetKnownFirewallZones(), zone)
    Builtins.y2error("Unknown firewall zone: %1", zone)
    return nil
  end

  Ops.get_string(@SETTINGS, Ops.add("FW_SERVICES_ACCEPT_", zone), "")
end

#GetAdditionalServices(protocol, zone) ⇒ Array<String>

This powerful function returns list of services/ports which are not assigned to any fully-supported known-services. This function doesn't check for services defined by packages. They are listed by a different way.

Examples:

GetAdditionalServices("TCP", "EXT") -> ["53", "128"]

Returns:

  • (Array<String>)

    of additional (unassigned) services



867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
# File 'library/network/src/lib/network/susefirewalld.rb', line 867

def GetAdditionalServices(protocol, zone)
  protocol = protocol.upcase

  if !IsSupportedProtocol(protocol.upcase)
    Builtins.y2error("Unknown protocol '%1'", protocol)
    return nil
  end
  if !IsKnownZone(zone)
    Builtins.y2error("Unknown zone '%1'", zone)
    return nil
  end

  # all ports or services allowed in zone for protocol
  all_allowed_services = GetAllowedServicesForZoneProto(zone, protocol)

  # And now drop the known ones
  all_allowed_services -= SuSEFirewallServices.GetSupportedServices().keys

  # well, actually it returns list of services not-assigned to any well-known service
  deep_copy(all_allowed_services)
end

#GetAllowedServicesForZoneProto(zone, protocol) ⇒ Array<String>

Function returns list of allowed ports for zone and protocol

Parameters:

Returns:

  • (Array<String>)

    of allowed ports



833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
# File 'library/network/src/lib/network/susefirewalld.rb', line 833

def GetAllowedServicesForZoneProto(zone, protocol)
  Yast.import "SuSEFirewallServices"

  result = []
  protocol = protocol.downcase

  get_zone_attr(zone, :ports).each do |p|
    port_proto = p.split("/")
    result << port_proto[0] if port_proto[1] == protocol
  end
  result = get_zone_attr(zone, :protocols) if protocol == "ip"
  # We return the name of service instead of its ports
  get_zone_attr(zone, :services).each do |s| # to be SF2 compatible.
    if protocol == "tcp"
      result << s if !SuSEFirewallServices.GetNeededTCPPorts(s).empty?
    elsif protocol == "udp"
      result << s if !SuSEFirewallServices.GetNeededUDPPorts(s).empty?
    end
  end
  # FIXME: Is this really needed?
  result.flatten!

  deep_copy(result)
end

#GetIgnoreLoggingBroadcast(_zone) ⇒ String

Function returns yes/no - ingoring broadcast for zone

Examples:

# Does not log ignored broadcast packets
GetIgnoreLoggingBroadcast () -> "yes"

Parameters:

Returns:

  • (String)

    “yes” or “no”



798
799
800
801
# File 'library/network/src/lib/network/susefirewalld.rb', line 798

def GetIgnoreLoggingBroadcast(_zone)
  return "no" if @SETTINGS["logging"] == "broadcast"
  "yes"
end

#GetInterfacesInZone(zone) ⇒ Array<String>

Function returns list of known interfaces in requested zone. Special strings like 'any' or 'auto' and unknown interfaces are removed from list.

Examples:

GetInterfacesInZone (“external”) -> [“eth4”, “eth5”]

Parameters:

Returns:

  • (Array<String>)

    of interfaces



501
502
503
504
505
# File 'library/network/src/lib/network/susefirewalld.rb', line 501

def GetInterfacesInZone(zone)
  return [] unless IsKnownZone(zone)
  known_interfaces_now = GetListOfKnownInterfaces()
  get_zone_attr(zone, :interfaces).find_all { |i| known_interfaces_now.include?(i) }
end

#GetInterfacesInZoneSupportingAnyFeature(zone) ⇒ Array<String>

Function returns list of known interfaces in requested zone. In the firewalld case, we don't support the special 'any' string. Thus, interfaces not in a zone will not be included.

Parameters:

Returns:

  • (Array<String>)

    of interfaces



567
568
569
# File 'library/network/src/lib/network/susefirewalld.rb', line 567

def GetInterfacesInZoneSupportingAnyFeature(zone)
  GetInterfacesInZone(zone)
end

#GetLoggingSettings(rule) ⇒ String

Function returns actual state of logging. @ note There is no 1-1 matching between SF2 and FirewallD when @ note it comes to logging. We need to be backwards compatible and @ note so we use the following conventions: @ note ACCEPT -> FirewallD can't log accepted packets so we always return @ note false. @ note DROP -> We map “all” to “ALL”, “broadcast, multicast or unicast” @ note to “CRIT” and “off” to “NONE”. @ note As a result of which, this method has little value in FirewallD

Parameters:

  • rule (String)

    definition 'ACCEPT' or 'DROP'

Returns:

  • (String)

    'ALL' or 'NONE'



747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
# File 'library/network/src/lib/network/susefirewalld.rb', line 747

def GetLoggingSettings(rule)
  return false if rule == "ACCEPT"
  if rule == "DROP"
    drop_rule = @SETTINGS["logging"]
    case drop_rule
    when "off"
      return "NONE"
    when "broadcast", "multicast", "unicast"
      return "CRIT"
    when "all"
      return "ALL"
    end
  else
    Builtins.y2error("Possible rules are only 'ACCEPT' or 'DROP'")
  end
end

#GetMasquerade(zone = "internal") ⇒ Boolean

Function returns actual state of Masquerading support. In FirewallD, masquerade is enabled per-zone so this function treats the 'internal' zone as the default zone if no zone is given as parameter.

Parameters:

  • zone (String) (defaults to: "internal")

    zone to get masqurade status from (default: internal)

Returns:

  • (Boolean)

    if supported



679
680
681
682
683
684
685
# File 'library/network/src/lib/network/susefirewalld.rb', line 679

def GetMasquerade(zone = "internal")
  if !IsKnownZone(zone)
    Builtins.y2error("zone %1 is not valid", zone)
    return nil
  end
  get_zone_attr(zone, :masquerade)
end

#GetProtectFromInternalZoneBoolean

Function returns if firewall is protected from internal zone. For firewalld, we just return true since the internal zone is treated like any other zone.

Returns:

  • (Boolean)

    if protected from internal



491
492
493
# File 'library/network/src/lib/network/susefirewalld.rb', line 491

def GetProtectFromInternalZone
  true
end

#GetServicesInZones(services) ⇒ Hash<String, Hash<String, Boolean>>

Function returns map of supported services all network interfaces.

Examples:

GetServicesInZones (["service:irc-server"]) -> $["service:irc-server":$["eth1":true]]
# No such service "something"
GetServicesInZones (["something"])) -> $["something":$["eth1":nil]]
GetServicesInZones (["samba-server"]) -> $["samba-server":$["eth1":false]]

Parameters:

  • services (Array<String>)

    list of services

Returns:

  • (Hash<String, Hash<String, Boolean>>)

    Returns in format `=> { interface => supported_status }`



582
583
584
585
586
587
588
589
590
591
592
593
# File 'library/network/src/lib/network/susefirewalld.rb', line 582

def GetServicesInZones(services)
  services = deep_copy(services)
  tmp_services = deep_copy(services)
  services = []
  Builtins.foreach(tmp_services) do |service|
    sf2_to_firewalld_service(service).each do |s|
      s = service.include?("service:") ? "service:" + s : s
      services << s
    end
  end
  super(services)
end

#GetSpecialInterfacesInZone(zone) ⇒ Array<String>

Function returns list of special strings like 'any' or 'auto' and unknown interfaces. This function is only valid for SF2. For firewalld, we return an empty array.

Examples:

GetSpecialInterfacesInZone("EXT") -> ["any", "unknown-1", "wrong-3"]

Parameters:

Returns:

  • (Array<String>)

    special strings or unknown interfaces



712
713
714
715
# File 'library/network/src/lib/network/susefirewalld.rb', line 712

def GetSpecialInterfacesInZone(zone)
  known_interfaces_now = GetListOfKnownInterfaces()
  get_zone_attr(zone, :interfaces).reject { |i| known_interfaces_now.include?(i) }
end

#GetZoneOfInterface(interface) ⇒ Object

Function returns the firewall zone of interface, nil if no zone includes the interface. Firewalld does not allow an interface to be in more than one zone, so no error detection for this case is needed.

Parameters:

Returns:

  • string zone, or nil



431
432
433
434
435
436
437
# File 'library/network/src/lib/network/susefirewalld.rb', line 431

def GetZoneOfInterface(interface)
  GetKnownFirewallZones().each do |zone|
    return zone if IsInterfaceInZone(interface, zone)
  end

  nil
end

#GetZonesOfInterfacesWithAnyFeatureSupported(interfaces) ⇒ Array<String>

Function returns list of zones of requested interfaces. Special string 'any' in 'EXT' zone is supported.

Examples:

GetZonesOfInterfaces (["eth1","eth4"]) -> ["EXT"]

Parameters:

Returns:

  • (Array<String>)

    firewall zones



447
448
449
450
451
452
# File 'library/network/src/lib/network/susefirewalld.rb', line 447

def GetZonesOfInterfacesWithAnyFeatureSupported(interfaces)
  interfaces = deep_copy(interfaces)
  zones = []
  interfaces.each { |interface| zones << GetZoneOfInterface(interface) }
  zones
end

#Import(import_settings) ⇒ Object

Function for setting SuSEFirewall configuration from input

Parameters:

  • import_settings (Hash<String, Object>)

    with configuration



178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'library/network/src/lib/network/susefirewalld.rb', line 178

def Import(import_settings)
  Read()
  import_settings = deep_copy(import_settings || {})
  # Sanitize it
  import_settings.keys.each do |k|
    if !GetKnownFirewallZones().include?(k) && !KEY_SETTINGS.include?(k)
      Builtins.y2warning("Removing invalid key: %1 from imported settings", k)
      import_settings.delete(k)
    elsif import_settings[k].is_a?(Hash)
      import_settings[k].keys.each do |v|
        if !ZONE_ATTRIBUTES.include?(v)
          Builtins.y2warning("Removing invalid value: %1 from key %2", v, k)
          import_settings[k].delete(v)
        end
      end
    end
  end

  # Ruby's merge will probably not work since we have nested hashes
  @SETTINGS.keys.each do |key|
    next unless import_settings.include?(key)
    if import_settings[key].class == Hash
      # Merge them
      @SETTINGS[key].merge!(import_settings[key])
    else
      @SETTINGS[key] = import_settings[key]
    end
  end

  # Merge missing attributes
  @SETTINGS.keys.each do |key|
    next unless GetKnownFirewallZones().include?(key)
    # is this a zone?
    @SETTINGS[key] = EMPTY_ZONE.merge(@SETTINGS[key])
    # Everything may have been modified
    @SETTINGS[key][:modified] = [:interfaces, :masquerade, :ports, :protocols, :services]
  end

  # Tests mock the read method so read the NetworkInterface list again
  NetworkInterfaces.Read if !@configuration_has_been_read

  SetModified()

  nil
end

#IsAnyNetworkInterfaceSupportedObject

Function returns whether the feature 'any' network interface is supported. This is a SF2 specific construct. For firewalld, we simply return false. We may decide to change this in the future.

Returns:

  • boolean false



459
460
461
# File 'library/network/src/lib/network/susefirewalld.rb', line 459

def IsAnyNetworkInterfaceSupported
  false
end

#IsInterfaceInZone(interface, zone) ⇒ Boolean

Function returns if the interface is in zone.

Examples:

IsInterfaceInZone (“eth-id-01:11:DA:9C:8A:2F”, “INT”) -> false

Parameters:

Returns:

  • (Boolean)

    is in zone



420
421
422
423
# File 'library/network/src/lib/network/susefirewalld.rb', line 420

def IsInterfaceInZone(interface, zone)
  interfaces = get_zone_attr(zone, :interfaces)
  interfaces.include?(interface)
end

#IsServiceSupportedInZone(service, zone) ⇒ Boolean

Function returns true if service is supported (allowed) in zone. Service must be defined already be defined.

Examples:

# All ports defined by dns-server service in SuSEFirewallServices module
# are enabled in the respective zone
IsServiceSupportedInZone ("dns-server", "external") -> true

Parameters:

Returns:

  • (Boolean)

    if supported

See Also:

  • SuSEFirewallServices


475
476
477
478
479
480
481
482
483
484
# File 'library/network/src/lib/network/susefirewalld.rb', line 475

def IsServiceSupportedInZone(service, zone)
  return nil if !IsKnownZone(zone)

  # We may have more than one FirewallD service per SF2 service
  sf2_to_firewalld_service(service).each do |s|
    return false if !in_zone_attr?(zone, :services, s)
  end

  true
end

#ReadObject



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'library/network/src/lib/network/susefirewalld.rb', line 234

def Read
  # Do not read it again and again
  # to avoid overwritting live configuration.
  if @configuration_has_been_read
    Builtins.y2milestone(
      "FirewallD configuration has been read already."
    )
    return true
  end

  ReadCurrentConfiguration()

  Builtins.y2milestone(
    "Firewall configuration has been read: %1.",
    @SETTINGS
  )
  # Always call NI::Read, bnc #396646
  NetworkInterfaces.Read

  # to read configuration only once
  @configuration_has_been_read = true
end

#read_zonesObject



257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'library/network/src/lib/network/susefirewalld.rb', line 257

def read_zones
  # Get all the information from zones and load them to @SETTINGS["zones"]
  # The following may seem somewhat complicated or fragile but it is more
  # efficient to only invoke a single firewall-cmd command instead of
  # iterating over the zones and then using all the different
  # firewall-cmd commands to get service, port, masquerade etc
  # information from them.
  all_zone_info = @fwd_api.list_all_zones
  # Drop empty lines
  all_zone_info.reject!(&:empty?)
  # And now build the hash
  zone = nil
  all_zone_info.each do |e|
    # is it a zone?
    z = e.split("\s")[0]
    if GetKnownFirewallZones().include?(z)
      zone = z
      next
    end
    if ZONE_ATTRIBUTES.any? { |w| e.include?(w.to_s) }
      attrs = e.split(":\s")
      attr = attrs[0].lstrip.to_sym
      # do not bother if empty
      next if attrs[1].nil?
      vals = attrs[1].split("\s")
      # Fix up for masquerade
      if attr == :masquerade
        set_to_zone_attr(zone, attr, (vals == "no" ? false : true))
      else
        vals.each { |x| add_to_zone_attr(zone, attr, x) }
      end
    end
  end
end

#ReadCurrentConfigurationObject



292
293
294
295
296
297
298
299
300
301
302
# File 'library/network/src/lib/network/susefirewalld.rb', line 292

def ReadCurrentConfiguration
  if SuSEFirewallIsInstalled()
    read_zones
    @SETTINGS["logging"] = @fwd_api.log_denied_packets
  end

  @SETTINGS["enable_firewall"] = IsEnabled()
  @SETTINGS["start_firewall"] = IsStarted()

  true
end

#RemoveAllowedPortsOrServices(remove_ports, protocol, zone, _check_for_aliases) ⇒ Object

Local function removes ports and their aliases (if check_for_aliases is true), for requested protocol and zone.

Parameters:

  • remove_ports (Array<String>)

    ports to be removed

  • protocol (String)

    Protocol

  • zone (String)

    Zone

  • _check_for_aliases (Boolean)

    unused



923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
# File 'library/network/src/lib/network/susefirewalld.rb', line 923

def RemoveAllowedPortsOrServices(remove_ports, protocol, zone, _check_for_aliases)
  remove_ports = deep_copy(remove_ports)
  if Ops.less_than(Builtins.size(remove_ports), 1)
    Builtins.y2warning(
      "Undefined list of %1 services/ports for service",
      protocol
    )
    return
  end

  SetModified()

  allowed_services = GetAllowedServicesForZoneProto(zone, protocol)
  Builtins.y2debug("RemoveAdditionalServices: currently allowed services for %1_%2 -> %3",
    zone, protocol, allowed_services)
  # and this is what we keep
  allowed_services -= remove_ports
  Builtins.y2debug("RemoveAdditionalServices: new allowed services for %1_%2 -> %3",
    zone, protocol, allowed_services)
  SetAllowedServicesForZoneProto(allowed_services, zone, protocol)
end

#RemoveInterfaceFromZone(interface, zone) ⇒ Object

Function removes interface from defined zone.

Examples:

RemoveInterfaceFromZone (“modem0”, “EXT”)

Parameters:



512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
# File 'library/network/src/lib/network/susefirewalld.rb', line 512

def RemoveInterfaceFromZone(interface, zone)
  return nil if !IsKnownZone(zone)

  SetModified()

  Builtins.y2milestone(
    "Removing interface '%1' from '%2' zone.",
    interface,
    zone
  )

  del_from_zone_attr(zone, :interfaces, interface)
  add_zone_modified(zone, :interfaces)

  nil
end

#RemoveSpecialInterfaceFromZone(interface, zone) ⇒ Object

Function removes special string from defined zone. For firewalld we return nil.

Parameters:



722
723
724
# File 'library/network/src/lib/network/susefirewalld.rb', line 722

def RemoveSpecialInterfaceFromZone(interface, zone)
  RemoveInterfaceFromZone(interface, zone)
end

#SetAcceptExpertRules(zone, expert_rules) ⇒ Boolean

Sets expert allow rules for zone.

Parameters:

  • zone (String)
  • expert_rules (String)

    whitespace-separated expert_rules

Returns:

  • (Boolean)

    if successful



1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
# File 'library/network/src/lib/network/susefirewalld.rb', line 1005

def SetAcceptExpertRules(zone, expert_rules)
  zone = Builtins.toupper(zone)

  # Check for zone
  if !Builtins.contains(GetKnownFirewallZones(), zone)
    Builtins.y2error("Unknown firewall zone: %1", zone)
    return false
  end

  Ops.set(@SETTINGS, Ops.add("FW_SERVICES_ACCEPT_", zone), expert_rules)
  SetModified()

  true
end

#SetAllowedServicesForZoneProto(allowed_services, zone, protocol) ⇒ Object

Function sets list of services as allowed ports for zone and protocol

Parameters:

  • allowed_services (Array<string>)

    list of allowed ports/services

  • zone (String)
  • protocol (String)


894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
# File 'library/network/src/lib/network/susefirewalld.rb', line 894

def SetAllowedServicesForZoneProto(allowed_services, zone, protocol)
  allowed_services = deep_copy(allowed_services)

  SetModified()

  protocol = protocol.downcase

  # allowed_services can contain both services and port definitions so the
  # first step is to split them up
  services, ports = sanitize_services_and_ports(allowed_services, protocol)

  # First we drop existing services and ports.
  delete_ports_with_protocol_from_zone(protocol, zone)
  delete_services_with_protocol_from_zone(protocol, zone)

  # And now add the new ports and services
  set_ports_with_protocol_to_zone(ports, protocol, zone)
  set_services_to_zone(services, zone)

  nil
end

#SetIgnoreLoggingBroadcast(_zone, bcast) ⇒ Object

Note:

Since Firewalld only accepts a single packet type to log,

Note:

we simply disable logging if broadcast logging is not desirable.

Note:

If you used SetIgnoreLoggingBroadcast is your code, make sure you

Note:

use SetLoggingSettings afterwards to enable the type of logging you

Note:

want.

Function sets yes/no - ingoring broadcast for zone

Examples:

# Do not log broadcast packetes from DMZ
SetIgnoreLoggingBroadcast ("DMZ", "yes")

Parameters:

  • _zone (String)

    unused

  • bcast (String)

    ignore 'yes' or 'no'



816
817
818
819
820
821
822
823
824
825
826
# File 'library/network/src/lib/network/susefirewalld.rb', line 816

def SetIgnoreLoggingBroadcast(_zone, bcast)
  bcast = bcast.casecmp("no").zero? ? "broadcast" : "off"

  return nil if @SETTINGS["logging"] == bcast

  SetModified()

  @SETTINGS["logging"] = bcast.downcase

  nil
end

#SetLoggingSettings(rule, state) ⇒ Object

Note:

Similar restrictions to GetLoggingSettings apply

Function sets state of logging.

Parameters:

  • rule (String)

    definition 'ACCEPT' or 'DROP'

  • state (String)

    new logging state 'ALL', 'CRIT', or 'NONE'



768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
# File 'library/network/src/lib/network/susefirewalld.rb', line 768

def SetLoggingSettings(rule, state)
  return nil if rule == "ACCEPT"
  if rule == "DROP"
    drop_rule = state.downcase
    case drop_rule
    when "none"
      @SETTINGS["logging"] = "off"
    when "crit"
      # Choosing unicast since it's likely to be the most common case
      @SETTINGS["logging"] = "unicast"
    when "all"
      @SETTINGS["logging"] = "all"
    end
  else
    Builtins.y2error("Possible rules are only 'ACCEPT' or 'DROP'")
  end

  SetModified()

  nil
end

#SetMasquerade(enable, zone = "internal") ⇒ Object

Function sets Masquerade support.

Parameters:

  • enable (Boolean)

    Enable or Disable masquerade

  • zone (String) (defaults to: "internal")

    Zone to enable masquerade on.

Returns:

  • nil



692
693
694
695
696
697
698
699
700
701
702
# File 'library/network/src/lib/network/susefirewalld.rb', line 692

def SetMasquerade(enable, zone = "internal")
  if !IsKnownZone(zone)
    Builtins.y2error("zone %1 is not valid", zone)
    return nil
  end
  SetModified()
  set_to_zone_attr(zone, :masquerade, enable)
  add_zone_modified(zone, :masquerade)

  nil
end

#SetServicesForZones(services_ids, firewall_zones, new_status) ⇒ Object

Function sets status for several services in several firewall zones.

Examples:

SetServicesForZones (["samba-server", "service:irc-server"], ["DMZ", "EXT"], false);
SetServicesForZones (["samba-server", "service:irc-server"], ["EXT", "DMZ"], true);

Parameters:

  • services_ids (Array<String>)

    service ids

  • firewall_zones (Array<String>)

    firewall zones (EXT|INT|DMZ…)

  • new_status (true, false)

    new status of services

Returns:

  • nil

See Also:

  • #GetServicesInZones()
  • #GetServices()


608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
# File 'library/network/src/lib/network/susefirewalld.rb', line 608

def SetServicesForZones(services_ids, firewall_zones, new_status)
  Yast.import "SuSEFirewallServices"

  services_ids = deep_copy(services_ids)
  zones = deep_copy(firewall_zones)

  tmp_services_ids = deep_copy(services_ids)
  services_ids = []
  tmp_services_ids.each do |service|
    sf2_to_firewalld_service(service).each do |s|
      services_ids << s
    end
  end

  # setting for each service
  services_ids.each do |service|
    # Service is not supported by firewalld.
    # We can only do such error checking if backend is running
    if IsStarted() && !@fwd_api.service_supported?(service)
      Builtins.y2error("Undefined service '#{service}'")
      raise(SuSEFirewalServiceNotFound, "Service with name '#{service}' does not exist")
    end
    zones.each do |zone|
      # Add/remove service to/from zone only if zone is not 'trusted',
      # 'blocked' or 'drop'. For these zones there is no need to
      # explicitly add/remove
      # services as all connections are by default accepted.
      next if ["block", "drop", "trusted"].include?(zone)

      # zone must be known one
      if !IsKnownZone(zone)
        Builtins.y2error(
          "Zone '%1' is unknown firewall zone, skipping...",
          zone
        )
        next
      end

      if new_status == true # enable
        Builtins.y2milestone(
          "Adding '%1' into '%2' zone",
          service, zone
        )
        # Only add it if it is not there
        if !in_zone_attr?(zone, :services, service)
          add_to_zone_attr(zone, :services, service)
          SetModified()
          add_zone_modified(zone, :services)
        end
      else # disable
        Builtins.y2milestone(
          "Removing '%1' from '%2' zone",
          service, zone
        )
        del_from_zone_attr(zone, :services, service)
        SetModified()
        add_zone_modified(zone, :services)
      end
    end
  end

  nil
end

#sf2_to_firewalld_service(service) ⇒ Object

Function which attempts to convert a sf2_service name to a firewalld equivalent.



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'library/network/src/lib/network/susefirewalld.rb', line 143

def sf2_to_firewalld_service(service)
  # First, let's strip off 'service:' from service name if present.
  tmp_service = if service.include?("service:")
    service.partition(":")[2]
  else
    service
  end

  sf2_to_firewalld_map = {
    # netbios is covered in the samba service file
    "netbios-server"    => ["samba"],
    "nfs-client"        => ["nfs"],
    "nfs-kernel-server" => ["mountd", "nfs", "rpc-bind"],
    "samba-server"      => ["samba"],
    "sshd"              => ["ssh"]
  }

  if sf2_to_firewalld_map.key?(tmp_service)
    sf2_to_firewalld_map[tmp_service]
  else
    [tmp_service]
  end
end

#sf2_to_firewalld_zone(zone) ⇒ Object



224
225
226
227
228
229
230
231
232
# File 'library/network/src/lib/network/susefirewalld.rb', line 224

def sf2_to_firewalld_zone(zone)
  sf2_to_firewalld_map = {
    "INT" => "trusted",
    "EXT" => "external",
    "DMZ" => "dmz"
  }

  sf2_to_firewalld_map[zone] || zone
end

#WriteObject



405
406
407
408
409
410
411
# File 'library/network/src/lib/network/susefirewalld.rb', line 405

def Write
  # Make the firewall changes permanent.
  return false if !WriteConfiguration()
  return false if !ActivateConfiguration()

  true
end

#WriteConfigurationObject



304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'library/network/src/lib/network/susefirewalld.rb', line 304

def WriteConfiguration
  # just disabled
  return true if !SuSEFirewallIsInstalled()

  return false if !GetModified()

  Builtins.y2milestone(
    "Firewall configuration has been changed. Writing: %1.",
    @SETTINGS
  )
  # FIXME: Need to improve that to not re-write everything
  begin
    # Set logging
    if !@SETTINGS["logging"].nil?
      @fwd_api.log_denied_packets(@SETTINGS["logging"]) if !@fwd_api.log_denied_packets?(@SETTINGS["logging"])
    end
    # Configure the zones
    GetKnownFirewallZones().each do |zone|
      if zone_attr_modified?(zone)
        Builtins.y2milestone("zone=#{zone} hasn't been modified. Skipping...")
        next
      end

      write_zone_masquerade(zone)
      write_zone_interfaces(zone)
      write_zone_services(zone)
      write_zone_ports(zone)
      write_zone_protocols(zone)

      # Configuration is now live. Move on
      ResetModified()
    end

  rescue FirewallCMDError
    Builtins.y2error("firewall-cmd failed")
    raise
  end

  # FIXME: perhaps "== true" can be dropped since this should
  # always be boolean?
  if !@SETTINGS["enable_firewall"].nil?
    if @SETTINGS["enable_firewall"] == true
      Builtins.y2milestone("Enabling firewall services")
      return false if !EnableServices()
    else
      Builtins.y2milestone("Disabling firewall services")
      return false if !DisableServices()
    end
  end

  true
end

#WriteOnlyObject

In SF2, it's used to write configuration, but not activate. For firewalld this is simply here to satisfy callers, like modules/Nfs.rb.

Returns:

  • true



360
361
362
363
# File 'library/network/src/lib/network/susefirewalld.rb', line 360

def WriteOnly
  # This does not check if firewalld is running
  return false if !WriteConfiguration()
end