def do_task(param, data_center):
    """
    do task
    """

    logger = GracLog.get_logger()
    try:
        mode = param[0]
        authorized_path = search_file_reversely('/sys/' + param[1],
                                                'authorized',
                                                REVERSE_LOOKUP_LIMIT)
        with open(authorized_path, 'w') as f:
            f.write('0')
            logger.info('mode has changed to {}'.format(mode))
            logger.debug('***** DVD MODULE disallow {}'.format(param[1]))
            logmsg, notimsg, grmcode = \
                make_media_msg(JSON_RULE_CD_DVD, mode)
            red_alert2(logmsg, notimsg, JLEVEL_DEFAULT_NOTI, grmcode,
                       data_center)
            write_event_log(
                SOMANSA,
                datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'),
                JSON_RULE_CD_DVD, SOMANSA_STATE_DISALLOW, 'null', 'null',
                'null', 'null')
    except:
        e = grac_format_exc()
        logger.error(e)

    return GRAC_OK
Ejemplo n.º 2
0
def remount_thread(devnode, mode, data_center):
    """
    remount
    """

    logger = GracLog.get_logger()

    for i in range(600):  #1 mins
        partis = psutil.disk_partitions()
        for parti in partis:
            if parti.device == devnode:
                remount_readonly(parti.device, parti.mountpoint)
                logger.info('{} mode has changed'.format(devnode))
                logmsg, notimsg, grmcode = \
                    make_media_msg(JSON_RULE_USB_MEMORY, mode)
                red_alert2(logmsg, notimsg, JLEVEL_DEFAULT_NOTI, grmcode,
                           data_center)
                write_event_log(
                    SOMANSA,
                    datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'),
                    JSON_RULE_USB_MEMORY, SOMANSA_STATE_READONLY, 'null',
                    'null', 'null', 'null')
                return
        time.sleep(0.1)
    logger.error('{} fail to change mode'.format(devnode))
Ejemplo n.º 3
0
    def sync_usb_memory(cls, state, data_center):
        """
        synchronize usb-memory
        """

        block_base_path = '/sys/class/block/*'
        block_node_regex = re.compile('^[a-zA-Z]+$')
        block_usb_regex = re.compile('/usb[0-9]*/')

        #block devices
        for block_device in glob.glob(block_base_path):
            device_node = block_device.split('/')[-1]
            if not block_node_regex.match(device_node):
                continue

            #/sys/devices
            device_sys_path = block_device + '/device'
            if not os.path.exists(device_sys_path):
                continue

            device_real_path = os.path.realpath(device_sys_path)

            #usb device
            if block_usb_regex.search(device_real_path):
                #whitelist
                serial_path = search_file_reversely(device_real_path, 'serial',
                                                    REVERSE_LOOKUP_LIMIT)
                if serial_path:
                    with open(serial_path) as f:
                        serial = f.read().strip('\n')
                    for s in data_center.get_usb_memory_whitelist():
                        if s == serial:
                            cls._logger.info(
                                'SYNC serial({}) is in whitelist'.format(
                                    serial))
                            return

                #authorized
                authorized = search_file_reversely(device_real_path,
                                                   'authorized',
                                                   REVERSE_LOOKUP_LIMIT)
                if not authorized:
                    cls._logger.error('{} not found authorized'.block_device)
                    return

                with open(authorized, 'w') as f:
                    f.write('0')
                    cls._logger.info(
                        'SYNC state={} authorized=0'.format(state))
                    logmsg, notimsg, grmcode = \
                        make_media_msg(JSON_RULE_USB_MEMORY, state)
                    red_alert2(logmsg, notimsg, JLEVEL_DEFAULT_NOTI, grmcode,
                               data_center)
                    write_event_log(
                        SOMANSA,
                        datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'),
                        JSON_RULE_USB_MEMORY, SOMANSA_STATE_DISALLOW, 'null',
                        'null', 'null', 'null')
                    cls._logger.debug(
                        '***** USB disallow {}'.format(block_device))
