Class: BlueWall

Inherits:
Object
  • Object
show all
Defined in:
lib/bluewall.rb

Defined Under Namespace

Classes: AuditResult, Rule

Instance Method Summary collapse

Constructor Details

#initializeBlueWall

Returns a new instance of BlueWall.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
# File 'lib/bluewall.rb', line 57

def initialize
  @supported_firewall_types = {
    'PFSENSE_LIKE' => {
      indicators: ['/pfsense/interfaces', '/pfsense/filter/rule'],
      description: 'A pfSense-like XML structure or configuration.'
    },
    'OPENSENSE_LIKE' => {
      indicators: ['/opnsense/interfaces', '/opnsense/filter/rule'],
      description: 'An OpenSense-like XML configuration.'
    }
  }

  @weights = {
    strength_explicit_wan_deny:             2.5,
    strength_restricted_mgmt_access:        4.0,
    strength_restricted_ssh_access:         4.0,
    strength_no_insecure_services_allowed:  2.5,
    strength_granular_lan_outbound:         1.5,
    strength_specific_wan_inbound_rule:     0.3,
    strength_simulated_attack_explicitly_blocked: 1.5,
    strength_simulated_exfiltration_blocked: 1.5,
    strength_simulated_legitimate_allowed:  0.8,
    strength_all_external_attacks_prevented_overall: 2.0,

    weakness_no_explicit_wan_deny:          -1.5,
    weakness_wan_mgmt_from_any:             -15.0,
    weakness_wan_ssh_from_any:              -15.0,
    weakness_overly_permissive_wan:         -20.0,
    weakness_insecure_service_allowed:      -4.0,
    weakness_broad_lan_outbound:            -1.0,
    weakness_simulated_attack_allowed:      -12.0,
    weakness_simulated_attack_implicitly_blocked: -1.0,
    weakness_simulated_exfiltration_allowed: -10.0,
    weakness_simulated_legitimate_blocked:  -3.0,
    weakness_no_rules_found:                -25.0,
    weakness_stateless_rule:                -1.8,
    weakness_nat_insecure_service:          -6.0
  }

  @max_raw_score_contribution = @weights.values.select { |v| v > 0 }.sum
  @min_raw_score_contribution = @weights.values.select { |v| v < 0 }.sum
  @score_range_buffer = 0.5
end

Instance Method Details

#_assess_frameworks(strengths, weaknesses, score) ⇒ Object



511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
# File 'lib/bluewall.rb', line 511

