Class: Dcmgr::NodeModules::ServiceNetfilter

Inherits:
Isono::NodeModules::Base
  • Object
show all
Includes:
Helpers::NicHelper, Logger, Bandwidth, Nat
Defined in:
lib/dcmgr/node_modules/service_netfilter.rb

Instance Method Summary collapse

Methods included from Bandwidth

#clear_bandwidth_limits, #limit_bandwidth

Methods included from Logger

create, default_logdev, included

Methods included from Helpers::NicHelper

#find_nic, #nic_state, #valid_nic?

Methods included from Nat

#arp_respond, #is_natted_ip?, #nat_exceptions, #nat_instance

Instance Method Details

#build_ebtables_basic_part(vif_map, inst_map) ⇒ Object



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
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 383

def build_ebtables_basic_part(vif_map, inst_map)
  basic_cmds = []
  hva_ipv4 = Isono::Util.default_gw_ipaddr

  ################################
  ## 0. chain name
  ################################

  # support IP protocol
  protocol_map = protocol_map(:ebtables)

  # make chain names.
  chains = []
  chains << "s_#{vif_map[:uuid]}"
  chains << "d_#{vif_map[:uuid]}"
  chains << "s_#{vif_map[:uuid]}_d_hst"
  chains << "d_#{vif_map[:uuid]}_s_hst"
  protocol_map.each { |k,v|
    chains << "s_#{vif_map[:uuid]}_#{k}"
    chains << "d_#{vif_map[:uuid]}_#{k}"
    chains << "s_#{vif_map[:uuid]}_d_hst_#{k}"
    chains << "d_#{vif_map[:uuid]}_s_hst_#{k}"
  }

  ################################
  ## 1. basic part
  ################################

  # create user defined chains.
  [ 'N' ].each { |xcmd|
    chains.each { |chain|
      basic_cmds << "ebtables -#{xcmd} #{chain}"
    }
  }

  # jumt to user defined chains
  basic_cmds << "ebtables -A FORWARD -i #{vif_map[:uuid]} -j s_#{vif_map[:uuid]}"
  basic_cmds << "ebtables -A FORWARD -o #{vif_map[:uuid]} -j d_#{vif_map[:uuid]}"
  basic_cmds << "ebtables -A INPUT   -i #{vif_map[:uuid]} -j s_#{vif_map[:uuid]}_d_hst"
  basic_cmds << "ebtables -A OUTPUT  -o #{vif_map[:uuid]} -j d_#{vif_map[:uuid]}_s_hst"

  # IP protocol routing
  protocol_map.each { |k,v|
    basic_cmds << "ebtables -A s_#{vif_map[:uuid]}       -p #{v} -j s_#{vif_map[:uuid]}_#{k}"
    basic_cmds << "ebtables -A d_#{vif_map[:uuid]}       -p #{v} -j d_#{vif_map[:uuid]}_#{k}"
    basic_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst -p #{v} -j s_#{vif_map[:uuid]}_d_hst_#{k}"
    basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_s_hst -p #{v} -j d_#{vif_map[:uuid]}_s_hst_#{k}"
  }

  if @node.manifest.config.packet_drop_log
    basic_cmds << "ebtables -A s_#{vif_map[:uuid]}       --log-level 4 --log-ip --log-arp --log-prefix 'D s_#{vif_map[:uuid]}:'       -j CONTINUE"
    basic_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst --log-level 4 --log-ip --log-arp --log-prefix 'D s_#{vif_map[:uuid]}_d_hst:' -j CONTINUE"
  end
  basic_cmds << "ebtables -A s_#{vif_map[:uuid]}       -j DROP"
  basic_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst -j DROP"
  # anti spoof: mac    # guest -> *
  basic_cmds << "ebtables -A s_#{vif_map[:uuid]}_arp       --protocol arp --arp-mac-src ! #{vif_map[:mac]} --log-ip --log-arp --log-prefix 'Dmc s_#{vif_map[:uuid]}_arp:'       -j CONTINUE"
  basic_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst_arp --protocol arp --arp-mac-src ! #{vif_map[:mac]} --log-ip --log-arp --log-prefix 'Dmc s_#{vif_map[:uuid]}_d_hst_arp:' -j CONTINUE"
  basic_cmds << "ebtables -A s_#{vif_map[:uuid]}_arp       --protocol arp --arp-mac-src ! #{vif_map[:mac]} -j DROP"
  basic_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst_arp --protocol arp --arp-mac-src ! #{vif_map[:mac]} -j DROP"
  # guest <- * (broadcast)
  basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_arp       --protocol arp                          --arp-mac-dst 00:00:00:00:00:00 --log-ip --log-arp --log-prefix 'Amc d_#{vif_map[:uuid]}_arp:'     -j CONTINUE"
  basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_s_hst_arp --protocol arp --arp-ip-src=#{hva_ipv4} --arp-mac-dst 00:00:00:00:00:00 --log-ip --log-arp --log-prefix 'Amc d_#{vif_map[:uuid]}_hst_arp:' -j CONTINUE"
  basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_arp       --protocol arp                          --arp-mac-dst 00:00:00:00:00:00 -j ACCEPT"
  basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_s_hst_arp --protocol arp --arp-ip-src=#{hva_ipv4} --arp-mac-dst 00:00:00:00:00:00 -j ACCEPT"

  # guest <- *
  basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_arp       --protocol arp --arp-mac-dst ! #{vif_map[:mac]} --log-ip --log-arp --log-prefix 'Dmc d_#{vif_map[:uuid]}_arp:'       -j CONTINUE"
  basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_s_hst_arp --protocol arp --arp-mac-dst ! #{vif_map[:mac]} --log-ip --log-arp --log-prefix 'Dmc d_#{vif_map[:uuid]}_s_hst_arp:' -j CONTINUE"
  basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_arp       --protocol arp --arp-mac-dst ! #{vif_map[:mac]} -j DROP"
  basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_s_hst_arp --protocol arp --arp-mac-dst ! #{vif_map[:mac]} -j DROP"

  # anti spoof: ipv4
  inst_map[:ips].each { |ipv4|
    #next if is_natted_ip? ipv4
    # guest -> *
    basic_cmds << "ebtables -A s_#{vif_map[:uuid]}_arp       --protocol arp --arp-ip-src ! #{ipv4} --log-ip --log-arp --log-prefix 'Dip s_#{vif_map[:uuid]}_arp:'       -j CONTINUE"
    basic_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst_arp --protocol arp --arp-ip-src ! #{ipv4} --log-ip --log-arp --log-prefix 'Dip s_#{vif_map[:uuid]}_d_hst_arp:' -j CONTINUE"
    basic_cmds << "ebtables -A s_#{vif_map[:uuid]}_arp       --protocol arp --arp-ip-src ! #{ipv4} -j DROP"
    basic_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst_arp --protocol arp --arp-ip-src ! #{ipv4} -j DROP"
    # guest <- *
    basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_arp       --protocol arp --arp-ip-dst ! #{ipv4} --log-ip --log-arp --log-prefix 'Dip d_#{vif_map[:uuid]}_arp:'       -j CONTINUE"
    basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_s_hst_arp --protocol arp --arp-ip-dst ! #{ipv4} --log-ip --log-arp --log-prefix 'Dip d_#{vif_map[:uuid]}_s_hst_arp:' -j CONTINUE"
    basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_arp       --protocol arp --arp-ip-dst ! #{ipv4} -j DROP"
    basic_cmds << "ebtables -A d_#{vif_map[:uuid]}_s_hst_arp --protocol arp --arp-ip-dst ! #{ipv4} -j DROP"
  }

  basic_cmds
