Beispiel #1
0
	def search_ids(vid, pid, *, offline=True):
		if offline:
			print_warning('Offline mode')

		try:
			usb_ids = USBIDs.prepare_database(offline=offline)
		except USBRipError as e:
			print_critical(str(e), errcode=e.errors['errcode'], initial_error=e.errors['initial_error'])
		else:
			_search_ids_helper(usb_ids, vid, pid)
			usb_ids.close()
Beispiel #2
0
    def open_storage(storage_type,
                     password,
                     columns,
                     *,
                     sieve=None,
                     repres=None):
        storage_full_path = '{}/{}.7z'.format(USBStorage._STORAGE_BASE,
                                              storage_type)
        if not os.path.isfile(storage_full_path):
            print_critical(
                'Storage not found: \'{}\''.format(storage_full_path))
            return

        try:
            out = _7zip_unpack(storage_full_path, password)
        except USBRipError as e:
            print_critical(str(e),
                           errcode=e.errors['errcode'],
                           initial_error=e.errors['initial_error'])
            return

        if 'Everything is Ok' in out:
            base_filename = re.search(r'Extracting\s*(.*?$)', out,
                                      re.MULTILINE).group(1)
            json_file = '{}/{}'.format(USBStorage._STORAGE_BASE, base_filename)
            USBEvents.open_dump(json_file, columns, sieve=sieve, repres=repres)
            os.remove(json_file)
        else:
            print_critical('Undefined behaviour while unpacking storage',
                           initial_error=out)
Beispiel #3
0
    def change_password(storage_type,
                        old_password,
                        new_password,
                        *,
                        compression_level='5'):
        storage_full_path = '{}/{}.7z'.format(USBStorage._STORAGE_BASE,
                                              storage_type)
        if not os.path.isfile(storage_full_path):
            print_critical(
                'Storage not found: \'{}\''.format(storage_full_path))
            return

        try:
            out = _7zip_unpack(storage_full_path, old_password)
            if 'Everything is Ok' in out:
                os.remove(storage_full_path)

                base_filename = re.search(r'Extracting\s*(.*?$)', out,
                                          re.MULTILINE).group(1)
                json_file = '{}/{}'.format(USBStorage._STORAGE_BASE,
                                           base_filename)

                out = _7zip_pack(storage_full_path, json_file, new_password,
                                 compression_level)
                if 'Everything is Ok' in out:
                    print_info('Password was successfully changed')
                else:
                    print_critical(
                        'Undefined behaviour while creating storage',
                        initial_error=out)

                os.remove(json_file)

            else:
                print_critical('Undefined behaviour while unpacking storage',
                               initial_error=out)

        except USBRipError as e:
            print_critical(str(e),
                           errcode=e.errors['errcode'],
                           initial_error=e.errors['initial_error'])
            return
Beispiel #4
0
    def list_storage(storage_type, password):
        storage_full_path = '{}/{}.7z'.format(USBStorage._STORAGE_BASE,
                                              storage_type)
        if not os.path.isfile(storage_full_path):
            print_critical(
                'Storage not found: \'{}\''.format(storage_full_path))
            return

        try:
            out = _7zip_list(storage_full_path, password)
        except USBRipError as e:
            print_critical(str(e),
                           errcode=e.errors['errcode'],
                           initial_error=e.errors['initial_error'])
            return

        if '--' in out:
            print(out[out.index('--'):] + '--')
        else:
            print_critical(
                'Undefined behaviour while listing storage contents',
                initial_error=out)