def _assess_frameworks(strengths, weaknesses, score)
  assessments = {}

  weakness_categories = {
    critical_exposure: weaknesses.any? { |w| w.include?('**Critical risk!**') || w.include?('**Major vulnerability!**') ||
                                          (w.include?('Simulated attack:') && w.include?('ALLOW')) ||
                                          (w.include?('Simulated exfiltration:') && w.include?('ALLOW')) },
    insecure_services: weaknesses.any? { |w| w.include?('insecure service') && w.include?('ALLOW') },
    broad_wan_rules: weaknesses.any? { |w| w.include?('overly permissive') && w.include?('WAN') },
    no_explicit_deny: weaknesses.any? { |w| w.include?('No explicit \'DENY all\' inbound rule on WAN') },
    functional_issues: weaknesses.any? { |w| w.include?('functional issue') },
    no_rules_at_all: weaknesses.any? { |w| w.include?('No firewall rules found in the configuration.') },
    nat_vulnerability: weaknesses.any? { |w| w.include?('NAT Rule') && (w.include?('insecure service') || w.include?('sensitive service')) }
  }

  # --- NIST CSF ---
  nist_score = 5.0
  nist_reasons = []
  nist_reasons << "Overall security score is low (#{sprintf("%.2f", score)}/10)." if score < 6.0
  if weakness_categories[:critical_exposure] || weakness_categories[:nat_vulnerability]
    nist_score -= 2.0
    nist_reasons << "Critical exposures (e.g., exposed management, allowed simulated attacks) detected."
  end
  if weakness_categories[:no_explicit_deny]
    nist_score -= 1.0
    nist_reasons << "Lack of explicit 'DENY all' inbound rule on WAN."
  end
  if weakness_categories[:insecure_services]
    nist_score -= 1.5
    nist_reasons << "Insecure services are allowed."
  end
  if weakness_categories[:functional_issues]
    nist_score -= 0.5
    nist_reasons << "Functional issues detected, potentially impacting system availability."
  end
  nist_score = [1.0, nist_score].max
  nist_status = nist_score >= 3.0 ? 'Pass' : 'Fail'
  assessments['NIST CSF'] = {
    status: nist_status,
    score: nist_score.round(1),
    reason: nist_reasons.empty? ? 'Generally aligns with NIST CSF principles.' : 'Significant weaknesses in core protective controls and risk management.',
    reason_details: nist_reasons
  }

  # --- ISO/IEC 27001 ---
  iso_score = 5.0
  iso_reasons = []
  if weakness_categories[:critical_exposure]
    iso_score -= 2.0
    iso_reasons << "Critical exposures impacting information security objectives."
  end
  if weakness_categories[:insecure_services]
    iso_score -= 1.5
    iso_reasons << "Insecure services are allowed, violating control objectives."
  end
  if weakness_categories[:broad_wan_rules]
    iso_score -= 1.0
    iso_reasons << "Overly broad WAN rules reduce control effectiveness."
  end
  if weakness_categories[:no_rules_at_all]
    iso_score -= 3.0
    iso_reasons << "No firewall rules found, indicating a lack of basic security controls."
  end
  iso_score = [1.0, iso_score].max
  iso_status = iso_score >= 3.0 ? 'Pass' : 'Fail'
  assessments['ISO/IEC 27001'] = {
    status: iso_status,
    score: iso_score.round(1),
    reason: iso_reasons.empty? ? 'Basic technical controls appear to be in place.' : 'Fundamental information security controls are not adequately implemented.',
    reason_details: iso_reasons
  }

  # --- CIS Controls ---
  cis_score = 5.0
  cis_reasons = []
  if weakness_categories[:critical_exposure] || weakness_categories[:nat_vulnerability]
    cis_score -= 2.5
    cis_reasons << "Violations of critical security controls (e.g., exposed management, allowed attacks)."
  end
  if weakness_categories[:insecure_services]
    cis_score -= 1.5
    cis_reasons << "Failure to block insecure services (CIS Control 1)."
  end
  if weakness_categories[:no_explicit_deny]
    cis_score -= 1.0
    cis_reasons << "Lack of explicit deny-all rule (CIS Control 9)."
  end
  if weakness_categories[:broad_wan_rules]
    cis_score -= 1.0
    cis_reasons << "Overly permissive inbound rules (CIS Control 9)."
  end
  cis_score = [1.0, cis_score].max
  cis_status = cis_score >= 3.5 ? 'Pass' : 'Fail'
  assessments['CIS Controls'] = {
    status: cis_status,
    score: cis_score.round(1),
    reason: cis_reasons.empty? ? 'Adheres to many foundational CIS Controls.' : 'Violations of critical security controls identified.',
    reason_details: cis_reasons
  }

  # --- PCI DSS ---
  pci_score = 5.0
  pci_reasons = []
  if weakness_categories[:insecure_services]
    pci_score -= 3.0
    pci_reasons << "Insecure services (e.g., FTP, Telnet, SMB) are allowed, which is a direct PCI DSS violation."
  end
  if weakness_categories[:broad_wan_rules]
    pci_score -= 2.0
    pci_reasons << "Overly permissive WAN rules violate PCI DSS requirement for strict access control."
  end
  if weakness_categories[:critical_exposure] || weakness_categories[:nat_vulnerability]
    pci_score -= 2.0
    pci_reasons << "Critical exposures (e.g., allowed simulated attacks) indicate insufficient segmentation/access controls."
  end
  pci_score = [1.0, pci_score].max
  pci_status = pci_score >= 4.0 ? 'Pass' : 'Fail'
  assessments['PCI DSS'] = {
    status: pci_status,
    score: pci_score.round(1),
    reason: pci_reasons.empty? ? 'No obvious firewall-related PCI DSS violations detected.' : '**Highly likely to fail PCI DSS.** Critical vulnerabilities present.',
    reason_details: pci_reasons
  }

  # --- SOC 2 ---
  soc2_score = 5.0
  soc2_reasons = []
  if weakness_categories[:critical_exposure]
    soc2_score -= 2.0
    soc2_reasons << "Critical exposures impact security and confidentiality criteria."
  end
  if weakness_categories[:broad_wan_rules]
    soc2_score -= 1.0
    soc2_reasons << "Broad WAN rules impact security and processing integrity."
  end
  if weakness_categories[:functional_issues]
    soc2_score -= 0.8
    soc2_reasons << "Functional issues (e.g., blocked legitimate traffic) impact availability."
  end
  if weakness_categories[:insecure_services]
    soc2_score -= 1.2
    soc2_reasons << "Allowing insecure services violates confidentiality and processing integrity."
  end
  soc2_score = [1.0, soc2_score].max
  soc2_status = soc2_score >= 3.5 ? 'Pass' : 'Fail'
  assessments['SOC 2'] = {
    status: soc2_status,
    score: soc2_score.round(1),
    reason: soc2_reasons.empty? ? 'Basic security controls appear adequate.' : 'Significant control deficiencies related to Trust Services Criteria.',
    reason_details: soc2_reasons
  }

  # --- COBIT 2019 ---
  cobit_score = 5.0
  cobit_reasons = []
  if score < 6.0
    cobit_score -= 1.0
    cobit_reasons << "Overall security score is low (#{sprintf("%.2f", score)}/10)."
  end
  if weakness_categories[:no_explicit_deny]
    cobit_score -= 1.0
    cobit_reasons << "Lack of explicit deny policy impacts governance over network access."
  end
  if weakness_categories[:broad_wan_rules]
    cobit_score -= 1.5
    cobit_reasons << "Overly permissive rules indicate poor risk management and control design."
  end
  if weakness_categories[:critical_exposure]
    cobit_score -= 2.0
    cobit_reasons << "Critical exposures reflect failure in MEA (Monitor, Evaluate, and Assess) processes."
  end
  if weakness_categories[:insecure_services]
    cobit_score -= 1.0
    cobit_reasons << "Allowing insecure services violates DSS05 (Managed Security Services)."
  end
  cobit_score = [1.0, cobit_score].max
  cobit_status = cobit_score >= 3.0 ? 'Pass' : 'Fail'
  assessments['COBIT 2019'] = {
    status: cobit_status,
    score: cobit_score.round(1),
    reason: cobit_reasons.empty? ? 'Basic governance of network security is present.' : 'Significant gaps in IT governance and control framework implementation.',
    reason_details: cobit_reasons
  }

  assessments