end

#build_ebtables_final_part(vif_map) ⇒ Object



549
550
551
552
553
554
555
556
557
558
559
560
561
562
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 549

def build_ebtables_final_part(vif_map)
  final_cmds = []

  ################################
  ## 3. final part
  ################################
  # deny,allow
  final_cmds << "ebtables -A d_#{vif_map[:uuid]}_arp       --log-level 4 --log-ip --log-arp --log-prefix 'D d_#{vif_map[:uuid]}_arp:'       -j CONTINUE"
  final_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst_arp --log-level 4 --log-ip --log-arp --log-prefix 'D s_#{vif_map[:uuid]}_d_hst_arp:' -j CONTINUE"
  final_cmds << "ebtables -A d_#{vif_map[:uuid]}_arp       -j DROP"
  final_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst_arp -j DROP"

  final_cmds
end

#build_ebtables_group_part(vif_map, inst_map, viftable_map) ⇒ Object



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
510
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
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 473

def build_ebtables_group_part(vif_map, inst_map, viftable_map)
  group_cmds = []
  hva_ipv4 = Isono::Util.default_gw_ipaddr

  ################################
  ## 2. group part
  ################################
  same_subnet_ipv4s = rpc.request('hva-collector', 'get_group_instance_ipv4s', inst_map[:uuid])

  network_map = rpc.request('hva-collector', 'get_network', inst_map[:instance_nics].first[:network_id])
  raise "UnknownNetworkId" if network_map.nil?
  joined_network = IPAddress("#{network_map[:ipv4_gw]}/#{network_map[:prefix]}")
  
  [ network_map[:dns_server], network_map[:dhcp_server] ].each { |ipv4|
    next unless joined_network.include? IPAddress(ipv4)      
    same_subnet_ipv4s << ipv4
  }       

  # network resource node(s)
  ng_maps = rpc.request('hva-collector', 'get_netfilter_groups_of_instance', inst_map[:uuid])
  rules = ng_maps.map { |ng_map|
    ng_map[:rules].map { |rule| rule[:permission] }
  }.flatten
  build_rule(rules).each do |rule|
    begin
      # <ArgumentError: Invalid IP "0.0.0.0">
      next unless joined_network.include? IPAddress(rule[:ip_source])
      same_subnet_ipv4s << rule[:ip_source]
    rescue Exception => e
      p e
    end
  end
  same_subnet_ipv4s << network_map[:ipv4_gw]

  # guest node(s) in HyperVisor.
  alive_inst_maps = rpc.request('hva-collector', 'get_alive_instances', node.node_id)
  guest_ipv4s = alive_inst_maps.map { |alive_inst_map|
    alive_inst_map[:ips]
  }.flatten.uniq.compact

  same_subnet_ipv4s.uniq.reverse_each do |ipv4|
    next if vif_map[:ipv4] == ipv4

    # get_macaddr_by_ipv4, ipv4
    if ipv4 == hva_ipv4
      #p "#{vif_map[:uuid]}(#{vif_map[:ipv4]}) -> [host] ***-****** (#{ipv4})"
      group_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst_arp --protocol arp --arp-ip-src #{vif_map[:ipv4]} --arp-ip-dst #{ipv4} --log-ip --log-arp --log-prefix 'Afw s_#{vif_map[:uuid]}_d_hst_arp:' -j CONTINUE"
      group_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst_arp --protocol arp --arp-ip-src #{vif_map[:ipv4]} --arp-ip-dst #{ipv4} -j ACCEPT"
    elsif guest_ipv4s.include?(ipv4)
      #p "#{vif_map[:uuid]}(#{vif_map[:ipv4]}) -> [guest] #{viftable_map[ipv4]}(#{ipv4})"

      # guest->guest
      group_cmds << "ebtables -A d_#{vif_map[:uuid]}_arp       --protocol arp --arp-ip-src #{ipv4} --arp-ip-dst #{vif_map[:ipv4]} --log-ip --log-arp --log-prefix 'Afw d_#{vif_map[:uuid]}_arp:'       -j CONTINUE"
      group_cmds << "ebtables -A d_#{vif_map[:uuid]}_arp       --protocol arp --arp-ip-src #{ipv4} --arp-ip-dst #{vif_map[:ipv4]} -j ACCEPT"
      # guest->host
      group_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst_arp --protocol arp --arp-ip-src #{vif_map[:ipv4]} --arp-ip-dst #{ipv4} --log-ip --log-arp --log-prefix 'Afw s_#{vif_map[:uuid]}_d_hst_arp:' -j CONTINUE"
      group_cmds << "ebtables -A s_#{vif_map[:uuid]}_d_hst_arp --protocol arp --arp-ip-src #{vif_map[:ipv4]} --arp-ip-dst #{ipv4} -j ACCEPT"
      
      unless viftable_map[ipv4].nil?
        # guest->guest
        group_cmds << "ebtables -A d_#{viftable_map[ipv4]}_arp       --protocol arp --arp-ip-src #{vif_map[:ipv4]} --arp-ip-dst #{ipv4} --log-ip --log-arp --log-prefix 'Arv d_#{viftable_map[ipv4]}_arp:' -j CONTINUE"
        group_cmds << "ebtables -A d_#{viftable_map[ipv4]}_arp       --protocol arp --arp-ip-src #{vif_map[:ipv4]} --arp-ip-dst #{ipv4} -j ACCEPT"

        # guest->host
        group_cmds << "ebtables -A s_#{viftable_map[ipv4]}_d_hst_arp --protocol arp --arp-ip-src #{ipv4} --arp-ip-dst #{vif_map[:ipv4]} --log-ip --log-arp --log-prefix 'Arv s_#{viftable_map[ipv4]}_d_hst_arp:' -j CONTINUE"
        group_cmds << "ebtables -A s_#{viftable_map[ipv4]}_d_hst_arp --protocol arp --arp-ip-src #{ipv4} --arp-ip-dst #{vif_map[:ipv4]} -j ACCEPT"
      end
    else
      #p "#{vif_map[:uuid]}(#{vif_map[:ipv4]}) -> [other] ***-******** (#{ipv4})"
      group_cmds << "ebtables -A d_#{vif_map[:uuid]}_arp --protocol arp --arp-ip-src #{ipv4} --arp-ip-dst #{vif_map[:ipv4]} --log-ip --log-arp --log-prefix 'Afw :d_#{vif_map[:uuid]}_arp' -j CONTINUE"
      group_cmds << "ebtables -A d_#{vif_map[:uuid]}_arp --protocol arp --arp-ip-src #{ipv4} --arp-ip-dst #{vif_map[:ipv4]} -j ACCEPT"
    end
  end

  group_cmds
