Exemplo n.º 1
0
def runCmd(command, with_stdout = False, with_stderr = False, inputtext = None):
    cmd = subprocess.Popen(command, bufsize = 1,
                           stdin = (inputtext and subprocess.PIPE or None),
                           stdout = subprocess.PIPE,
                           stderr = subprocess.PIPE,
                           shell = isinstance(command, str))

    (out, err) = cmd.communicate(inputtext)
    rv = cmd.returncode

    l = "ran %s; rc %d" % (str(command), rv)
    if inputtext:
        l += " with input %s" % inputtext
    if out != "":
        l += "\nSTANDARD OUT:\n" + out
    if err != "":
        l += "\nSTANDARD ERROR:\n" + err
    logger.debug(l)

    if with_stdout and with_stderr:
        return rv, out, err
    elif with_stdout:
        return rv, out
    elif with_stderr:
        return rv, err
    return rv
Exemplo n.º 2
0
def runCmd(command, with_stdout=False, with_stderr=False, inputtext=None):
    cmd = subprocess.Popen(command,
                           bufsize=1,
                           stdin=(inputtext and subprocess.PIPE or None),
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE,
                           shell=isinstance(command, str))

    (out, err) = cmd.communicate(inputtext)
    rv = cmd.returncode

    l = "ran %s; rc %d" % (str(command), rv)
    if inputtext:
        l += " with input %s" % inputtext
    if out != "":
        l += "\nSTANDARD OUT:\n" + out
    if err != "":
        l += "\nSTANDARD ERROR:\n" + err

    for line in l.split('\n'):
        logger.debug(line)

    if with_stdout and with_stderr:
        return rv, out, err
    elif with_stdout:
        return rv, out
    elif with_stderr:
        return rv, err
    return rv
Exemplo n.º 3
0
def inject_to_vifs(args):
    log.debug('Entry point: Inject IGMP query per pif')
    if args.no_check_snooping_toggle:
        vifs = args.vifs
    else:
        vifs = [vif for vif in args.vifs if igmp_snooping_is_enabled_on_bridge_of_vif(vif)]
    injector = IGMPQueryInjector(args.max_resp_time, vifs, args.vif_connected_timeout)
    return injector.inject()
Exemplo n.º 4
0
def inject_to_vifs(args):
    log.debug('Entry point: Inject IGMP query per pif')
    if args.no_check_snooping_toggle:
        vifs = args.vifs
    else:
        vifs = [vif for vif in args.vifs if igmp_snooping_is_enabled_on_bridge_of_vif(vif)]
    injector = IGMPQueryInjector(args.max_resp_time, vifs, args.vif_connected_timeout)
    return injector.inject()
Exemplo n.º 5
0
 def fileContents(self, fn):
     key = 'file:' + fn
     if key not in self.cache:
         logger.debug("Opening " + fn)
         f = open(fn)
         self.cache[key] = ''.join(f.readlines())
         f.close()
     return self.cache[key]
Exemplo n.º 6
0
 def fileContents(self, fn):
     key = 'file:' + fn
     if key not in self.cache:
         logger.debug("Opening " + fn)
         f = open(fn)
         self.cache[key] = ''.join(f.readlines())
         f.close()
     return self.cache[key]
Exemplo n.º 7
0
    def del_interface(self, interface):
        """remove an interface from this device

        :param interface:(UsbInterface) the UsbInterface to remove
        :return: None
        """
        if interface in self.interfaces:
            log.debug("removing interface: " + interface)
            self.interfaces.remove(interface)
Exemplo n.º 8
0
    def openAddress(self, address):
        logger.debug("Opening "+address)
        self._cleanup()
        url = urllib.unquote(address)

        self.ftp.voidcmd('TYPE I')
        s = self.ftp.transfercmd('RETR ' + url).makefile('rb')
        self.cleanup = True
        return s
Exemplo n.º 9
0
    def openAddress(self, address):
        logger.debug("Opening " + address)
        self._cleanup()
        url = urllib.unquote(address)

        self.ftp.voidcmd('TYPE I')
        s = self.ftp.transfercmd('RETR ' + url).makefile('rb')
        self.cleanup = True
        return s
Exemplo n.º 10
0
    def add_interface(self, interface):
        """ add an interface to this device

        :param interface:(UsbInterface) the UsbInterface to add
        :return: None
        """
        if interface in self.interfaces:
            log.debug("overriding existing interface: " + interface)
            self.interfaces.remove(interface)
        self.interfaces.add(interface)
