Пример #1
0
    def event_history(self, columns, *, indent=4, sieve=None, repres=None):
        self._events_to_show = _filter_events(self._all_events, sieve)
        if not self._events_to_show:
            print_info('No USB events found!')
            return

        if not cfg.QUIET and cfg.ISATTY:
            choice, abs_filename = _output_choice('event history',
                                                  'history.json', 'history/')
            if choice == '2':
                try:
                    _dump_events(self._events_to_show, 'event history',
                                 abs_filename, indent)
                except USBRipError as e:
                    print_critical(str(e),
                                   initial_error=e.errors['initial_error'])
                return

        # elif choice == '1' or choice == '':

        if columns:
            table_data = [[COLUMN_NAMES[name] for name in columns]]
        else:
            columns = [key for key in COLUMN_NAMES.keys()]
            table_data = [[val for val in COLUMN_NAMES.values()]]

        _represent_events(self._events_to_show, columns, table_data,
                          'USB-History-Events', repres)
Пример #2
0
    def __new__(cls, files=None):
        try:
            # child_env = os.environ.copy()
            # child_env['LANG'] = 'en_US.utf-8'
            # journalctl_out = check_output(['journalctl'], env=child_env).decode('utf-8')
            journalctl_out = check_output(
                ['journalctl', '-o', 'short-iso-precise']).decode('utf-8')

            if '-- Logs begin at' in journalctl_out:
                filtered_history = _read_log_file(None,
                                                  log=StringIO(journalctl_out))

            elif files:
                filtered_history = []
                for file in files:
                    filtered_history.extend(_read_log_file(file))

            else:
                filtered_history = _get_filtered_history()

        except USBRipError as e:
            print_critical(str(e), initial_error=e.errors['initial_error'])
            return None

        all_events = _parse_history(filtered_history)

        instance = super().__new__(cls)
        instance._all_events = all_events  # self._all_events
        instance._violations = []  # self._violations
        instance._events_to_show = None  # self._events_to_show
        return instance
Пример #3
0
    def open_dump(input_dump, columns, *, sieve=None, repres=None):
        abs_input_dump = os.path.abspath(input_dump)

        print_info(f'Opening USB event dump: "{abs_input_dump}"')

        try:
            with open(abs_input_dump, 'r', encoding='utf-8') as dump:
                events_dumped = json.load(dump)
        except json.decoder.JSONDecodeError as e:
            print_critical('Failed to decode event dump (JSON)',
                           initial_error=str(e))
            return

        if not events_dumped:
            print_critical('This dump is empty!')
            return

        events_to_show = _filter_events(events_dumped, sieve)
        if not events_to_show:
            print_info('No USB events found!')
            return

        if columns:
            table_data = [[COLUMN_NAMES[name] for name in columns]]
        else:
            columns = [key for key in COLUMN_NAMES.keys()]
            table_data = [[val for val in COLUMN_NAMES.values()]]

        _represent_events(events_to_show, columns, table_data,
                          'USB-Event-Dump', repres)
Пример #4
0
	def generate_auth_json(self, output_auth, attributes, *, indent=4, sieve=None):
		self._events_to_show = _filter_events(self._all_events, sieve)
		if not self._events_to_show:
			print_info('No USB devices found!')

		rand_id = f'usbrip-{randint(1000, 9999)}'
		self._events_to_show += [{
			'conn':     rand_id,
			'host':     rand_id,
			'vid':      rand_id,
			'pid':      rand_id,
			'prod':     rand_id,
			'manufact': rand_id,
			'serial':   rand_id,
			'port':     rand_id,
			'disconn':  rand_id
		}]

		abs_output_auth = os.path.abspath(output_auth)

		try:
			dirname = os.path.dirname(abs_output_auth)
			os_makedirs(dirname)
		except USBRipError as e:
			print_critical(str(e), initial_error=e.errors['initial_error'])
			return 1
		else:
			print_info(f'Created directory "{dirname}/"')

		try:
			auth_json = open(abs_output_auth, 'w', encoding='utf-8')
		except PermissionError as e:
			print_critical(f'Permission denied: "{abs_output_auth}". Retry with sudo', initial_error=str(e))
			return 1

		print_info('Generating authorized device list (JSON)')

		if not attributes:
			attributes = ('vid', 'pid', 'prod', 'manufact', 'serial')

		auth = defaultdict(set)
		for event in tqdm(self._events_to_show, ncols=80, unit='dev'):
			for key, val in event.items():
				if key in attributes and val is not None:
					auth[key].add(val)

		auth = {key: list(vals) for key, vals in auth.items()}

		for key in auth.keys():
			auth[key].sort()

		json.dump(auth, auth_json, sort_keys=True, indent=indent)
		auth_json.close()

		os.chmod(abs_output_auth, stat.S_IRUSR | stat.S_IWUSR)  # 600

		print_info(f'New authorized device list: "{abs_output_auth}"')