end

#build_iptables_basic_part(vif_map, inst_map) ⇒ Object



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
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 564

def build_iptables_basic_part(vif_map, inst_map)
  basic_cmds = []

  network_map = rpc.request('hva-collector', 'get_network', inst_map[:instance_nics].first[:network_id])
  raise "UnknownNetworkId" if network_map.nil?

  ################################
  ## 0. chain name
  ################################

  # support IP protocol
  protocol_map = protocol_map(:iptables)

  # make chain names.
  chains = []
  protocol_map.each { |k,v|
    chains << "s_#{vif_map[:uuid]}_#{k}"
    chains << "d_#{vif_map[:uuid]}_#{k}"
  }
  chains << "s_#{vif_map[:uuid]}"
  chains << "d_#{vif_map[:uuid]}"

  ################################
  ## 1. basic part
  ################################

  # metadata-server
  port = network_map[:metadata_server_port] || 80
  [ 'A' ].each { |xcmd|
    basic_cmds << "iptables -t nat -#{xcmd} PREROUTING -m physdev --physdev-in #{vif_map[:uuid]} -d 169.254.169.254 -p tcp --dport 80 -j DNAT --to-destination #{network_map[:metadata_server]}:#{port}"
  }
  # create user defined chains.
  [ 'N' ].each { |xcmd|
    chains.each { |chain|
      basic_cmds << "iptables -#{xcmd} #{chain}"

      # logger & drop
      basic_cmds << "iptables -N #{chain}_drop"
      if @node.manifest.config.packet_drop_log
        basic_cmds << "iptables -A #{chain}_drop -j LOG --log-level 4 --log-prefix 'D #{chain}:'"
      end
      basic_cmds << "iptables -A #{chain}_drop -j DROP"
    }
  }

  # DHCP Server
  basic_cmds << "iptables -A d_#{vif_map[:uuid]}_udp -p udp ! -s #{network_map[:dhcp_server]} --sport 67 -j d_#{vif_map[:uuid]}_udp_drop"
  basic_cmds << "iptables -A d_#{vif_map[:uuid]}_udp -p udp ! -s #{network_map[:dhcp_server]} --sport 68 -j d_#{vif_map[:uuid]}_udp_drop"

  # group nodes
  # group node IPv4 addresses.
  ipv4s = rpc.request('hva-collector', 'get_group_instance_ipv4s', inst_map[:uuid])
  ipv4s << network_map[:ipv4_gw]
  ipv4s.uniq.reverse_each { |addr|
    basic_cmds << "iptables -A d_#{vif_map[:uuid]} -s #{addr} -j ACCEPT"
  }

  # IP protocol routing
  [ 's', 'd' ].each do |bound|
    protocol_map.each { |k,v|
      basic_cmds << "iptables -N #{bound}_#{vif_map[:uuid]}_#{k}"

      case k
      when 'tcp'
        case bound
        when 's'
          basic_cmds << "iptables -A #{bound}_#{vif_map[:uuid]} -m state --state NEW,ESTABLISHED -p #{k} -j #{bound}_#{vif_map[:uuid]}_#{k}"
        when 'd'
          basic_cmds << "iptables -A #{bound}_#{vif_map[:uuid]} -m state --state RELATED,ESTABLISHED -p #{k} -j ACCEPT"
          basic_cmds << "iptables -A #{bound}_#{vif_map[:uuid]} -p #{k} -j #{bound}_#{vif_map[:uuid]}_#{k}"
        end
      when 'udp'
        case bound
        when 's'
          basic_cmds << "iptables -A #{bound}_#{vif_map[:uuid]} -m state --state NEW,ESTABLISHED -p #{k} -j #{bound}_#{vif_map[:uuid]}_#{k}"
        when 'd'
          basic_cmds << "iptables -A #{bound}_#{vif_map[:uuid]} -m state --state ESTABLISHED -p #{k} -j ACCEPT"
          basic_cmds << "iptables -A #{bound}_#{vif_map[:uuid]} -p #{k} -j #{bound}_#{vif_map[:uuid]}_#{k}"
        end
      when 'icmp'
        case bound
        when 's'
          basic_cmds << "iptables -A #{bound}_#{vif_map[:uuid]} -m state --state NEW,ESTABLISHED,RELATED -p #{k} -j #{bound}_#{vif_map[:uuid]}_#{k}"
        when 'd'
          basic_cmds << "iptables -A #{bound}_#{vif_map[:uuid]} -m state --state ESTABLISHED,RELATED -p #{k} -j ACCEPT"
          basic_cmds << "iptables -A #{bound}_#{vif_map[:uuid]} -p #{k} -j #{bound}_#{vif_map[:uuid]}_#{k}"
        end
      end
    }
  end

  basic_cmds << "iptables -A FORWARD -m physdev --physdev-is-bridged --physdev-in  #{vif_map[:uuid]} -j s_#{vif_map[:uuid]}"
  basic_cmds << "iptables -A FORWARD -m physdev --physdev-is-bridged --physdev-out #{vif_map[:uuid]} -j d_#{vif_map[:uuid]}"

  ##
  ## ACCEPT
  ##
  # DHCP Server
  basic_cmds << "iptables -A d_#{vif_map[:uuid]}_udp -p udp -s #{network_map[:dhcp_server]} --sport 67 -j ACCEPT"
  basic_cmds << "iptables -A d_#{vif_map[:uuid]}_udp -p udp -s #{network_map[:dhcp_server]} --sport 68 -j ACCEPT"

  # DNS Server
  basic_cmds << "iptables -A s_#{vif_map[:uuid]}_udp -p udp -d #{network_map[:dns_server]} --dport 53 -j ACCEPT"

  ##
  ## DROP
  ##
  protocol_map.each { |k,v|
    # DHCP
    basic_cmds << "iptables -A s_#{vif_map[:uuid]} -d #{network_map[:dhcp_server]} -p #{k} -j s_#{vif_map[:uuid]}_#{k}_drop"
    # DNS
    basic_cmds << "iptables -A s_#{vif_map[:uuid]} -d #{network_map[:dns_server]} -p #{k} -j s_#{vif_map[:uuid]}_#{k}_drop"
  }

  basic_cmds