Exemplo n.º 11
0
    def check(self, device):
        """check if a usb device can be passed through

        if one of device's interfaces is denied by rule, the device is denied.
        Normally, there should be a catch all rule at last line of policy file:
            ALLOW: # Otherwise allow everything else
        If there isn't, and no matching rule is found, the interface will also
        be denied.

        Only if all interfaces are allowed, the device is allowed to passed
        through.

        Example of a device before checking
        UsbDevice: (u'1-2', {'idVendor': '17ef', 'ID_VENDOR_FROM_DATABASE':
        u'Lenovo', 'bConfigurationValue': '1', 'bDeviceClass': '00',
        'ID_MODEL_FROM_DATABASE': '', 'version': ' 2.00', 'idProduct': '383c',
          'bNumInterfaces': ' 1', 'serial': 'H8RU2TGE', 'bcdDevice': '0100'})
            |__ UsbInterface: (u'1-2:1.0', {'bInterfaceNumber': '00',
            'bInterfaceClass': '08', 'bInterfaceProtocol': '50',
            'bInterfaceSubClass': '06'})
            |__ Allow: False

        UsbDevice: (u'4-1.2', {'idVendor': '2717', 'ID_VENDOR_FROM_DATABASE':
         '' , 'bConfigurationValue': '1', 'bDeviceClass': '00',
        'ID_MODEL_FROM_DATABASE': '', 'version': ' 2.00', 'idProduct': 'ff48',
          'bNumInterfaces': ' 2', 'serial': '7b06864', 'bcdDevice': '0404'})
            |__ UsbInterface: (u'4-1.2:1.0', {'bInterfaceNumber': '00',
            'bInterfaceClass': 'ff', 'bInterfaceProtocol': '00',
            'bInterfaceSubClass': 'ff'})
            |__ UsbInterface: (u'4-1.2:1.1', {'bInterfaceNumber': '01',
            'bInterfaceClass': 'ff', 'bInterfaceProtocol': '01',
            'bInterfaceSubClass': '42'})
            |__ Allow: False

        :param device:(UsbDevice) the device to check
        :return:(bool) if allow pass through
        """
        log.debug("policy check: " + device.get_node())
        for i in device.get_all_interfaces():
            allow_interface = False
            for r in self.rule_list:
                if self.match_device_interface(r, device, i):
                    if r[self._ALLOW]:
                        log.debug("allow " + i.get_node())
                        allow_interface = True
                        break
                    else:
                        log.debug("deny " + i.get_node())
                        return False
            if not allow_interface:
                log.debug("deny " + i.get_node() + ", no matching rule")
                return False

        log.debug("allow " + device.get_node())
        return True
Exemplo n.º 12
0
    def access(self, path):
        try:
            logger.debug("Testing "+path)
            self._cleanup()
            url = urllib.unquote(path)

            lst = self.ftp.nlst(os.path.dirname(url))
            return os.path.basename(url) in map(os.path.basename, lst)
        except Exception, e:
            logger.info(str(e))
            return False
Exemplo n.º 13
0
    def access(self, path):
        try:
            logger.debug("Testing " + path)
            self._cleanup()
            url = urllib.unquote(path)

            if self.ftp.size(url) is not None:
                return True
            lst = self.ftp.nlst(os.path.dirname(url))
            return os.path.basename(url) in map(os.path.basename, lst)
        except Exception, e:
            logger.info(str(e))
            return False
Exemplo n.º 14
0
def get_usb_info():
    context, devices, interfaces = pyudev.Context(), [], []

    for d in context.list_devices(subsystem="usb", DEVTYPE="usb_device"):
        device = UsbDevice(d.sys_name, d, d.attributes)
        if device.is_initialized() and not device.is_class_hub():
            devices.append(device)
        else:
            log.debug("ignore usb device:" + str(device))

    for d in context.list_devices(subsystem="usb", DEVTYPE="usb_interface"):
        interface = UsbInterface(d.sys_name, d.attributes)
        if interface.is_initialized() and not interface.is_class_hub():
            interfaces.append(interface)
        else:
            log.debug("ignore usb interface:" + str(interface))

    return devices, interfaces