end

#audit_rules(rules, firewall_type, system_meta, aliases, nat_rules) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# File 'lib/bluewall.rb', line 288

def audit_rules(rules, firewall_type, system_meta, aliases, nat_rules)
  strengths = []
  weaknesses = []
  raw_score = 0.0
  simulated_attacks = []

  system_ip = system_meta[:system_ip].to_s.downcase
  lan_net = system_meta[:interfaces][:lan][:net].to_s.downcase rescue nil
  wan_ip = system_meta[:interfaces][:wan][:ip].to_s.downcase rescue nil

  # --- Explicit WAN Deny ---
  wan_explicit_block_all = rules.any? do |r|
    r.interface == 'wan' && r.direction == 'in' && r.action == 'DENY' &&
      r.protocol == 'any' && r.source == 'any' && r.destination == 'any'
  end

  if wan_explicit_block_all
    strengths << "Explicit 'DENY all' inbound rule on WAN detected, enhancing clarity and reinforcing default deny."
    raw_score += @weights[:strength_explicit_wan_deny]
  else
    weaknesses << "No explicit 'DENY all' inbound rule on WAN. Relying on implicit deny can lead to oversight."
    raw_score += @weights[:weakness_no_explicit_wan_deny]
  end

  broad_lan_outbound_weakness_added = false
  critical_weakness_types_found = Set.new

  rules.each do |rule|
    if rule.action == 'ALLOW' && rule.direction == 'in' &&
       (rule.destination == 'self' || rule.destination == system_ip || rule.destination == wan_ip) &&
       [80, 443].include?(rule.dport)

      if rule.interface == 'wan' && rule.source == 'any'
        weaknesses << "Rule [ID:#{rule.id}] allows firewall management (HTTP/HTTPS) from 'any' source on WAN. **Critical risk!**"
        raw_score += @weights[:weakness_wan_mgmt_from_any]
        critical_weakness_types_found << :wan_mgmt_from_any
      elsif rule.interface == 'wan' && rule.source != 'any'
        strengths << "Rule [ID:#{rule.id}] restricts firewall management access to specific trusted sources on WAN."
        raw_score += @weights[:strength_restricted_mgmt_access]
      end
    end

    if rule.action == 'ALLOW' && rule.direction == 'in' &&
       (rule.destination == 'self' || rule.destination == system_ip || rule.destination == wan_ip) &&
       rule.dport == 22

      if rule.interface == 'wan' && rule.source == 'any'
        weaknesses << "Rule [ID:#{rule.id}] allows SSH access to firewall from 'any' source on WAN. **Critical risk!**"
        raw_score += @weights[:weakness_wan_ssh_from_any]
        critical_weakness_types_found << :wan_ssh_from_any
      elsif rule.interface == 'wan' && rule.source != 'any'
        strengths << "Rule [ID:#{rule.id}] restricts SSH access to firewall to specific trusted sources on WAN."
        raw_score += @weights[:strength_restricted_ssh_access]
      end
    end

    if rule.action == 'ALLOW' && rule.interface == 'wan' && rule.direction == 'in' &&
       (rule.source == 'any' || rule.source.nil?) && (rule.destination == 'any' || rule.destination.nil?) &&
       rule.protocol == 'any'
      weaknesses << "Rule [ID:#{rule.id}] is an overly permissive 'ALLOW' rule from WAN to 'any' destination. **Major vulnerability!**"
      raw_score += @weights[:weakness_overly_permissive_wan]
      critical_weakness_types_found << :overly_permissive_wan
    end

    if rule.action == 'ALLOW' && rule.direction == 'in' && [21, 23, 445, 139].include?(rule.dport)
      weaknesses << "Rule [ID:#{rule.id}] on interface '#{rule.interface}' allows insecure service (port #{rule.dport}). Consider disabling or securing alternatives."
      raw_score += @weights[:weakness_insecure_service_allowed]
      critical_weakness_types_found << :insecure_service_allowed
    end

    if rule.action == 'ALLOW' && rule.interface == 'lan' && rule.direction == 'out' &&
       (rule.source == lan_net || rule.source == 'any') && rule.destination == 'any' && rule.protocol == 'any'
      unless broad_lan_outbound_weakness_added
        weaknesses << "A broad 'ALLOW all' outbound rule from LAN exists. Review to ensure no unnecessary egress traffic."
        raw_score += @weights[:weakness_broad_lan_outbound]
        broad_lan_outbound_weakness_added = true
      end
    end

    if rule.action == 'ALLOW' && rule.interface == 'wan' && rule.direction == 'in' && rule.dport &&
       ![80, 443, 22, 21, 23, 445, 139].include?(rule.dport)
      if rule.source != 'any' && rule.destination != 'any' && rule.protocol != 'any'
        strengths << "Rule [ID:#{rule.id}] provides granular access for a specific service (Port #{rule.dport})."
        raw_score += @weights[:strength_specific_wan_inbound_rule]
      end
    end
  end

  unless broad_lan_outbound_weakness_added
    strengths << "LAN outbound rules appear granular, promoting better control over egress."
    raw_score += @weights[:strength_granular_lan_outbound]
  end

  if rules.empty? && firewall_type != 'UNKNOWN'
    weaknesses << "No firewall rules found in the configuration. This implies an 'allow all' or unknown state."
    raw_score += @weights[:weakness_no_rules_found]
    critical_weakness_types_found << :no_rules_found
  end

  # --- Simulated Attack Scenarios ---
  require 'set'
  simulated_scenarios = [
    { name: "WAN to LAN SSH (Port 22)",
      packet: { src_ip: '203.0.113.1', dst_ip: '10.0.0.100', dst_port: 22, protocol: 'tcp', interface: 'wan', direction: 'in' }, type: :attack, randomize_port: false },
    { name: "WAN to LAN RDP (Port 3389)",
      packet: { src_ip: '203.0.113.1', dst_ip: '10.0.0.100', dst_port: 3389, protocol: 'tcp', interface: 'wan', direction: 'in' }, type: :attack, randomize_port: false },
    { name: "WAN to Firewall HTTP Management (Port 80)",
      packet: { src_ip: '203.0.113.1', dst_ip: system_ip, dst_port: 80, protocol: 'tcp', interface: 'wan', direction: 'in' }, type: :attack, randomize_port: false },
    { name: "WAN to Firewall HTTPS Management (Port 443)",
      packet: { src_ip: '203.0.113.1', dst_ip: system_ip, dst_port: 443, protocol: 'tcp', interface: 'wan', direction: 'in' }, type: :attack, randomize_port: false },
    { name: "WAN to Internal FTP Server (Port 21)",
      packet: { src_ip: '203.0.113.1', dst_ip: '10.0.0.200', dst_port: 21, protocol: 'tcp', interface: 'wan', direction: 'in' }, type: :attack, randomize_port: false },
    { name: "WAN to Internal SMB Share (Port 445)",
      packet: { src_ip: '203.0.113.1', dst_ip: '10.0.0.200', dst_port: 445, protocol: 'tcp', interface: 'wan', direction: 'in' }, type: :attack, randomize_port: false },
    { name: "LAN to External Web (Port 80 - Expected Allowed)",
      packet: { src_ip: '10.0.0.50', dst_ip: '8.8.8.8', dst_port: 80, protocol: 'tcp', interface: 'lan', direction: 'out' }, type: :legitimate, randomize_port: false },
    { name: "WAN to Firewall SSH Brute-force (Random Port)",
      packet: { src_ip: '185.10.10.10', dst_ip: system_ip, protocol: 'tcp', interface: 'wan', direction: 'in' }, type: :attack, randomize_port: true, base_port: 22 },
    { name: "LAN to External Exfiltration (Random High Port)",
      packet: { src_ip: '10.0.0.100', dst_ip: '1.2.3.4', protocol: 'tcp', interface: 'lan', direction: 'out' }, type: :exfiltration, randomize_port: true, port_range: (49152..65535) },
    { name: "DMZ to LAN Database Access (Random Port)",
      packet: { src_ip: '172.16.0.50', dst_ip: '10.0.0.150', protocol: 'tcp', interface: 'dmz', direction: 'in' }, type: :attack, randomize_port: true, base_port: 1433 },
    { name: "WAN to Internal Reverse Shell (Random High Port)",
      packet: { src_ip: '203.0.113.1', dst_ip: '10.0.0.100', protocol: 'tcp', interface: 'wan', direction: 'in' }, type: :attack, randomize_port: true, port_range: (49152..65535) },
    { name: "WAN to Internal Netcat Listener (Random High Port)",
      packet: { src_ip: '203.0.113.1', dst_ip: '10.0.0.100', protocol: 'tcp', interface: 'wan', direction: 'in' }, type: :attack, randomize_port: true, port_range: (49152..65535) },
  ]

  wan_dmz_attacks_prevented_count = 0
  wan_dmz_total_attacks_in_scenarios = 0

  simulated_scenarios.each do |scenario|
    num_loops = scenario[:randomize_port] ? 5 : 1
    scenario_outcomes = []
    scenario_allowed_any_time = false

    num_loops.times do
      current_packet = scenario[:packet].dup
      if scenario[:randomize_port]
        if scenario[:base_port]
          current_packet[:dst_port] = [1, [scenario[:base_port] - 100 + rand(201), 65535].min].max
        elsif scenario[:port_range]
          current_packet[:dst_port] = rand(scenario[:port_range])
        else
          current_packet[:dst_port] = rand(1024..65535)
        end
        scenario_name_with_port = "#{scenario[:name]} (Port #{current_packet[:dst_port]})"
      else
        scenario_name_with_port = scenario[:name]
      end

      outcome = simulate_connection_attempt(rules + nat_rules, current_packet, system_meta)
      scenario_outcomes << "#{scenario_name_with_port}: #{outcome}"
      scenario_allowed_any_time = true if outcome == 'ALLOW'
    end

    simulated_attacks.concat(scenario_outcomes)

    is_external_attack_scenario = (scenario[:name].include?("WAN to") || scenario[:name].include?("DMZ to")) && scenario[:type] == :attack
    is_exfiltration_scenario = scenario[:type] == :exfiltration
    is_legitimate_scenario = scenario[:type] == :legitimate

    if is_external_attack_scenario
      wan_dmz_total_attacks_in_scenarios += 1
    end

    if scenario_allowed_any_time
      if is_legitimate_scenario
        strengths << "Simulated legitimate traffic: '#{scenario[:name]}' was ALLOWED (as expected) in at least one test."
        raw_score += @weights[:strength_simulated_legitimate_allowed]
      elsif is_external_attack_scenario
        weaknesses << "Simulated attack: '#{scenario[:name]}' was ALLOWED in at least one randomized test. **Major exposure!**"
        raw_score += @weights[:weakness_simulated_attack_allowed]
        critical_weakness_types_found << :simulated_attack_allowed
      elsif is_exfiltration_scenario
        weaknesses << "Simulated exfiltration: '#{scenario[:name]}' was ALLOWED in at least one randomized test. Review outbound rules for data leakage prevention."
        raw_score += @weights[:weakness_simulated_exfiltration_allowed]
        critical_weakness_types_found << :simulated_exfiltration_allowed
      end
    else
      if is_legitimate_scenario
        weaknesses << "Simulated legitimate traffic: '#{scenario[:name]}' was BLOCKED/IMPLICITLY_BLOCKED unexpectedly in all tests. This might indicate a functional issue."
        raw_score += @weights[:weakness_simulated_legitimate_blocked]
      elsif is_external_attack_scenario
        if scenario_outcomes.any? { |o| o.include?('DENY') }
          strengths << "Simulated attack: '#{scenario[:name]}' was EXPLICITLY_BLOCKED in tests (strong security)."
          raw_score += @weights[:strength_simulated_attack_explicitly_blocked]
        else
          weaknesses << "Simulated attack: '#{scenario[:name]}' was IMPLICITLY_BLOCKED in all tests. Consider explicit block rules for clarity and robustness."
          raw_score += @weights[:weakness_simulated_attack_implicitly_blocked]
        end
        wan_dmz_attacks_prevented_count += 1
      elsif is_exfiltration_scenario
        if scenario_outcomes.any? { |o| o.include?('DENY') }
          strengths << "Simulated exfiltration: '#{scenario[:name]}' was BLOCKED in tests. Good for data leakage prevention."
          raw_score += @weights[:strength_simulated_exfiltration_blocked]
        else
          weaknesses << "Simulated exfiltration: '#{scenario[:name]}' was IMPLICITLY_BLOCKED. Consider explicit block rules for data leakage prevention."
          raw_score += @weights[:weakness_simulated_exfiltration_allowed]
        end
      end
    end
  end

  if wan_dmz_total_attacks_in_scenarios > 0 && wan_dmz_attacks_prevented_count == wan_dmz_total_attacks_in_scenarios
    strengths << "All simulated external attack attempts were successfully prevented (either explicitly or implicitly blocked)."
    raw_score += @weights[:strength_all_external_attacks_prevented_overall]
  end

  raw_score += (critical_weakness_types_found.size * -5.0)

  effective_min_raw_score = @min_raw_score_contribution - @score_range_buffer
  effective_max_raw_score = @max_raw_score_contribution + @score_range_buffer
  range = effective_max_raw_score - effective_min_raw_score
  normalized_score = range.abs < 1e-9 ? 0.5 : (raw_score - effective_min_raw_score) / range
  final_score = (normalized_score * 9) + 1
  final_score = [1.0, [final_score, 10.0].min].max

  framework_assessments = _assess_frameworks(strengths, weaknesses, final_score)

  { strengths: strengths, weaknesses: weaknesses, score: final_score, simulated_attacks: simulated_attacks, framework_assessments: framework_assessments }