end

#build_iptables_final_part(vif_map) ⇒ Object



718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 718

def build_iptables_final_part(vif_map)
  final_cmds = []

  # support IP protocol
  protocol_map = protocol_map(:iptables)

  ################################
  ## 3. final part
  ################################

  # drop other routings
  protocol_map.each { |k,v|
    final_cmds << "iptables -A d_#{vif_map[:uuid]}_#{k} -p #{k} -j d_#{vif_map[:uuid]}_#{k}_drop"
  }

  # IP protocol routing
  [ 'd' ].each do |bound|
    protocol_map.each { |k,v|
      final_cmds << "iptables -A #{bound}_#{vif_map[:uuid]}_#{k} -j #{bound}_#{vif_map[:uuid]}_#{k}_drop"
    }
  end

  final_cmds
end

#build_iptables_group_part(vif_map, inst_map) ⇒ Object



681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 681

def build_iptables_group_part(vif_map, inst_map)
  group_cmds = []

  ################################
  ## 2. group part
  ################################
  ng_maps = rpc.request('hva-collector', 'get_netfilter_groups_of_instance', inst_map[:uuid])
  rules = ng_maps.map { |ng_map|
    ng_map[:rules].map { |rule| rule[:permission] }
  }.flatten

  # security group
  build_rule(rules).each do |rule|
    case rule[:ip_protocol]
    when 'tcp', 'udp'
      if rule[:ip_fport] == rule[:ip_tport]
        group_cmds << "iptables -A d_#{vif_map[:uuid]}_#{rule[:ip_protocol]} -p #{rule[:ip_protocol]} -s #{rule[:ip_source]} --dport #{rule[:ip_fport]} -j ACCEPT"
      else
        group_cmds << "iptables -A d_#{vif_map[:uuid]}_#{rule[:ip_protocol]} -p #{rule[:ip_protocol]} -s #{rule[:ip_source]} --dport #{rule[:ip_fport]}:#{rule[:ip_tport]} -j ACCEPT"
      end
    when 'icmp'
      # icmp
      #   This extension can be used if `--protocol icmp' is specified. It provides the following option:
      #   [!] --icmp-type {type[/code]|typename}
      #     This allows specification of the ICMP type, which can be a numeric ICMP type, type/code pair, or one of the ICMP type names shown by the command
      #      iptables -p icmp -h
      if rule[:icmp_type] == -1 && rule[:icmp_code] == -1
        group_cmds << "iptables -A d_#{vif_map[:uuid]}_#{rule[:ip_protocol]} -p #{rule[:ip_protocol]} -s #{rule[:ip_source]} -j ACCEPT"
      else
        group_cmds << "iptables -A d_#{vif_map[:uuid]}_#{rule[:ip_protocol]} -p #{rule[:ip_protocol]} -s #{rule[:ip_source]} --icmp-type #{rule[:icmp_type]}/#{rule[:icmp_code]} -j ACCEPT"
      end
    end
  end

  group_cmds