Exemplo n.º 15
0
    def __init__(self):
        """ parse policy file, generate rule list

        Note: hubs are never allowed to pass through
        """
        self.rule_list = []
        try:
            with open(self._PATH, "r") as f:
                log.debug("=== policy file begin")
                for line in f:
                    log.debug(line[0:-1])
                    self.parse_line(line)
                log.debug("=== policy file end")
        except IOError as e:
            # without policy file, no device will be allowed to passed through
            log_exit("Caught error {}, policy file error".format(str(e)))

        log.debug("=== rule list begin")
        log_list(self.rule_list)
        log.debug("=== rule list end")
Exemplo n.º 16
0
    def start(self):
        if self.start_count == 0:
            self.ftp = ftplib.FTP()
            #self.ftp.set_debuglevel(1)
            port = ftplib.FTP_PORT
            if self.url_parts.port:
                port = self.url_parts.port
            self.ftp.connect(self.url_parts.hostname, port)
            username = self.url_parts.username
            password = self.url_parts.password
            if username:
                username = urllib.unquote(username)
            if password:
                password = urllib.unquote(password)
            self.ftp.login(username, password)

            directory = urllib.unquote(self.url_parts.path[1:])
            if directory != '':
                logger.debug("Changing to " + directory)
                self.ftp.cwd(directory)

        self.start_count += 1
Exemplo n.º 17
0
    def start(self):
        if self.start_count == 0:
            self.ftp = ftplib.FTP()
            #self.ftp.set_debuglevel(1)
            port = ftplib.FTP_PORT
            if self.url_parts.port:
                port = self.url_parts.port
            self.ftp.connect(self.url_parts.hostname, port)
            username = self.url_parts.username
            password = self.url_parts.password
            if username:
                username = urllib.unquote(username)
            if password:
                password = urllib.unquote(password)
            self.ftp.login(username, password)

            directory = urllib.unquote(self.url_parts.path[1:])
            if directory != '':
                logger.debug("Changing to " + directory)
                self.ftp.cwd(directory)

        self.start_count += 1
Exemplo n.º 18
0
    def match_device_interface(self, rule, device, interface):
        """check if a rule can match a device and one of its interface
        for device, check its vid, pid, rel
        for interface, check its class, subclass, prot

        :param rule: (dict) the rule to match
        :param device:(UsbDevice) the device to check
        :param interface:(UsbInterface) the interface to check
        :return:(bool) if they match
        """
        for k in [k for k in rule if k in self._KEY_MAP_DEVICE]:
            log.debug("check {} props[{}] against {}".format(
                interface.get_node(), k, str(rule)))
            if not hex_equal(rule[k], device[self._KEY_MAP_DEVICE[k]]):
                return False

        for k in [k for k in rule if k in self._KEY_MAP_INTERFACE]:
            log.debug("check {} props[{}] against {}".format(
                interface.get_node(), k, str(rule)))
            if not hex_equal(rule[k], interface[self._KEY_MAP_INTERFACE[k]]):
                return False

        log.debug("found matching rule: " + str(rule))
        return True
Exemplo n.º 19
0
def read_int(path):
    with open(path) as f:
        return int(f.readline())


def reset_device(bus, dev):
    with open("/dev/bus/usb/{0:03d}/{1:03d}".format(bus, dev), "w") as f:
        fcntl.ioctl(f.fileno(), USBDEVFS_RESET, 0)


if __name__ == "__main__":
    log.logToSyslog(level=logging.DEBUG)

    if len(sys.argv) != 2:
        sys.exit("usage: {} device_node".format(sys.argv[0]))

    device = sys.argv[1]
    pattern = re.compile(r"^\d+-\d+(\.\d+)*$")
    if pattern.match(device) is None:
        log.debug("unexpected device node: {}".format(device))
        exit(1)

    try:
        bus = read_int("/sys/bus/usb/devices/{}/busnum".format(device))
        dev = read_int("/sys/bus/usb/devices/{}/devnum".format(device))
        reset_device(bus, dev)
    except (IOError, ValueError):
        log.debug(traceback.format_exc())
        exit(1)
Exemplo n.º 20
0
def log_list(l):
    for s in l:
        log.debug(s)