end

#calculate_defense_depth(rules) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/bluewall.rb', line 274

def calculate_defense_depth(rules)
  interface_count = rules.map(&:interface).uniq.size
  action_diversity = rules.map(&:action).uniq.size
  protocol_diversity = rules.map(&:protocol).uniq.size
  port_specificity = rules.count { |r| r.dport && r.dport > 0 } / rules.size.to_f

  score = (interface_count / 5.0) * 1.0 +
          (action_diversity / 2.0) * 1.0 +
          (protocol_diversity / 5.0) * 1.0 +
          port_specificity * 2.0

  [[score, 5.0].min, 0.0].max
end

#calculate_entropy(strings) ⇒ Object



265
266
267
268
269
270
271
272
# File 'lib/bluewall.rb', line 265

def calculate_entropy(strings)
  text = strings.join('').downcase
  freq = Hash.new(0)
  text.each_char { |c| freq[c] += 1 }
  total = text.length.to_f
  return 0 if total == 0
  -freq.values.map { |count| (count / total) * Math.log2(count / total) }.sum
end

#conduct_audit(config_file_path) ⇒ Object



698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
# File 'lib/bluewall.rb', line 698

def conduct_audit(config_file_path)
  puts "Starting BlueWall audit..."
  unless File.exist?(config_file_path)
    puts "Error: Configuration file not found at '#{config_file_path}'"
    return AuditResult.new('N/A', [], [], ["Configuration file not found: #{config_file_path}"], 1.0, 'Audit failed.', [], {})
  end

  begin
    xml_content = File.read(config_file_path)
    xml_doc = Nokogiri::XML(xml_content) { |c| c.options = Nokogiri::XML::ParseOptions::NOBLANKS }

    system_meta = {
      interfaces: extract_interfaces_from_xml(xml_doc),
      system_ip: extract_system_ip_from_xml(xml_doc)
    }

    firewall_type = detect_firewall_type_from_xml(xml_doc)
    if firewall_type == 'UNKNOWN'
      return AuditResult.new(firewall_type, [], [], ['Unrecognized XML structure.'], 1.0, 'Cannot perform audit.', [], {})
    end

    puts "Detected firewall type: #{firewall_type}"

    aliases = extract_aliases_from_xml(xml_doc)
    schedules = extract_schedules_from_xml(xml_doc)
    nat_rules = extract_nat_rules_from_xml(xml_doc, aliases)
    rules = parse_config_from_xml(xml_doc, aliases)

    puts "Parsed #{rules.count} firewall rules, #{aliases.size} aliases, #{nat_rules.size} NAT rules."

    if rules.empty?
      return AuditResult.new(firewall_type, [], [], ['No firewall rules found.'], 1.0, 'Cannot audit empty ruleset.', [], {})
    end

    audit_findings = audit_rules(rules, firewall_type, system_meta, aliases, nat_rules)
    details = "BlueWall audit completed based on common cybersecurity principles tailored for #{firewall_type} (inspired by CIS Controls and NIST CSF). Score reflects adherence to least privilege, rule specificity, handling of insecure services, and interface-specific security."

    AuditResult.new(
      firewall_type, rules, audit_findings[:strengths], audit_findings[:weaknesses],
      audit_findings[:score], details, audit_findings[:simulated_attacks], audit_findings[:framework_assessments]
    )
  rescue Nokogiri::XML::SyntaxError => e
    puts "Error parsing XML: #{e.message}"
    AuditResult.new('N/A', [], [], ["XML error: #{e.message}"], 1.0, 'Parse failed.', [], {})
  rescue StandardError => e
    puts "Unexpected error: #{e.message}"
    AuditResult.new('ERROR', [], [], ["Unexpected error: #{e.message}"], 1.0, 'Audit failed.', [], {})
  end