Пример #5
0
    def change_password(storage_type, *, compression_level='5'):
        storage_full_path = f'{USBStorage._STORAGE_BASE}/{storage_type}.7z'
        if not os.path.isfile(storage_full_path):
            print_critical(f'Storage not found: "{storage_full_path}"')
            return

        old_password = getpass('Old password: '******'New password: '******'Confirm new password: '******'Passwords does not match, try again')
            return

        try:
            out = _7zip_unpack(storage_full_path, old_password)
            if 'Everything is Ok' in out:
                base_filename = re.search(
                    r'([^\n ]*\.json)',
                    _7zip_list(storage_full_path, old_password),
                    re.MULTILINE).group(1)
                json_file = f'{USBStorage._STORAGE_BASE}/{base_filename}'
                os.remove(storage_full_path)

                out = _7zip_pack(storage_full_path, json_file, new_password,
                                 compression_level)

                if 'Everything is Ok' in out:
                    print_info('Password was successfully changed')

                    conf_parser = ConfigParser(allow_no_value=True)
                    conf_parser.optionxform = str
                    conf_parser.read(CONFIG_FILE, encoding='utf-8')
                    conf_parser.set(storage_type, 'password', new_password)
                    with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
                        conf_parser.write(f)

                    print_info('Configuration file updated')

                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
Пример #6
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()
Пример #7
0
def _output_choice(list_name, default_filename, dirname):
    while True:
        print(
            f'[?] How would you like your {list_name} list to be generated?\n')

        print('    1. JSON-file')
        print('    2. Terminal stdout')

        number = input('\n[>] Please enter the number of your choice: ')

        if number == '1':
            while True:
                filename = input(
                    f'[>] Please enter the base name for the output file '
                    f'(default is "{default_filename}"): ')

                if all(c in printable
                       for c in filename) and len(filename) < 256:
                    if not filename:
                        filename = default_filename
                    elif filename[-5:] != '.json':
                        filename = filename + '.json'

                    filename = root_dir_join(dirname + filename)

                    try:
                        dirname = os.path.dirname(filename)
                        os_makedirs(dirname)
                    except USBRipError as e:
                        print_critical(str(e),
                                       initial_error=e.errors['initial_error'])
                        return (None, '')
                    else:
                        print_info(f'Created "{dirname}"')

                    overwrite = True
                    if os.path.isfile(filename):
                        while True:
                            overwrite = input(
                                '[?] File exists. Would you like to overwrite it? [Y/n]: '
                            )
                            if len(overwrite) == 1 and overwrite in 'Yy':
                                overwrite = True
                                break
                            elif len(overwrite) == 1 and overwrite in 'Nn':
                                overwrite = False
                                break

                    if overwrite:
                        return (int(number), filename)

        elif number == '2':
            return (int(number), '')
Пример #8
0
	def __new__(cls, files=None):
		try:
			if files:
				filtered_history = []
				for file in files:
					filtered_history.extend(_read_log_file(file))

			else:
				print_info('Trying to run journalctl...')

				# child_env = os.environ.copy()
				# child_env['LANG'] = 'en_US.utf-8'
				# journalctl_out = check_output(['journalctl'], env=child_env).decode('utf-8')

				try:
					journalctl_out = check_output([
						'journalctl',
						'-o',
						'short-iso-precise'
					]).decode('utf-8')

				except Exception as e:
					print_warning(f'Failed to run journalctl: {str(e)}')
					filtered_history = _get_filtered_history()

				else:
					if '-- Logs begin at' in journalctl_out:
						print_info('Successfully ran journalctl')

						filtered_history = _read_log_file(
							None,
							log=StringIO(journalctl_out),
							total=journalctl_out.count('\n')
						)

					else:
						print_warning(f'An error occurred when running journalctl: {journalctl_out}')
						filtered_history = _get_filtered_history()

		except USBRipError as e:
			print_critical(str(e), initial_error=e.errors['initial_error'])
			return None

		all_events = _parse_history(filtered_history)

		instance = super().__new__(cls)
		instance._all_events = all_events  # self._all_events
		instance._violations = []          # self._violations
		instance._events_to_show = None    # self._events_to_show
		return instance