Ejemplo n.º 4
0
    def sync_wireless(cls, state, data_center):
        """
        synchronize wireless
        """

        wl_base_path = '/sys/class/net'
        wl_inner_regex = re.compile('wireless')

        for wl in glob.glob(wl_base_path + '/*'):
            wl_node = wl.split('/')[-1]

            for wl_inner in glob.glob(wl + '/*'):
                file_name = wl_inner.split('/')[-1]
                if wl_inner_regex.match(file_name):
                    wl_inner_real_path = os.path.realpath(wl_inner + '/device')
                    remove = search_file_reversely(wl_inner_real_path,
                                                   'remove',
                                                   REVERSE_LOOKUP_LIMIT)
                    if not remove:
                        cls._logger.error(
                            '{} not found remove'.format(wl_inner))
                        continue

                    with open(remove, 'w') as f:
                        f.write('1')

                    if os.path.exists(remove):
                        remove_second = '/'.join(
                            remove.split('/')[:-2]) + '/remove'
                        if not os.path.exists(remove_second):
                            logger.error('wireless=>FAIL TO REMOVE 1')
                            continue
                        else:
                            with open(remove_second, 'w') as sf:
                                sf.write('1')

                    if os.path.exists(remove):
                        logger.error('wireless=>FAIL TO REMOVE 2')
                        continue

                    with open(META_FILE_PCI_RESCAN, 'a') as f:
                        f.write('wireless=>{}'.format(remove))
                    cls._logger.info('SYNC state={} remove=1'.format(state))
                    logmsg, notimsg, grmcode = \
                        make_media_msg(JSON_RULE_WIRELESS, state)
                    red_alert2(logmsg, notimsg, JLEVEL_DEFAULT_NOTI, grmcode,
                               data_center)
                    write_event_log(
                        SOMANSA,
                        datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'),
                        JSON_RULE_WIRELESS, SOMANSA_STATE_DISALLOW, 'null',
                        'null', 'null', 'null')
Ejemplo n.º 5
0
    def sync_cd_dvd(cls, state, data_center):
        """
        synchronize cd_dvd
        """

        block_base_path = '/sys/class/block/*'
        block_node_regex = re.compile('^sr[0-9]+$')
        block_usb_regex = re.compile('/usb[0-9]*/')

        #block devices
        for block_device in glob.glob(block_base_path):
            device_node = block_device.split('/')[-1]
            if not block_node_regex.match(device_node):
                continue

            #/sys/devices
            device_sys_path = block_device + '/device'
            if not os.path.exists(device_sys_path):
                continue

            device_real_path = os.path.realpath(device_sys_path)

            #usb device
            if block_usb_regex.search(device_real_path):
                authorized = search_file_reversely(device_real_path,
                                                   'authorized',
                                                   REVERSE_LOOKUP_LIMIT)
                if not authorized:
                    cls._logger.error(
                        '{} not found authorized'.format(device_node))
                    continue

                with open(authorized, 'w') as f:
                    f.write('0')
                    cls._logger.info(
                        'SYNC state={} authorized=0'.format(state))
                    logmsg, notimsg, grmcode = \
                        make_media_msg(JSON_RULE_CD_DVD, state)
                    red_alert2(logmsg, notimsg, JLEVEL_DEFAULT_NOTI, grmcode,
                               data_center)
                    write_event_log(
                        SOMANSA,
                        datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'),
                        JSON_RULE_CD_DVD, SOMANSA_STATE_DISALLOW, 'null',
                        'null', 'null', 'null')
                    cls._logger.debug(
                        '***** DVD disallow {}'.format(block_device))
Ejemplo n.º 6
0
    def sync_bluetooth(cls, state, data_center):
        """
        synchronize bluetooth
        """

        mac_regex = re.compile(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})')

        if not bluetooth_exists():
            cls._logger.error('bluetooth controller not found')
            return

        for controller in glob.glob('/var/lib/bluetooth/*'):
            for mac in glob.glob(controller + '/*'):
                mac = mac.split('/')[-1].upper()
                if not mac_regex.match(mac):
                    continue

                for wl in data_center.get_bluetooth_whitelist():
                    if wl.upper() == mac:
                        break
                else:
                    if not GracSynchronizer.bluetooth_dev_is_connected(mac):
                        continue

                    p1 = subprocess.Popen(
                        ['echo', '-e', 'disconnect {}\nquit'.format(mac)],
                        stdout=subprocess.PIPE)
                    p2 = subprocess.Popen(['bluetoothctl'],
                                          stdin=p1.stdout,
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE)
                    p1.stdout.close()
                    cls._logger.info(
                        'disconnecting controller-mac={} device-mac={}'.format(
                            controller, mac))
                    cls._logger.info(p2.communicate()[0].decode('utf8'))
                    logmsg, notimsg, grmcode = \
                        make_media_msg(JSON_RULE_BLUETOOTH, state)
                    red_alert2(logmsg, notimsg, JLEVEL_DEFAULT_NOTI, grmcode,
                               data_center)
                    write_event_log(
                        SOMANSA,
                        datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'),
                        JSON_RULE_BLUETOOTH, SOMANSA_STATE_DISALLOW, 'null',
                        'null', 'null', 'null')

        cls._logger.info('SYNC state={}'.format(state))