end

#detect_firewall_type_from_xml(xml_doc) ⇒ Object



101
102
103
104
105
106
107
108
# File 'lib/bluewall.rb', line 101

def detect_firewall_type_from_xml(xml_doc)
  @supported_firewall_types.each do |type, info|
    if info[:indicators].all? { |xpath| xml_doc.at_xpath(xpath) }
      return type
    end
  end
  'UNKNOWN'
end

#extract_aliases_from_xml(xml_doc) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/bluewall.rb', line 127

def extract_aliases_from_xml(xml_doc)
  aliases = {}
  xml_doc.xpath('//aliases/alias').each do |a|
    name = a.at_xpath('name')&.content
    type = a.at_xpath('type')&.content
    address = a.at_xpath('address')&.content || ''
    descr = a.at_xpath('descr')&.content || ''
    next unless name
    aliases[name] = { type: type, address: address.split(/\s+/), description: descr }
  end
  aliases
end

#extract_interfaces_from_xml(xml_doc) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
# File 'lib/bluewall.rb', line 110

def extract_interfaces_from_xml(xml_doc)
  interfaces = {}
  xml_doc.xpath('//interfaces/*/ipaddr').each do |ip_node|
    interface_name = ip_node.parent.name
    interfaces[interface_name.to_sym] = {
      ip: ip_node.content || '',
      net: ip_node.parent.at_xpath('subnet')&.content || ''
    }
  end
  interfaces
