Pergunta

I don't know much about Ruby and I need to understand what this script does. I know it calls ebtables to add rules that configure networks for Virtual machines. But I'm not sure how?

this is the code:

#!/usr/bin/env ruby

require 'pp'
require 'rexml/document'

VM_NAME=ARGV[0]

# Uncomment to act only on the listed bridges.
#FILTERED_BRIDGES = ['beth0']

def activate(rule)
    system "sudo ebtables -A #{rule}"
end

def get_bridges
    bridges = Hash.new
    brctl_exit=`brctl show`
    cur_bridge = ""
    brctl_exit.split("\n")[1..-1].each do |l| 
        l = l.split
        if l.length > 1
            cur_bridge = l[0]
            bridges[cur_bridge] = Array.new
            bridges[cur_bridge] << l[3]
        else
            bridges[cur_bridge] << l[0]
        end
    end
    bridges
end

def get_interfaces
    bridges = get_bridges
    if defined? FILTERED_BRIDGES
        FILTERED_BRIDGES.collect {|k,v| bridges[k]}.flatten
    else
        bridges.values.flatten
    end
end

nets=`virsh -c qemu:///system dumpxml #{VM_NAME}`

doc=REXML::Document.new(nets).root

interfaces = get_interfaces()

doc.elements.each('/domain/devices/interface') {|net|
    tap=net.elements['target'].attributes['dev']
    if interfaces.include? tap
        iface_mac=net.elements['mac'].attributes['address']

        mac=iface_mac.split(':')
        mac[-1]='00'
        net_mac=mac.join(':')


        in_rule="FORWARD -s ! #{net_mac}/ff:ff:ff:ff:ff:00 -o #{tap} -j DROP"
        out_rule="FORWARD -s ! #{iface_mac} -i #{tap} -j DROP"

        activate(in_rule)
        activate(out_rule)
    end
}

So apparently it extracts mac adresses (not sure which ones) and drops packet/or forwards them somewhere?

Thanks a lot for your help!

Foi útil?

Solução

The script runs virsh -c qemu:///system dumpxml #{VM_NAME} where VM_NAME is the first parameter to the script.

It actually runs it twice, most certainly by mistake. The first run

nets=`virsh -c qemu:///system dumpxml #{VM_NAME}`

then it runs it a second time and places the XML output in the variable doc

doc=REXML::Document.new(nets).root

It then loops over the interfaces, getting the value from attribute dev in the element <target. If that value is in the result from the brctl show command it gets the MAC address from the address attribute in the <mac> element.

The MAC is split to an array by : and the last element in that array is changed to '00' and the net_mac is created from that array.

#{net_mac} in the in_rule assignment will be replaced by the newly constructed net_mac. And so on.

Then the in_rule and out_rule are applied with the sudo ebtables -A #{rule} command.

Clear?

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top