Ejemplo n.º 7
0
def do_task(param, data_center):
    """
    do task
    """

    logger = GracLog.get_logger()
    try:
        mode = param[0]
        remove_path = search_file_reversely('/sys/' + param[1], 'remove',
                                            REVERSE_LOOKUP_LIMIT)
        #v2.0
        if not os.path.exists(remove_path):
            logger.error('(wireless) REMOVE NOT FOUND')
            return

        with open(remove_path, 'w') as f:
            f.write('1')

        if os.path.exists(remove_path):
            remove_second = '/'.join(remove_path.split('/')[:-2]) + '/remove'
            if not os.path.exists(remove_second):
                logger.error('(wireless) FAIL TO REMOVE 1')
                return
            else:
                with open(remove_second, 'w') as sf:
                    sf.write('1')

        if os.path.exists(remove_path):
            logger.error('(wireless) FAIL TO REMOVE 2')
            return

        with open(META_FILE_PCI_RESCAN, 'a') as f2:
            f2.write('wireless=>{}'.format(remove_path))
        logger.info('mode has changed to {}'.format(mode))
        logmsg, notimsg, grmcode = \
            make_media_msg(JSON_RULE_WIRELESS, mode)
        red_alert2(logmsg, notimsg, JLEVEL_DEFAULT_NOTI, grmcode, data_center)
        write_event_log(SOMANSA,
                        datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'),
                        JSON_RULE_WIRELESS, SOMANSA_STATE_DISALLOW, 'null',
                        'null', 'null', 'null')
    except:
        e = grac_format_exc()
        logger.error(e)

    return GRAC_OK
Ejemplo n.º 8
0
def do_task(param, data_center):
    """
    do task
    """

    logger = GracLog.get_logger()
    try:
        mode = param[0]
        serial = param[2].strip() if param[2] else ''

        #whitelist
        if serial:  #param[2]:
            #serial = param[2].strip('\n')
            for s in data_center.get_usb_memory_whitelist():
                if s == serial:
                    logger.info('serial({}) is in whitelist'.format(serial))

                    #usb whitelist register signal
                    signal_msg = ['except', '103', 'already in whitelist']
                    data_center.GRAC.media_usb_info(','.join(signal_msg))
                    return GRAC_OK

            #usb whitelist register signal
            product = param[3].strip() if param[3] else ''
            vendor = param[4].strip() if param[4] else ''
            model = param[5].strip() if param[5] else ''

            user_id, _ = catch_user_id()

            if not user_id or user_id[0] == '-':
                signal_msg = ['except', '101', 'not login']
            if user_id[0] == '+':
                signal_msg = ['except', '102', 'local user not supported']
            else:
                signal_msg = [
                    'normal', user_id, serial, '', product, '', vendor, model
                ]
            data_center.GRAC.media_usb_info(','.join(signal_msg))
        else:
            signal_msg = ['except', '104', 'serial not found']
            data_center.GRAC.media_usb_info(','.join(signal_msg))

        if mode == JSON_RULE_DISALLOW:
            devpath = param[1]
            authorized_path = search_file_reversely('/sys/' + devpath,
                                                    'authorized',
                                                    REVERSE_LOOKUP_LIMIT)

            with open(authorized_path, 'w') as f:
                f.write('0')
                logger.info('mode has changed to {}'.format(mode))
                logmsg, notimsg, grmcode = \
                    make_media_msg(JSON_RULE_USB_MEMORY, mode)
                red_alert2(logmsg, notimsg, JLEVEL_DEFAULT_NOTI, grmcode,
                           data_center)
                write_event_log(
                    SOMANSA,
                    datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'),
                    JSON_RULE_USB_MEMORY, SOMANSA_STATE_DISALLOW, 'null',
                    'null', 'null', 'null')
                logger.debug('***** USB MODULE disallow {}'.format(param[1]))

        elif mode == JSON_RULE_READONLY:
            devnode = '/dev/' + param[1]
            thr = threading.Thread(target=remount_thread,
                                   args=(devnode, mode, data_center))
            thr.daemon = True
            thr.start()
            logger.info('{} mode is changing to {}'.format(devnode, mode))
            logger.debug('***** USB MODULE read_only {}'.format(param[1]))
    except:
        e = grac_format_exc()
        GracLog.get_logger().error(e)
        logger.error(e)

    return GRAC_OK