Beispiel #5
0
def main():
    if not len(sys.argv) > 1:
        print(BANNER + '\n')
        usbrip_arg_error()

    parser = cmd_line_options()
    args = parser.parse_args()

    if 'quiet' in args and not args.quiet:
        print(BANNER + '\n')
    else:
        cfg.QUIET = True

    # ----------------------------------------------------------
    # ------------------------- Banner -------------------------
    # ----------------------------------------------------------

    if args.subparser == 'banner':
        print(BANNER)

    # ----------------------------------------------------------
    # ----------------------- USB Events -----------------------
    # ----------------------------------------------------------

    elif args.subparser == 'events' and args.ue_subparser:
        sieve, repres = validate_ue_args(args)

        # ------------------- USB Events History -------------------

        if args.ue_subparser == 'history':
            timing.begin()
            ueh = USBEvents(args.file)
            if ueh:
                ueh.event_history(args.column, sieve=sieve, repres=repres)

        # -------------------- USB Events Open ---------------------

        elif args.ue_subparser == 'open':
            timing.begin()
            USBEvents.open_dump(args.input,
                                args.column,
                                sieve=sieve,
                                repres=repres)

        # ------------------ USB Events Gen Auth -------------------

        elif args.ue_subparser == 'gen_auth':
            timing.begin()
            ueg = USBEvents(args.file)
            if ueg:
                if ueg.generate_auth_json(args.output,
                                          args.attribute,
                                          sieve=sieve):
                    usbrip_internal_error()
            else:
                usbrip_internal_error()

        # ----------------- USB Events Violations ------------------

        elif args.ue_subparser == 'violations':
            timing.begin()
            uev = USBEvents(args.file)
            if uev:
                uev.search_violations(args.input,
                                      args.attribute,
                                      args.column,
                                      sieve=sieve,
                                      repres=repres)

    # ----------------------------------------------------------
    # ---------------------- USB Storage -----------------------
    # ----------------------------------------------------------

    elif args.subparser == 'storage' and args.us_subparser:
        if os.geteuid() != 0:
            sys.exit('Permission denied. Retry with sudo')

        sieve, repres = validate_us_args(args)
        timing.begin()
        us = USBStorage()

        # -------------------- USB Storage List --------------------

        if args.us_subparser == 'list':
            us.list_storage(args.storage_type, args.password)

        # -------------------- USB Storage Open --------------------

        elif args.us_subparser == 'open':
            us.open_storage(args.storage_type,
                            args.password,
                            args.column,
                            sieve=sieve,
                            repres=repres)

        # ------------------- USB Storage Update -------------------

        elif args.us_subparser == 'update':
            if us.update_storage(args.storage_type,
                                 args.password,
                                 input_auth=args.input,
                                 attributes=args.attribute,
                                 compression_level=args.lvl,
                                 sieve=sieve):
                usbrip_internal_error()

        # ------------------- USB Storage Create -------------------

        elif args.us_subparser == 'create':
            if us.create_storage(args.storage_type,
                                 password=args.password,
                                 input_auth=args.input,
                                 attributes=args.attribute,
                                 compression_level=args.lvl,
                                 sieve=sieve):
                usbrip_internal_error()

        # ------------------- USB Storage Passwd -------------------

        elif args.us_subparser == 'passwd':
            us.change_password(args.storage_type,
                               args.old,
                               args.new,
                               compression_level=args.lvl)

    # ----------------------------------------------------------
    # ------------------------ USB IDs -------------------------
    # ----------------------------------------------------------

    elif args.subparser == 'ids' and args.ui_subparser:
        validate_ui_args(args)
        timing.begin()
        ui = USBIDs()

        # --------------------- USB IDs Search ---------------------

        if args.ui_subparser == 'search':
            ui.search_ids(args.vid, args.pid, offline=args.offline)

        # -------------------- USB IDs Download --------------------

        elif args.ui_subparser == 'download':
            try:
                usb_ids = ui.prepare_database(offline=False)
            except USBRipError as e:
                print_critical(str(e),
                               errcode=e.errors['errcode'],
                               initial_error=e.errors['initial_error'])
            else:
                usb_ids.close()

    else:
        subparser = ' ' + args.subparser + ' '
        usbrip_arg_error('Choose one of the usbrip {} actions'.format(
            args.subparser),
                         subparser=subparser)