end

#extract_nat_rules_from_xml(xml_doc, aliases) ⇒ Object



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/bluewall.rb', line 154

def extract_nat_rules_from_xml(xml_doc, aliases)
  nat_rules = []
  xml_doc.xpath('//nat/rule').each_with_index do |rule_node, index|
    rule_id = rule_node.at_xpath('id')&.content || "nat_rule_#{index + 1}"
    action = 'ALLOW'
    interface = rule_node.at_xpath('interface')&.content || 'any'
    direction = 'in'
    protocol = rule_node.at_xpath('protocol')&.content || 'any'

    source_node = rule_node.at_xpath('source')
    source = resolve_alias(source_node&.at_xpath('address')&.content, aliases) || 'any'

    destination_node = rule_node.at_xpath('destination')
    destination = resolve_alias(destination_node&.at_xpath('address')&.content, aliases) || 'any'

    dport = rule_node.at_xpath('destination/port')&.content&.to_i
    dport = resolve_alias(dport.to_s, aliases).to_i if dport && aliases.key?(dport.to_s)
    comment = rule_node.at_xpath('descr')&.content
    quick = true
    schedule = nil
    gateway = rule_node.at_xpath('gateway')&.content
    state_type = 'keep state'

    nat_rules << Rule.new(rule_id, action, interface, direction, protocol, source, destination, dport, comment, quick, schedule, gateway, state_type, true)
  end
  nat_rules