Пример #9
0
    def generate_auth_json(self,
                           output_auth,
                           attributes,
                           *,
                           indent=4,
                           sieve=None):
        self._events_to_show = _filter_events(self._all_events, sieve)
        if not self._events_to_show:
            print_info('No USB devices found!')
            return 1

        abs_output_auth = os.path.abspath(output_auth)

        try:
            dirname = os.path.dirname(abs_output_auth)
            os_makedirs(dirname)
        except USBRipError as e:
            print_critical(str(e), initial_error=e.errors['initial_error'])
            return 1
        else:
            print_info(f'Created "{dirname}"')

        try:
            auth_json = open(abs_output_auth, 'w', encoding='utf-8')
        except PermissionError as e:
            print_critical(
                f'Permission denied: "{abs_output_auth}". Retry with sudo',
                initial_error=str(e))
            return 1

        print_info('Generating authorized device list (JSON)')

        if not attributes:
            attributes = ('vid', 'pid', 'prod', 'manufact', 'serial')

        auth = defaultdict(list)
        for event in tqdm(self._events_to_show, ncols=80, unit='dev'):
            for key, val in event.items():
                if (key in attributes and val is not None
                        and val not in auth[key]):
                    auth[key].append(val)

        for key in auth.keys():
            auth[key].sort()

        json.dump(auth, auth_json, sort_keys=True, indent=indent)
        auth_json.close()

        print_info(f'New authorized device list: "{abs_output_auth}"')