end

#build_rule(rules = []) ⇒ Object



743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 743

def build_rule(rules = [])
  rule_maps = []

  rules.each do |rule|
    rule = rule.strip.gsub(/[\s\t]+/, '')
    from_group = false
    ipv4s = []

    # ex.
    # "tcp:22,22,ip4:0.0.0.0"
    # "udp:53,53,ip4:0.0.0.0"
    # "icmp:-1,-1,ip4:0.0.0.0"

    # 1st phase
    # ip_tport    : tcp,udp? 1 - 16bit, icmp: -1
    # id_port has been separeted in first phase.
    from_pair, ip_tport, source_pair = rule.split(',')

    next if from_pair.nil?
    next if ip_tport.nil?
    next if source_pair.nil?

    # 2nd phase
    # ip_protocol : [ tcp | udp | icmp ]
    # ip_fport    : tcp,udp? 1 - 16bit, icmp: -1
    ip_protocol, ip_fport = from_pair.split(':')

    # protocol    : [ ip4 | ip6 | #{account_id} ]
    # ip_source   : ip4? xxx.xxx.xxx.xxx./[0-32], ip6? (not yet supprted), #{netfilter_group_id}
    protocol, ip_source = source_pair.split(':')

    begin
      s = StringScanner.new(protocol)
      until s.eos?
        case
        when s.scan(/ip6/)
          # TODO#FUTURE: support IPv6 address format
          next
        when s.scan(/ip4/)
          # IPAddress doesn't support prefix '0'.
          ip_addr, prefix = ip_source.split('/', 2)
          if prefix.to_i == 0
            ip_source = ip_addr
          end
        when s.scan(/a-\w{8}/)
          from_group = true
          inst_maps = rpc.request('hva-collector', 'get_instances_of_account_netfilter_group', protocol, ip_source)
          inst_maps.each { |inst_map|
            ipv4s << inst_map[:ips]
          }
        else
          raise "unexpected protocol '#{s.peep(20)}'"
        end
      end
    rescue Exception => e
      p e
      next
    end

    begin
      if from_group == false
        #p "from_group:(#{from_group}) ip_source -> #{ip_source}"
        ip = IPAddress(ip_source)
        ip_source = case ip.u32
                    when 0
                      "#{ip.address}/0"
                    else
                      "#{ip.address}/#{ip.prefix}"
                    end
      else
        ipv4s = ipv4s.flatten.uniq
      end
    rescue Exception => e
      p e
      next
    end

    case ip_protocol
    when 'tcp', 'udp'
      ip_fport = ip_fport.to_i
      ip_tport = ip_tport.to_i

      # validate port range
      [ ip_fport, ip_tport ].each do |port|
        next unless port >= 1 && port <= 65535
      end

      if ip_fport <= ip_tport
        if from_group == false
          rule_maps << {
            :ip_protocol => ip_protocol,
            :ip_fport    => ip_fport,
            :ip_tport    => ip_tport,
            :protocol    => protocol,
            :ip_source   => ip_source,
          }
        else
          ipv4s.each { |ip|
            rule_maps << {
              :ip_protocol => ip_protocol,
              :ip_fport    => ip_fport,
              :ip_tport    => ip_tport,
              :protocol    => 'ip4',
              :ip_source   => ip,
            }
          }
        end
      end
    when 'icmp'
      # via http://docs.amazonwebservices.com/AWSEC2/latest/CommandLineReference/
      #
      # For the ICMP protocol, the ICMP type and code must be specified.
      # This must be specified in the format type:code where both are integers.
      # Type, code, or both can be specified as -1, which is a wildcard.

      icmp_type = ip_fport.to_i
      icmp_code = ip_tport.to_i

      # icmp_type
      case icmp_type
      when -1
      when 0, 3, 5, 8, 11, 12, 13, 14, 15, 16, 17, 18
      else
        next
      end

      # icmp_code
      case icmp_code
      when -1
      when 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
        # when icmp_type equals -1 icmp_code must equal -1.
        next if icmp_type == -1
      else
        next
      end

      if from_group == false
        rule_maps << {
          :ip_protocol => ip_protocol,
          :icmp_type   => ip_tport.to_i, # ip_tport.to_i, # -1 or 0,       3,    5,       8,        11, 12, 13, 14, 15, 16, 17, 18
          :icmp_code   => ip_fport.to_i, # ip_fport.to_i, # -1 or 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
          :protocol    => protocol,
          :ip_source   => ip_source,
        }
      else
        ipv4s.each { |ip|
          rule_maps << {
            :ip_protocol => ip_protocol,
            :icmp_type   => ip_tport.to_i, # ip_tport.to_i, # -1 or 0,       3,    5,       8,        11, 12, 13, 14, 15, 16, 17, 18
            :icmp_code   => ip_fport.to_i, # ip_fport.to_i, # -1 or 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
            :protocol    => 'ip4',
            :ip_source   => ip,
          }
        }
      end
    end
  end

  rule_maps
