Example #1
0
 def test_set_sensor_interface_error (self):
     print ("Testing set_sensor_interfacesa with an unknown interface name")
     sys_ifaces = [iface.name for iface in  netinterfaces.get_network_interfaces() if iface.name !='lo']
     #print "Traza 1:" + str(sys_ifaces)
     nose.tools.ok_ (len(sys_ifaces)>0, msg="The system needs at least one network interface disting of lo")
     (result, resp) = set_sensor_interfaces ("127.0.0.1", ["gamusino", "ascodevida"])
     nose.tools.ok_ (result == False, msg="gamusiono must be no a valid iface name")
Example #2
0
def put_sensor_interface(sensor_id):
    """
    Set the [sensor]/interfaces list on ossim_setup.conf of the sensor
    """
    # Get the 'ifaces' param list, with contains the ifaces
    # It must be a comma separate list
    ifaces = request.args.get('ifaces')
    if ifaces is None:
        current_app.logger.error("interfaces: put_sensor_interface error: Missing parameter 'ifaces'")
        return make_bad_request("Missing parameter ifaces")

    (success, sensor_ip) = get_sensor_ip_from_sensor_id(sensor_id)
    if not success:
        current_app.logger.error("interfaces: put_sensor_interface  error: Bad 'sensor_id'")
        return make_bad_request("Bad sensor_id")

    # Call the ansible module to obtain the [sensor]/iface
    (success, data) = set_sensor_interfaces(sensor_ip, ifaces)
    if not success:
        current_app.logger.error("interfaces: put_sensor_interfaces_from_conf error: %s" % data)
        return make_error("Error setting sensor interfaces", 500)

    # Now launch reconfig task
    job = alienvault_reconfigure.delay(sensor_ip)

    # Now format the list by a dict which key is the sensor_id and the value if the list of ifaces
    return make_ok(job_id_reconfig=job.id)
Example #3
0
 def test_set_sensor_interfaces (self):
     print ("Testing set_sensor_interfaces")
     sys_ifaces = [iface.name for iface in  netinterfaces.get_network_interfaces() if iface.name !='lo']
     #print "Traza 1:" + str(sys_ifaces)
     nose.tools.ok_ (len(sys_ifaces)>0, msg="The system needs at least one network interface disting of lo")
     # Generate a list of ramdom ifaces
     test_ifaces = random.sample (sys_ifaces, random.randint(1, len(sys_ifaces)))
     # Backup de system interfaces
     (result, backup_ifaces) = get_sensor_interfaces ("127.0.0.1")
     nose.tools.ok_ (result == True, msg="Can't get backup of ossim_setup.conf interfaces")
     (result, resp) = set_sensor_interfaces ("127.0.0.1", ",".join(test_ifaces))
     nose.tools.ok_ (result == True, msg="Error in set_sensor_interfaces")
     # Verify
     nose.tools.ok_ (self.__verify_iface_list (test_ifaces) == True, msg="Can't verify interface list")
     # Restore backup 
     (result, resp) = set_sensor_interfaces ("127.0.0.1",
                                             ",".join  (backup_ifaces))
     nose.tools.ok_ (result == True, msg="Can't restore backup interfaces =>" + str(resp) + " Result: " + str(result))
     nose.tools.ok_ (self.__verify_iface_list (backup_ifaces) == True, msg="Can't verify interface list")