Exemplo n.º 21
0
                      (eth.get("Kernel name", "Unknown"), ))

        try:
            current_state.append(
                MACPCI(eth["Assigned MAC"],
                       eth["Bus Info"],
                       kname=eth["Kernel name"],
                       order=int(eth["BIOS device"]["all_ethN"][3:]),
                       ppn=eth["BIOS device"]["physical"],
                       label=eth.get("SMBIOS Label", "")))
        except Exception, e:
            LOG.error("Can't generate current state for interface '%s' - "
                      "%s" % (eth, e))
    current_state.sort()

    LOG.debug("Current state = %s" % (niceformat(current_state), ))

    static_rules.generate(current_state)
    dynamic_rules.generate(current_state)

    static_eths = [x.tname for x in static_rules.rules]
    last_boot = [x for x in dynamic_rules.rules if x.tname not in static_eths]

    LOG.debug("StaticRules Formulae = %s" %
              (niceformat(static_rules.formulae), ))
    LOG.debug("StaticRules Rules = %s" % (niceformat(static_rules.rules), ))
    LOG.debug("DynamicRules Lastboot = %s" % (niceformat(last_boot), ))

    # Invoke the renaming logic
    try:
        transactions = rename(static_rules=static_rules.rules,
Exemplo n.º 22
0
    def writeFile(self, in_fh, out_name):
        self._cleanup()
        fname = urllib.unquote(out_name)

        logger.debug("Storing as " + fname)
        self.ftp.storbinary('STOR ' + fname, in_fh)
Exemplo n.º 23
0
def remap_netdevs(remap_list):

    # # rename everything sideways to safe faffing with temp renanes
    # for x in ( x for x in os.listdir("/sys/class/net/") if x[:3] == "eth" ):
    #     util.runCmd2(['ip', 'link', 'set', x, 'name', 'side-'+x])

    for cmd in remap_list:
        parse_arg(cmd)

        # Grab the current state from biosdevname
    current_eths = all_devices_all_names()
    current_state = []

    for nic in current_eths:
        eth = current_eths[nic]

        if not ("BIOS device" in eth and "Kernel name" in eth
                and "Assigned MAC" in eth and "Bus Info" in eth and "all_ethN"
                in eth["BIOS device"] and "physical" in eth["BIOS device"]):
            LOG.error("Interface information for '%s' from biosdevname is "
                      "incomplete; Discarding." %
                      (eth.get("Kernel name", "Unknown"), ))

        try:
            current_state.append(
                MACPCI(eth["Assigned MAC"],
                       eth["Bus Info"],
                       kname=eth["Kernel name"],
                       order=int(eth["BIOS device"]["all_ethN"][3:]),
                       ppn=eth["BIOS device"]["physical"],
                       label=eth.get("SMBIOS Label", "")))
        except Exception as e:
            LOG.error("Can't generate current state for interface '%s' - "
                      "%s" % (eth, e))
    current_state.sort()

    LOG.debug("Current state = %s" % (niceformat(current_state), ))

    static_rules.generate(current_state)
    dynamic_rules.generate(current_state)

    static_eths = [x.tname for x in static_rules.rules]
    last_boot = [x for x in dynamic_rules.rules if x.tname not in static_eths]

    LOG.debug("StaticRules Formulae = %s" %
              (niceformat(static_rules.formulae), ))
    LOG.debug("StaticRules Rules = %s" % (niceformat(static_rules.rules), ))
    LOG.debug("DynamicRules Lastboot = %s" % (niceformat(last_boot), ))

    # Invoke the renaming logic
    try:
        transactions = rename(static_rules=static_rules.rules,
                              cur_state=current_state,
                              last_state=last_boot,
                              old_state=[])
    except Exception as e:
        LOG.critical("Problem from rename logic: %s.  Giving up" % (e, ))
        return

    # Apply transactions, or explicitly state that there are none
    if len(transactions):
        for src, dst in transactions:
            ip_link_set_name(src, dst)
    else:
        LOG.info("No transactions.  No need to rename any nics")

    # Regenerate dynamic configuration
    def macpci_as_list(x):
        return [str(x.mac), str(x.pci), x.tname]

    new_lastboot = map(macpci_as_list, current_state)
    dynamic_rules.lastboot = new_lastboot

    LOG.info("All done ordering the network devices")
Exemplo n.º 24
0
    def writeFile(self, in_fh, out_name):
        self._cleanup()
        fname = urllib.unquote(out_name)

        logger.debug("Storing as " + fname)
        self.ftp.storbinary('STOR ' + fname, in_fh)