end

#extract_schedules_from_xml(xml_doc) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/bluewall.rb', line 140

def extract_schedules_from_xml(xml_doc)
  schedules = {}
  xml_doc.xpath('//schedules/schedule').each do |s|
    name = s.at_xpath('name')&.content
    descr = s.at_xpath('descr')&.content || ''
    times = s.at_xpath('times')&.content || ''
    weekdays = s.at_xpath('weekdays')&.content || ''
    months = s.at_xpath('months')&.content || ''
    next unless name
    schedules[name] = { descr: descr, times: times, weekdays: weekdays, months: months }
  end
  schedules
end

#extract_system_ip_from_xml(xml_doc) ⇒ Object



122
123
124
125
# File 'lib/bluewall.rb', line 122

def extract_system_ip_from_xml(xml_doc)
  (xml_doc.at_xpath('//system/wan/ipaddr')&.content ||
   xml_doc.at_xpath('//system/general/hostname')&.content || '')
end

#match_ip_or_network(packet_ip_str, rule_ip_or_network_str, interface_ips) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/bluewall.rb', line 217

def match_ip_or_network(packet_ip_str, rule_ip_or_network_str, interface_ips)
  packet_ip_str = packet_ip_str.to_s
  rule_ip_or_network_str = rule_ip_or_network_str.to_s
  return true if rule_ip_or_network_str == 'any'
  return true if packet_ip_str == rule_ip_or_network_str

  if rule_ip_or_network_str == 'self'
    return true if packet_ip_str == interface_ips[:wan_ip] || packet_ip_str == interface_ips[:lan_ip]
  end

  if rule_ip_or_network_str.include?('/')
    rule_base_ip, rule_cidr_mask = rule_ip_or_network_str.split('/')
    if rule_cidr_mask == '24' && !rule_base_ip.empty?
      packet_octets = packet_ip_str.split('.')
      rule_octets = rule_base_ip.split('.')
      return packet_octets.size >= 3 && rule_octets.size >= 3 && packet_octets[0..2].join('.') == rule_octets[0..2].join('.')
    end
  end

  false