Example #4
0
def set_interfaces_roles(system_ip,interface_roles):
    """ Check the role of subset of intefaces in the system
    
        @param system_ip      The system IP where we're going to operate
        @param inteface_roles  A json describing each interface we're going
                              to touch
        interface_role format:
        { "iface" : {"role":<role>, "ipaddress":<ipaddress>, "netmask":<netmask>}, ...}
        
        The possibles roles and params
            monitoring => no ipaddress and no netmask
            log_management => ipaddress and netmask must be present
            disable => no ipaddress and no netmask
        iface is the name of the network interface as configures (eth0, eth1, etc)
        iface SHOULD NOT BE the admin interface
                               
    """
    def get_admin_interface_from_current_status(current_status):
        for interface, interface_data in current_status.iteritems():
            if interface_data['role'] == 'admin':
                return interface
        return None

    # check params
    if system_ip == "":
        return False, "The system_ip should be a valid IP Address"
    if not isinstance(interface_roles, dict):
        return False, "The interface_roles should be a dictionary"
    if len(interface_roles)<=0:
        return False, "Empty interface roles"
    # Retrieve the current status.
    rc, net_current_status = get_iface_list(system_ip)

    if not rc:
        return False, "We can't retrieve the current status of the network configuration: %s" % net_current_status

    # The management interface can't be set.
    admin_interface = get_admin_interface_from_current_status(net_current_status)
    if admin_interface is not None:
        if admin_interface in interface_roles.keys():
            return False, "'%s' is the admin interface. You can't set the role" % admin_interface

    # Retrieve the network interface list from ansible facts
    response = ansible.run_module([system_ip],
                                  module="av_setup",
                                  args="filter=ansible_interfaces",
                                  use_sudo=True)

    if system_ip in response['dark']:
        return False, "We can't retrieve the current network interface list: %s" % response['dark'][system_ip]

    if response['contacted'][system_ip].get('Failed',False) is True:
        return False, "We can't retrieve the current network interface list: %s" % response['contacted'][system_ip]

    # Ok, now in response we have all systems interfaces returned  by ansible
    # u'ansible_facts': {u'ansible_interfaces': [u'lo', u'bond0', u'eth2', u'eth1', u'eth0']}}}} 
    # First verify that the admin iface is in the list
    system_interfaces = response['contacted'][system_ip]['ansible_facts']['ansible_interfaces']
    if admin_interface not in system_interfaces:
        return False, "Internal error admin iface '%s' not in system interfaces '%s'" % \
                     (admin_interface, str(system_interfaces))

    # Check that all ifaces are included in system_ifaces
    if not set(interface_roles.keys()).issubset(set(system_interfaces)):
        return False, "There are interfaces in the request that are not present in the system"

    # Retrieves the current [sensor]interfaces from ossim_setup.conf
    (success, sensor_ifaces) = get_sensor_interfaces(system_ip)
    if not success:
        return False, "Can't get current sensor interfaces"
    sensor_ifaces = sensor_ifaces['sensor_interfaces']
    # Ok, now we must check that each param obeys the constrains

    # Retrieve the system configured interfaces
    (success,system_configured_ifaces) = get_conf_network_interfaces(system_ip, store_path=True)
    if not success:
        return False, "Can't retrieve the current configured interfaces"

    # Build a hash table with key=ethx and value False
    result_ifaces = dict([(x, False) for x in interface_roles.keys()])

    old_sensor_ifaces = sensor_ifaces[:]  # CLone, python use refs
    removed_interfaces = []
    added_interfaces = []

    # Before attempting to make changes we have to check if the result of the operation would be consistent
    future_net_status = net_current_status.copy()
    for iface, conf in interface_roles.items():
        role = conf.get('role', None)
        netmask = conf.get('netmask', None)
        address = conf.get('ipaddress', None)
        if future_net_status.has_key(iface):
            if future_net_status[iface]['role'] != role:
                future_net_status[iface].pop('ipv4', None) # Clear the old IPv4 because we have change roles
            future_net_status[iface]['role'] = role
            # We need to clear all the info if we changed the role
            future_net_status[iface]['promisc'] = False
            if role == 'monitoring':
                future_net_status[iface]['promisc'] = True
            if role == 'log_management':
                ipconf = {'network': "", 'netmask': netmask, 'address': address}
                future_net_status[iface]['ipv4'] = ipconf

    admin_interfaces_future_net_status = [iface for iface, data in future_net_status.iteritems() if
                                          data['role'] is 'admin']

    if len(admin_interfaces_future_net_status) > 1:
        return False, "The admin interface is: %s and it's not allowed to configure more than one %s" % (
        admin_interface, admin_interfaces_future_net_status)

    ip_interfaces = [data['ipv4']['address'] for iface, data in future_net_status.iteritems() if
                     'ipv4' in data and data['ipv4']['address'] is not None and data['role'] is not 'disabled' and data['role'] is not 'monitoring']

    if len(ip_interfaces) > len(set(ip_interfaces)):
        return False, "It's not allowed to have more than one interface with the same ip"

    for iface, conf in interface_roles.items():
        role = conf.get('role', None)
        if role == "log_management":
            iface_netmask = conf.get('netmask', None)
            iface_address = conf.get('ipaddress', None)

            if iface_address is None:
                result_ifaces[iface] = (False,
                                        "In order to configure the given interface (%s) as a log management "
                                        "interface we need an IP address(%s)" % (
                                            iface, iface_address))
                continue
            if iface_netmask is None:
                result_ifaces[iface] = (False,
                                        "In order to configure the given interface (%s) as a log management "
                                        "interface we need a valid netmask (%s)" % (
                                            iface, iface_netmask))
                continue

            (success, result) = set_conf_iface(system_ip, iface, iface_address, iface_netmask)
            if not success:
                api_log.error("Can't configure iface '%s' msg: %s " % (iface, str(result)))
                result_ifaces[iface] = (False, "Can't configure iface '%s' msg: %s" % (iface, str(result)))
                continue
            result_ifaces[iface] = (True, "Configured in /etc/network/interfaces")
            added_interfaces.append(iface)
            if iface in sensor_ifaces:
                sensor_ifaces.remove(iface)

        elif role == 'disabled' or role == 'monitoring':
            # Check if the iface is in the
            if iface in system_configured_ifaces.keys():
                # Down iface
                (success,result) = iface_debian_down(system_ip,[iface])
                if not success:
                    api_log.error("Can't bring down configured iface '%s' " % iface)
                    result_ifaces[iface] = False,"Can't bring down configured iface '%s' " % iface
                    continue
                (success,result) = delete_conf_iface (system_ip, iface)
                if not success:
                    result_ifaces[iface] = (False,
                                            "Can't delete iface from /etc/network/interfaces msg: %s" % str(result))
                    continue

                removed_interfaces.append(iface)
                result_ifaces[iface] = (True, "Removed from /etc/network/interfaces")
            else:
                result_ifaces[iface] = (True, "Not in /etc/network/interfaces")

            if role == 'disabled':
                removed_interfaces.append(iface)
                if iface in sensor_ifaces:
                    sensor_ifaces.remove(iface)
            else:
                added_interfaces.append(iface)
                if iface not in sensor_ifaces:
                    sensor_ifaces.append(iface)
        else:
            return False, "Invalid Role (%s) for the interface %s" % (role, iface)

    # Here the code must be OK
    # How can we make and atomic "configuration" of this code

    # Now, check if we have to change the [sensor]interfaces
    # First, now ifdown
    (success,msg) = iface_down(system_ip, removed_interfaces)
    if not success:
        return False, "Something wrong has happened while setting down the interfaces %s" % msg
    # Give me up
    (success, msg) = iface_up(system_ip, added_interfaces)
    if not success:
        return False, "Something wrong has happened while setting up the interfaces %s" % msg

    if set(sensor_ifaces) != set(old_sensor_ifaces):
        # Set the ne sensors
        (success,msg) = set_sensor_interfaces(system_ip,",".join(sensor_ifaces))
        if not success:
            return False, result_ifaces

    # Regenerate /etc/alienvault/network/interfaces
    # It should be done until all the interface management is ported to use lib av_config
    fire_trigger(system_ip=system_ip,
                 trigger="alienvault-network-interfaces-migrate",
                 execute_trigger=False)

    return True, result_ifaces