Пример #10
0
    def create_storage(storage_type,
                       password,
                       *,
                       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 = f'{USBStorage._STORAGE_BASE}/{min_date}-{max_date}.json'
        else:
            json_file = f'{USBStorage._STORAGE_BASE}/{datetime.now().strftime("%Y%m%dT%H%M%S")}.json'

        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

        storage_full_path = f'{USBStorage._STORAGE_BASE}/{storage_type}.7z'
        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(f'New {storage_type} storage: "{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)
Пример #11
0
    def __new__(cls, files=None):
        if files:
            filtered_history = []
            for file in files:
                filtered_history.extend(_read_log_file(file))
        else:
            try:
                filtered_history = _get_filtered_history()
            except USBRipError as e:
                print_critical(str(e))
                return None

        all_events = _parse_history(filtered_history)

        instance = super().__new__(cls)
        instance._all_events = all_events  # self._all_events
        instance._violations = []  # self._violations
        instance._events_to_show = None  # self._events_to_show
        return instance
Пример #12
0
    def __new__(cls, files=None):
        if files:
            raw_history = DefaultOrderedDict(default_factory=list)
            for file in files:
                raw_history.update(_read_log_file(file))
        else:
            try:
                raw_history = _get_raw_history()
            except USBRipError as e:
                print_critical(str(e))
                return None

        divided_history = _divide_history(raw_history)
        all_events = _parse_history(divided_history)

        instance = super().__new__(cls)
        instance._all_events = all_events  # self._all_events
        instance._violations = []  # self._violations
        instance._events_to_show = None  # self._events_to_show
        return instance
Пример #13
0
    def open_storage(storage_type,
                     password,
                     columns,
                     *,
                     sieve=None,
                     repres=None):
        storage_full_path = f'{USBStorage._STORAGE_BASE}/{storage_type}.7z'
        if not os.path.isfile(storage_full_path):
            print_critical(f'Storage not found: "{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'([^\n ]*\.json)',
                                      _7zip_list(storage_full_path, password),
                                      re.MULTILINE).group(1)
            json_file = f'{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)
Пример #14
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)
Пример #15
0
    def search_violations(self,
                          input_auth,
                          attributes,
                          columns,
                          *,
                          indent=4,
                          sieve=None,
                          repres=None):
        print_info(
            f'Opening authorized device list: "{os.path.abspath(input_auth)}"')

        try:
            auth = _process_auth_list(input_auth, indent)
        except json.decoder.JSONDecodeError as e:
            print_critical('Failed to decode authorized device list (JSON)',
                           initial_error=str(e))
            return

        print_info('Searching for violations')

        if not attributes:
            attributes = auth.keys()

        for event in self._all_events:
            try:
                if any(event[key] not in vals and event[key] is not None
                       for key, vals in zip(attributes, auth.values())):
                    self._violations.append(event)
            except KeyError as e:
                print_critical('No such attribute in authorized device list',
                               initial_error=str(e))
                return

        self._events_to_show = _filter_events(self._violations, sieve)
        if not self._events_to_show:
            print_info('No USB violation events found!')
            return

        if not cfg.QUIET and cfg.ISATTY:
            number, filename = _output_choice('violation', 'viol.json',
                                              'violations/')
            if number is None:
                return
            elif number == 1:
                try:
                    _dump_events(self._events_to_show, 'violations', filename,
                                 indent)
                except USBRipError as e:
                    print_critical(str(e),
                                   initial_error=e.errors['initial_error'])
                return

        if columns:
            table_data = [[COLUMN_NAMES[name] for name in columns]]
        else:
            columns = [key for key in COLUMN_NAMES.keys()]
            table_data = [[val for val in COLUMN_NAMES.values()]]

        _represent_events(self._events_to_show, columns, table_data,
                          'USB-Violation-Events', repres)
Пример #16
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
Пример #17
0
	def list_storage(storage_type, password):
		storage_full_path = f'{USBStorage._STORAGE_BASE}/{storage_type}.7z'
		if not os.path.isfile(storage_full_path):
			print_critical(f'Storage not found: "{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)
Пример #18
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:
		if cfg.ISATTY:
			print(BANNER + '\n')
		else:
			print(f'# Done as: usbrip {" ".join(sys.argv[1:])}')
	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(f'Choose one of the usbrip {args.subparser} actions', subparser=subparser)
Пример #19
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)
Пример #20
0
def main():
    if not len(sys.argv) > 1:
        print(BANNER + '\n')
        usbrip_arg_error()

    arg_parser = get_arg_parser()
    args = arg_parser.parse_args()

    if 'quiet' in args and not args.quiet:
        if cfg.ISATTY:
            print(BANNER + '\n')
        else:
            print(f'# Done as: usbrip {" ".join(sys.argv[1:])}')
    else:
        cfg.QUIET = True

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

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

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

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

        sieve, repres = validate_ue_args(args)

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

        if args.ue_subparser == 'history':
            timing.begin()
            ue = USBEvents(args.file)
            if ue:
                ue.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 GenAuth -------------------

        elif args.ue_subparser == 'genauth':
            timing.begin()
            ue = USBEvents(args.file)
            if ue:
                if ue.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()
            ue = USBEvents(args.file)
            if ue:
                ue.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')

        if any(not os.path.exists(p)
               for p in ('/opt/usbrip/', '/var/opt/usbrip',
                         '/usr/local/bin/usbrip')):
            sys.exit(
                'The "storage" module can only be used when usbrip is installed via "installer.sh" - https://git.io/fjDPT'
            )

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

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

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

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

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

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

        elif args.us_subparser == 'update':
            if us.update_storage(args.storage_type,
                                 config_parser[args.storage_type]['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,
                                 config_parser[args.storage_type]['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, 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(f'Choose one of the usbrip {args.subparser} actions',
                         subparser=subparser)
Пример #21
0
	def update_storage(
		storage_type,
		password,
		*,
		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 = f'{USBStorage._STORAGE_BASE}/{storage_type}.7z'
		if not os.path.isfile(storage_full_path):
			print_critical(f'Storage not found: "{storage_full_path}"')
			return 1

		print_info(f'Updating storage: "{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:
			base_filename = re.search(r'([^\n ]*\.json)', _7zip_list(storage_full_path, password), re.MULTILINE).group(1)
			json_file = f'{USBStorage._STORAGE_BASE}/{base_filename}'
			os.remove(storage_full_path)

			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 = f'{USBStorage._STORAGE_BASE}/{min_date}-{max_date}.json'
			_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)