end

#parse_config_from_xml(xml_doc, aliases) ⇒ Object



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
# File 'lib/bluewall.rb', line 187

def parse_config_from_xml(xml_doc, aliases)
  rules = []
  xml_doc.xpath('//filter/rule').each_with_index do |rule_node, index|
    rule_id = rule_node.at_xpath('id')&.content || rule_node.at_xpath('descr')&.content || "xml_rule_#{index + 1}"
    action = rule_node.at_xpath('type')&.content == 'block' ? 'DENY' : 'ALLOW'
    interface = rule_node.at_xpath('interface')&.content || 'any'
    direction = rule_node.at_xpath('direction')&.content || 'in'
    protocol = rule_node.at_xpath('protocol')&.content || 'any'

    source_node = rule_node.at_xpath('source/network') || rule_node.at_xpath('source/address')
    source = resolve_alias(source_node&.content, aliases) || 'any'
    source = 'any' if rule_node.at_xpath('source/any')

    destination_node = rule_node.at_xpath('destination/network') || rule_node.at_xpath('destination/address')
    destination = resolve_alias(destination_node&.content, aliases) || 'any'
    destination = 'any' if rule_node.at_xpath('destination/any')

    dport = rule_node.at_xpath('destination/port')&.content&.to_i
    dport = resolve_alias(dport.to_s, aliases).to_i if dport && aliases.key?(dport.to_s)
    comment = rule_node.at_xpath('descr')&.content
    quick = rule_node.at_xpath('quick')&.content == 'on'
    schedule = rule_node.at_xpath('sched')&.content
    gateway = rule_node.at_xpath('gateway')&.content
    state_type = rule_node.at_xpath('statetype')&.content || 'keep state'

    rules << Rule.new(rule_id, action, interface, direction, protocol, source, destination, dport, comment, quick, schedule, gateway, state_type, false)
  end
  rules
end

#resolve_alias(value, aliases) ⇒ Object



182
183
184
185
# File 'lib/bluewall.rb', line 182

def resolve_alias(value, aliases)
  return value unless value && aliases.key?(value)
  aliases[value][:address].first
end

#simulate_connection_attempt(rules, packet, system_meta) ⇒ Object



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/bluewall.rb', line 239

def simulate_connection_attempt(rules, packet, system_meta)
  interface_ips = {
    wan_ip: system_meta[:interfaces][:wan][:ip],
    lan_ip: system_meta[:interfaces][:lan][:ip]
  }

  rules.each do |rule|
    next unless rule.interface == 'any' || rule.interface == packet[:interface]
    next unless rule.direction == 'any' || rule.direction == packet[:direction]
    next unless rule.protocol == 'any' || rule.protocol == packet[:protocol]
    next unless match_ip_or_network(packet[:src_ip], rule.source, interface_ips)
    next unless match_ip_or_network(packet[:dst_ip], rule.destination, interface_ips)

    if rule.dport && packet[:dst_port]
      next unless rule.dport == packet[:dst_port]
    elsif rule.dport && !packet[:dst_port]
      next
    end

    return rule.action if rule.quick
    return rule.action
  end

  'IMPLICITLY_BLOCKED'
end