Example #5
0
def set_interfaces_roles(system_ip,interface_roles):
    """ Check the role of subset of intefaces in the system
    
        @param system_ip      The system IP where we're going to operate
        @param inteface_roles  A json describing each interface we're going
                              to touch
        interface_role format:
        { "iface" : {"role":<role>, "ipaddress":<ipaddress>, "netmask":<netmask>}, ...}
        
        The possibles roles and params
            monitoring => no ipaddress and no netmask
            log_management => ipaddress and netmask must be present
            disable => no ipaddress and no netmask
        iface is the name of the network interface as configures (eth0, eth1, etc)
        iface SHOULD NOT BE the admin interface
                               
    """
    def get_admin_interface_from_current_status(current_status):
        for interface, interface_data in current_status.iteritems():
            if interface_data['role'] == 'admin':
                return interface
        return None

    # check params
    if system_ip == "":
        return False, "The system_ip should be a valid IP Address"
    if not isinstance(interface_roles, dict):
        return False, "The interface_roles should be a dictionary"
    if len(interface_roles)<=0:
        return False, "Empty interface roles"
    # Retrieve the current status.
    rc, net_current_status = get_iface_list(system_ip)

    if not rc:
        return False, "We can't retrieve the current status of the network configuration: %s" % net_current_status

    # The management interface can't be set.
    admin_interface = get_admin_interface_from_current_status(net_current_status)
    if admin_interface is not None:
        if admin_interface in interface_roles.keys():
            return False, "'%s' is the admin interface. You can't set the role" % admin_interface

    # Retrieve the network interface list from ansible facts
    response = ansible.run_module([system_ip],
                                  module="av_setup",
                                  args="filter=ansible_interfaces",
                                  use_sudo=True)

    if system_ip in response['dark']:
        return False, "We can't retrieve the current network interface list: %s" % response['dark'][system_ip]

    if response['contacted'][system_ip].get('Failed',False) is True:
        return False, "We can't retrieve the current network interface list: %s" % response['contacted'][system_ip]

    # Ok, now in response we have all systems interfaces returned  by ansible
    # u'ansible_facts': {u'ansible_interfaces': [u'lo', u'bond0', u'eth2', u'eth1', u'eth0']}}}} 
    # First verify that the admin iface is in the list
    system_interfaces = response['contacted'][system_ip]['ansible_facts']['ansible_interfaces']
    if admin_interface not in system_interfaces:
        return False, "Internal error admin iface '%s' not in system interfaces '%s'" % \
                     (admin_interface, str(system_interfaces))

    # Check that all ifaces are included in system_ifaces
    if not set(interface_roles.keys()).issubset(set(system_interfaces)):
        return False, "There are interfaces in the request that are not present in the system"

    # Retrieves the current [sensor]interfaces from ossim_setup.conf
    (success, sensor_ifaces) = get_sensor_interfaces(system_ip)
    if not success:
        return False, "Can't get current sensor interfaces"
    sensor_ifaces = sensor_ifaces['sensor_interfaces']
    # Ok, now we must check that each param obeys the constrains

    # Retrieve the system configured interfaces
    (success,system_configured_ifaces) = get_conf_network_interfaces(system_ip, store_path=True)
    if not success:
        return False, "Can't retrieve the current configured interfaces"

    # Build a hash table with key=ethx and value False
    result_ifaces = dict([(x, False) for x in interface_roles.keys()])

    old_sensor_ifaces = sensor_ifaces[:]  # CLone, python use refs
    removed_interfaces = []
    added_interfaces = []

    # Before attempting to make changes we have to check if the result of the operation would be consistent
    future_net_status = net_current_status.copy()
    for iface, conf in interface_roles.items():
        role = conf.get('role', None)
        netmask = conf.get('netmask', None)
        address = conf.get('ipaddress', None)
        if future_net_status.has_key(iface):
            if future_net_status[iface]['role'] != role:
                future_net_status[iface].pop('ipv4', None) # Clear the old IPv4 because we have change roles
            future_net_status[iface]['role'] = role
            # We need to clear all the info if we changed the role
            future_net_status[iface]['promisc'] = False
            if role == 'monitoring':
                future_net_status[iface]['promisc'] = True
            if role == 'log_management':
                ipconf = {'network': "", 'netmask': netmask, 'address': address}
                future_net_status[iface]['ipv4'] = ipconf

    admin_interfaces_future_net_status = [iface for iface, data in future_net_status.iteritems() if
                                          data['role'] is 'admin']

    if len(admin_interfaces_future_net_status) > 1:
        return False, "The admin interface is: %s and it's not allowed to configure more than one %s" % (
        admin_interface, admin_interfaces_future_net_status)

    ip_interfaces = [data['ipv4']['address'] for iface, data in future_net_status.iteritems() if
                     'ipv4' in data and data['ipv4']['address'] is not None and data['role'] is not 'disabled' and data['role'] is not 'monitoring']

    if len(ip_interfaces) > len(set(ip_interfaces)):
        return False, "It's not allowed to have more than one interface with the same ip"

    for iface, conf in interface_roles.items():
        role = conf.get('role', None)
        if role == "log_management":
            iface_netmask = conf.get('netmask', None)
            iface_address = conf.get('ipaddress', None)

            if iface_address is None:
                result_ifaces[iface] = (False,
                                        "In order to configure the given interface (%s) as a log management "
                                        "interface we need an IP address(%s)" % (
                                            iface, iface_address))
                continue
            if iface_netmask is None:
                result_ifaces[iface] = (False,
                                        "In order to configure the given interface (%s) as a log management "
                                        "interface we need a valid netmask (%s)" % (
                                            iface, iface_netmask))
                continue

            (success, result) = set_conf_iface(system_ip, iface, iface_address, iface_netmask)
            if not success:
                api_log.error("Can't configure iface '%s' msg: %s " % (iface, str(result)))
                result_ifaces[iface] = (False, "Can't configure iface '%s' msg: %s" % (iface, str(result)))
                continue
            result_ifaces[iface] = (True, "Configured in /etc/network/interfaces")
            added_interfaces.append(iface)
            if iface in sensor_ifaces:
                sensor_ifaces.remove(iface)

        elif role == 'disabled' or role == 'monitoring':
            # Check if the iface is in the
            if iface in system_configured_ifaces.keys():
                # Down iface
                (success,result) = iface_debian_down(system_ip,[iface])
                if not success:
                    api_log.error("Can't bring down configured iface '%s' " % iface)
                    result_ifaces[iface] = False,"Can't bring down configured iface '%s' " % iface
                    continue
                (success,result) = delete_conf_iface (system_ip, iface)
                if not success:
                    result_ifaces[iface] = (False,
                                            "Can't delete iface from /etc/network/interfaces msg: %s" % str(result))
                    continue

                removed_interfaces.append(iface)
                result_ifaces[iface] = (True, "Removed from /etc/network/interfaces")
            else:
                result_ifaces[iface] = (True, "Not in /etc/network/interfaces")

            if role == 'disabled':
                removed_interfaces.append(iface)
                if iface in sensor_ifaces:
                    sensor_ifaces.remove(iface)
            else:
                added_interfaces.append(iface)
                if iface not in sensor_ifaces:
                    sensor_ifaces.append(iface)
        else:
            return False, "Invalid Role (%s) for the interface %s" % (role, iface)

    # Here the code must be OK
    # How can we make and atomic "configuration" of this code

    # Now, check if we have to change the [sensor]interfaces
    # First, now ifdown
    (success,msg) = iface_down(system_ip, removed_interfaces)
    if not success:
        return False, "Something wrong has happened while setting down the interfaces %s" % msg
    # Give me up
    (success, msg) = iface_up(system_ip, added_interfaces)
    if not success:
        return False, "Something wrong has happened while setting up the interfaces %s" % msg

    if set(sensor_ifaces) != set(old_sensor_ifaces):
        # Set the ne sensors
        (success,msg) = set_sensor_interfaces(system_ip,",".join(sensor_ifaces))
        if not success:
            return False, result_ifaces

    # Regenerate /etc/alienvault/network/interfaces
    # It should be done until all the interface management is ported to use lib av_config
    fire_trigger(system_ip=system_ip,
                 trigger="alienvault-network-interfaces-migrate",
                 execute_trigger=False)

    return True, result_ifaces