Ejemplo n.º 9
0
    def sync_usb_memory_readonly(cls, state, data_center):
        """
        synchronize usb-memory readonly
        """

        block_base_path = '/sys/class/block/*'
        block_node_regex = re.compile('^[a-zA-Z]+$')
        block_usb_regex = re.compile('/usb[0-9]*/')

        #block devices
        for block_device in glob.glob(block_base_path):
            device_node = block_device.split('/')[-1]
            if not block_node_regex.match(device_node):
                continue

            #/sys/devices
            device_sys_path = block_device + '/device'
            if not os.path.exists(device_sys_path):
                continue

            device_real_path = os.path.realpath(device_sys_path)

            #usb device
            if block_usb_regex.search(device_real_path):
                #whitelist
                serial_path = search_file_reversely(device_real_path, 'serial',
                                                    REVERSE_LOOKUP_LIMIT)
                if serial_path:
                    with open(serial_path) as f:
                        serial = f.read().strip('\n')
                    for s in data_center.get_usb_memory_whitelist():
                        if s == serial:
                            cls._logger.info(
                                'SYNC serial({}) is in whitelist'.format(
                                    serial))
                            return

                skeep_uuid = False
                for usb_label_path in ('/dev/disk/by-label/*',
                                       '/dev/disk/by-uuid/*'):
                    for usb_label in glob.glob(usb_label_path):
                        if usb_label.lower().endswith('efi'):
                            continue
                        usb_label_realpath = os.path.realpath(usb_label)
                        usb_label_node = re.split(
                            '[0-9]+',
                            usb_label_realpath.split('/')[-1])[0]
                        if usb_label_node == device_node:
                            mount_point = '/media/gooroom/' + usb_label.split(
                                '/')[-1]
                            umount_mount_readonly(usb_label_realpath,
                                                  mount_point)
                            cls._logger.info('SYNC state={} {} remounted '\
                                'as readonly'.format(state, usb_label_realpath))
                            cls._logger.debug(
                                '***** USB read_only {} {}'.format(
                                    usb_label_realpath, mount_point))
                            logmsg, notimsg, grmcode = \
                                make_media_msg(JSON_RULE_USB_MEMORY, state)
                            red_alert2(logmsg, notimsg, JLEVEL_DEFAULT_NOTI,
                                       grmcode, data_center)
                            write_event_log(
                                SOMANSA,
                                datetime.datetime.now().strftime(
                                    '%Y%m%d %H:%M:%S'), JSON_RULE_USB_MEMORY,
                                SOMANSA_STATE_READONLY, 'null', 'null', 'null',
                                'null')
                            skeep_uuid = True
                            break
                    if skeep_uuid:
                        break
def do_task(param, data_center):
    """
    do task
    """

    logger = GracLog.get_logger()

    if not bluetooth_exists():
        logger.error('bluetooth controller not found')
        return GRAC_OK

    try:
        mode = param[0]
        unique = param[1].strip() if param[1] else param[1]
        name = param[2].strip() if param[2] else param[2]
        mac = ''
        if unique:
            mac = unique
        elif name:
            name = name.upper()
            delim_cnt = 0
            num_cnt = 0
            for n in name:
                if n == '.' or n == ':':
                    delim_cnt += 1
                    continue
                if ord(n) >= ord('0') and ord(n) <= ord('9'):
                    num_cnt += 1
                    continue
                if ord(n) >= ord('A') and ord(n) <= ord('F'):
                    num_cnt += 1
                    continue
                break
            else:
                if (delim_cnt == 0 or delim_cnt == 5) and num_cnt == 12:
                    mac = name
        if not mac:
            raise Exception('!! bluetooth mac not found')

        mac = mac.replace('.', ':').strip('\n').upper()
        for m in data_center.get_bluetooth_whitelist():
            if m.upper() == mac:
                logger.info('mac({}) is in whitelist'.format(mac))
                return GRAC_OK

        p1 = subprocess.Popen(
            ['echo', '-e', 'disconnect {}\nquit'.format(mac)],
            stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['bluetoothctl'],
                              stdin=p1.stdout,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)
        p1.stdout.close()
        logger.info(p2.communicate()[0].decode('utf8'))
        logmsg, notimsg, grmcode = \
            make_media_msg(JSON_RULE_BLUETOOTH, mode)
        red_alert2(logmsg, notimsg, JLEVEL_DEFAULT_NOTI, grmcode, data_center)
        write_event_log(SOMANSA,
                        datetime.datetime.now().strftime('%Y%m%d %H:%M:%S'),
                        JSON_RULE_BLUETOOTH, SOMANSA_STATE_DISALLOW, 'null',
                        'null', 'null', 'null')
    except:
        e = grac_format_exc()
        logger.error(e)

    return GRAC_OK