end

#build_vif_map(inst_map = {}) ⇒ Object



259
260
261
262
263
264
265
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 259

def build_vif_map(inst_map = {})
  vif_map = {
    :uuid  => inst_map[:instance_nics].first[:uuid],
    :mac   => inst_map[:instance_nics].first[:mac_addr].unpack('A2'*6).join(':'),
    :ipv4  => inst_map[:ips].first,
  }
end

#do_exec(cmds) ⇒ Object



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 285

def do_exec(cmds)
  recmds = []

  eos = "__EOS_#{Isono::Util.gen_id}___"
  recmds << "/bin/cat <<'#{eos}' | /bin/bash"
  cmds.flatten.uniq.each { |cmd|
    puts cmd if @node.manifest.config.verbose_netfilter == true
    recmds << cmd
  }
  recmds << "#{eos}"

  logger.debug("applying rule line(s): #{recmds.size - 2}")
  system(recmds.join("\n"))
  logger.debug("applied rule line(s): #{recmds.size - 2}")
end

#eventObject



908
909
910
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 908

def event
  @event ||= Isono::NodeModules::EventChannel.new(@node)
end

#init_bandwidth_limit(network_maps) ⇒ Object



379
380
381
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 379

def init_bandwidth_limit(network_maps)
  do_exec([clear_bandwidth_limits,limit_bandwidth(network_maps)])