Beispiel #6
0
    def create_storage(storage_type,
                       *,
                       password=None,
                       input_auth=None,
                       attributes=None,
                       compression_level='5',
                       indent=4,
                       sieve=None):
        if storage_type == 'history':
            events_to_show = _get_history_events(sieve)
        elif storage_type == 'violations':
            try:
                events_to_show = _get_violation_events(sieve, input_auth,
                                                       attributes, indent)
            except USBRipError as e:
                print_critical(str(e), initial_error=e.errors['initial_error'])
                return 1

        if events_to_show is None:
            return 1

        if events_to_show:
            min_date, max_date = _get_dates(events_to_show)
            json_file = '{}/{}-{}.json'.format(USBStorage._STORAGE_BASE,
                                               min_date, max_date)
        else:
            json_file = '{}/{}.json'.format(USBStorage._STORAGE_BASE,
                                            datetime.now().strftime('%m%d'))

        try:
            _dump_events(events_to_show, storage_type, json_file, indent)
        except USBRipError as e:
            print_critical(str(e), initial_error=e.errors['initial_error'])
            return 1

        if password is None:
            print_warning('No password provided, generating random one')
            password = _gen_random_password(12)

        storage_full_path = '{}/{}.7z'.format(USBStorage._STORAGE_BASE,
                                              storage_type)
        if os.path.exists(storage_full_path):
            os.remove(storage_full_path)

        try:
            out = _7zip_pack(storage_full_path, json_file, password,
                             compression_level)
        except USBRipError as e:
            os.remove(json_file)
            print_critical(str(e),
                           errcode=e.errors['errcode'],
                           initial_error=e.errors['initial_error'])
            return 1

        if 'Everything is Ok' in out:
            print_info('New {} storage: \'{}\''.format(storage_type,
                                                       storage_full_path))
            print_secret('Your password is', secret=password)
            os.remove(json_file)
        else:
            print_critical('Undefined behaviour while creating storage',
                           initial_error=out)
Beispiel #7
0
    def update_storage(storage_type,
                       password=None,
                       *,
                       input_auth=None,
                       attributes=None,
                       compression_level='5',
                       indent=4,
                       sieve=None):
        if storage_type == 'history':
            events_to_show = _get_history_events(sieve)
        elif storage_type == 'violations':
            try:
                events_to_show = _get_violation_events(sieve, input_auth,
                                                       attributes, indent)
            except USBRipError as e:
                print_critical(str(e), initial_error=e.errors['initial_error'])
                return 1

        if events_to_show is None:
            return 1

        if events_to_show:
            min_date, max_date = _get_dates(events_to_show)
        else:
            print_info('No events to append')
            return 1

        storage_full_path = '{}/{}.7z'.format(USBStorage._STORAGE_BASE,
                                              storage_type)
        if not os.path.isfile(storage_full_path):
            print_critical(
                'Storage not found: \'{}\''.format(storage_full_path))
            return 1

        print_info('Updating storage: \'{}\''.format(storage_full_path))

        try:
            out = _7zip_unpack(storage_full_path, password)
        except USBRipError as e:
            print_critical(str(e),
                           errcode=e.errors['errcode'],
                           initial_error=e.errors['initial_error'])
            return 1

        if 'Everything is Ok' in out:
            os.remove(storage_full_path)
            base_filename = re.search(r'Extracting\s*(.*?$)', out,
                                      re.MULTILINE).group(1)
            json_file = '{}/{}'.format(USBStorage._STORAGE_BASE, base_filename)

            with open(json_file, 'r', encoding='utf-8') as dump:
                events_dumped = json.load(dump)
            os.remove(json_file)

            merged_events = _merge_json_events(events_dumped, events_to_show)

            if len(base_filename) > 9:  # len('mmdd.json') == 9
                min_date = base_filename[:4]

            new_json_file = '{}/{}-{}.json'.format(USBStorage._STORAGE_BASE,
                                                   min_date, max_date)
            _dump_events(merged_events, storage_type, new_json_file, indent)

            try:
                out = _7zip_pack(storage_full_path, new_json_file, password,
                                 compression_level)
            except USBRipError as e:
                os.remove(new_json_file)
                print_critical(str(e),
                               errcode=e.errors['errcode'],
                               initial_error=e.errors['initial_error'])
                return 1

            if 'Everything is Ok' in out:
                print_info('Storage was successfully updated')
            else:
                print_critical('Undefined behaviour while creating storage',
                               initial_error=out)

            os.remove(new_json_file)

        else:
            print_critical('Undefined behaviour while unpacking storage',
                           initial_error=out)