end

#init_ebtables(inst_maps = [], viftable_map = {}) ⇒ Object



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
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 301

def init_ebtables(inst_maps = [], viftable_map = {})
  init_cmds  = []
  basic_cmds = []
  group_cmds = []
  nat_cmds   = []
  final_cmds = []

  init_cmds << "ebtables --init-table"
  #Clear the nat table. This table is only used in build_ebtables_nat_part
  init_cmds << "ebtables -t nat --init-table"

  inst_maps.each { |inst_map|
    vif_map = build_vif_map(inst_map)

    basic_cmds << build_ebtables_basic_part(vif_map, inst_map)            
    group_cmds << build_ebtables_group_part(vif_map, inst_map, viftable_map)
    final_cmds << build_ebtables_final_part(vif_map)
  }

  viftable_map.each { |k,v|
    logger.debug("viftable: #{v} <=> #{k}")
  }

  do_exec([init_cmds, basic_cmds, group_cmds, final_cmds])
end

#init_iptables(inst_maps = []) ⇒ Object



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
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 327

def init_iptables(inst_maps = [])
  init_cmds  = []
  basic_cmds = []
  group_cmds = []
  nat_cmds   = []
  final_cmds = []

  [ 'raw', 'nat', 'filter' ].each { |table|
    [ 'F', 'Z', 'X' ].each { |xcmd|
      init_cmds << "iptables -t #{table} -#{xcmd}"
    }
  }
  
  #TODO: Make an option in the config file to use ipset
  use_ipset = true
  if use_ipset
    ['F','X'].each { |xcmd|
      init_cmds << "ipset -#{xcmd}"
    }
  end

  # via http://backreference.org/2010/06/11/iptables-debugging/
  # To debug ipv4 packets.
  # $ sudo tail -F /var/log/kern.log | grep TRACE:
  if @node.manifest.config.debug_iptables
    init_cmds << "iptables -t raw -A OUTPUT -p icmp -j TRACE"
    init_cmds << "iptables -t raw -A PREROUTING -p icmp -j TRACE"
  end

  inst_maps.each { |inst_map|
    vif_map = build_vif_map(inst_map)

    basic_cmds << build_iptables_basic_part(vif_map, inst_map)
    group_cmds << build_iptables_group_part(vif_map, inst_map)
    final_cmds << build_iptables_final_part(vif_map)
  }

  do_exec([init_cmds, basic_cmds, group_cmds, final_cmds])
end

#init_netfilterObject



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
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 190

def init_netfilter
  begin
    inst_maps = rpc.request('hva-collector', 'get_alive_instances', node.node_id)

    viftable_map = {}
    inst_maps = inst_maps.map { |inst_map|
      viftable_map[ inst_map[:ips].first ] = inst_map[:instance_nics].first[:uuid]

      # Does the hva have instance?
      unless inst_map[:host_pool][:node_id] == node.node_id
        logger.warn("no match for the instance: #{inst_map[:uuid]}")
        next
      end
      # Does host have vif?
      next unless valid_nic?(inst_map[:instance_nics].first[:uuid])
      inst_maps
    }.flatten.uniq.compact

    init_iptables(inst_maps) if @node.manifest.config.enable_iptables
    init_ebtables(inst_maps, viftable_map) if @node.manifest.config.enable_ebtables
    init_static_nat(inst_maps) if @node.manifest.config.enable_iptables && @node.manifest.config.enable_ebtables
    init_bandwidth_limit(networks = rpc.request('hva-collector', 'get_networks')) if @node.manifest.config.enable_iptables
    sleep 1

    logger.info("initialized netfilter")
  rescue Exception => e
    p e
  end
end

#init_static_nat(inst_maps = []) ⇒ Object



367
368
369
370
371
372
373
374
375
376
377
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 367

def init_static_nat(inst_maps = [])
  accept_cmds = []
  nat_cmds    = []
  
  inst_maps.each { |inst_map|
    accept_cmds << nat_exceptions(inst_map) unless @node.manifest.config.use_ipset
    nat_cmds    << nat_instance(inst_map)
  }
  
  do_exec([accept_cmds,nat_cmds])
end

#protocol_map(type) ⇒ Object



267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 267

def protocol_map(type)
  case type
  when :iptables
    {
      'tcp'  => 'tcp',
      'udp'  => 'udp',
      'icmp' => 'icmp',
    }
  when :ebtables
    {
      'ip4'  => 'ip4',
      'arp'  => 'arp',
      #'ip6'  => 'ip6',
      #'rarp' => '0x8035',
    }
  end
end

#refresh_netfilter_by_friend_instance_id(inst_id) ⇒ Object

from event_subscriber



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 221

def refresh_netfilter_by_friend_instance_id(inst_id)
  raise "UnknownInstanceID" if inst_id.nil?

  begin
    ng_maps = rpc.request('hva-collector', 'get_netfilter_groups_of_instance', inst_id)
    # get friend instance(s)
    friend_inst_maps = ng_maps.map { |ng_map|
      rpc.request('hva-collector', 'get_instances_of_netfilter_group', ng_map[:id])
    }.flatten.uniq
    guest_inst_maps = rpc.request('hva-collector', 'get_alive_instances', node.node_id)

    uuids = friend_inst_maps.map { |inst_map| inst_map[:uuid] } & guest_inst_maps.map  { |inst_map| inst_map[:uuid] }
    logger.info("my guest instance(s)?: #{uuids.inspect}")

    if uuids.flatten.uniq.size > 0
      init_netfilter
    else
      # group_instance: 1->0
      inst_map = rpc.request('hva-collector', 'get_instance', inst_id)
      init_netfilter if inst_map[:host_pool][:node_id] == node.node_id
    end
  rescue Exception => e
    p e
  end
end

#refresh_netfilter_by_joined_netfilter_group_id(netfilter_group_id) ⇒ Object

from event_subscriber



248
249
250
251
252
253
254
255
256
257
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 248

def refresh_netfilter_by_joined_netfilter_group_id(netfilter_group_id)
  raise "UnknownNetfilterGroupID" if netfilter_group_id.nil?

  begin
    inst_maps = rpc.request('hva-collector', 'get_instances_of_netfilter_group', netfilter_group_id)
    init_netfilter if inst_maps.size > 0
  rescue Exception => e
    p e
  end
end

#rpcObject



904
905
906
# File 'lib/dcmgr/node_modules/service_netfilter.rb', line 904

def rpc
  @rpc ||= Isono::NodeModules::RpcChannel.new(@node)
end