def read_register( ctx: click.Context, address: int, item_length: int, count: int, file: click.File, use_hexdump: bool, ) -> None: """Reads the contents of a memory location or register value. The address of the register or memory location should be passed in as the first argument. Optional arguments include the data format of the register value in the number of bits and number of bytes to read. \b ADDRESS - starting address where to read FORMAT - bits per item: valid values: 8, 16, 32; default 32 COUNT - bytes to read; default size of FORMAT FILE - write data into a file; write to stdout if not specified """ with SDP(ctx.obj["interface"]) as sdp: response = sdp.read_safe(address, count, item_length) if not response: click.echo( f"Error: invalid sub-command or arguments 'read-register {address:#8X} {item_length} {count}'" ) sys.exit(1) if file: file.write(response) # type: ignore else: click.echo(format_raw_data(response, use_hexdump=use_hexdump)) display_output([], sdp.hab_status, ctx.obj["use_json"])
def main(source: click.File, destination: click.File) -> int: requirements = source.read().split() new_requirements = sort_requirements(requirements=requirements) destination.write("\n".join(new_requirements)) click.echo(f"Successfully wrote to {destination.name}") return 0
def read_key_store(ctx: click.Context, key_store_file: click.File) -> None: """Read the key store from bootloader to host(PC). \b FILE - Binary file to save the key store. """ with McuBoot(ctx.obj['interface']) as mboot: response = mboot.kp_read_key_store() if not response: raise SPSDKError('Error reading key store') key_store_file.write(response) # type: ignore display_output([len(response)], mboot.status_code, ctx.obj['use_json'])
def process_input_file(input: click.File, output: click.File): "Process file and create a download link for output file" if DEBUG: click.echo("global debug set, printing some debug output") while True: click.echo(f"Reading from {input.name}...") chunk = input.read(2048) if not chunk: break click.echo(f"Writing to {output.name}...") chunk = chunk.upper() output.write(chunk) click.echo({output.name})
def generate_key_blob(ctx: click.Context, dek_file: click.File, blob_file: click.File) -> None: """Generate the Key Blob for a given DEK. \b DEK_FILE - the file with the binary DEK key BLOB_FILE - the generated file with binary key blob """ with McuBoot(ctx.obj['interface']) as mboot: data = dek_file.read() # type: ignore write_response = mboot.generate_key_blob(data) if not write_response: raise ValueError(f"Error generating key blob") blob_file.write(write_response) # type: ignore display_output([mboot.status_code, len(write_response)], mboot.status_code, ctx.obj['use_json'])
def read_register(ctx: click.Context, address: int, item_length: int, count: int, file: click.File, use_hexdump: bool) -> None: """Read one or more registers. \b ADDRESS - starting address where to read FORMAT - bits per item: valid values: 8, 16, 32; default 32 COUNT - items to read; default 1 FILE - write data into a file; write to stdout if not specified """ with SDP(ctx.obj['interface']) as sdp: response = sdp.read_safe(address, count, item_length) if not response: click.echo(f"Error: invalid command or arguments 'read-register {address:#8X} {item_length} {count}'") sys.exit(1) if file: file.write(response) # type: ignore else: click.echo(format_raw_data(response, use_hexdump=use_hexdump)) display_output([], sdp.response_value, ctx.obj['use_json'])
def read_memory(ctx: click.Context, address: int, byte_count: int, out_file: click.File, memory_id: int, use_hexdump: bool) -> None: """Read memory. \b ADDRESS - starting address BYTE_COUNT - number of bytes to read FILE - store result into this file, if not specified use stdout MEMORY_ID - id of memory to read from (default: 0) """ with McuBoot(ctx.obj['interface']) as mboot: response = mboot.read_memory(address, byte_count, memory_id) assert response, "Error reading memory" if out_file: out_file.write(response) # type: ignore else: click.echo(format_raw_data(response, use_hexdump=use_hexdump)) display_output([len(response)], mboot.status_code, ctx.obj['use_json'], f"Read {len(response)} of {byte_count} bytes.")
def generate_stats(output:click.File, limit=None): try: from google.cloud import bigquery client = bigquery.Client() except Exception: logger.error("Error creating BigQuery client, Aura is probably not correctly configured. Please consult docs.") sys.exit(1) if limit: q = PYPI_STATS_QUERY + f" LIMIT {int(limit)}" else: q = PYPI_STATS_QUERY logger.info("Running Query on PyPI download dataset") query_job = client.query( q, location = 'US', ) for row in query_job: output.write(json.dumps(dict(row)) + '\n') logger.info("PyPI download stats generation finished")
def generate_key_blob(ctx: click.Context, dek_file: click.File, blob_file: click.File, key_sel: str) -> None: """Generate the Key Blob for a given DEK. \b DEK_FILE - the file with the binary DEK key BLOB_FILE - the generated file with binary key blob KEY_SEL - select the BKEK used to wrap the BK and generate the blob. For devices with SNVS, valid options of [key_sel] are 0, 1 or OTPMK: OTPMK from FUSE or OTP(default), 2 or ZMK: ZMK from SNVS, 3 or CMK: CMK from SNVS, For devices without SNVS, this option will be ignored. """ with McuBoot(ctx.obj['interface']) as mboot: data = dek_file.read() # type: ignore key_sel_int = int(key_sel) if key_sel.isnumeric() else GenerateKeyBlobSelect.get(key_sel) assert isinstance(key_sel_int, int) write_response = mboot.generate_key_blob(data, key_sel=key_sel_int) display_output( [mboot.status_code, len(write_response)] if write_response else None, mboot.status_code, ctx.obj['use_json'] ) if write_response: blob_file.write(write_response) # type: ignore
def process_optional_output_file(output: click.File): "Process an output file given as option" if output is None: click.echo("No input file given") else: output.write('Some text written to optional output file')
def dump(file, outfile: click.File): "Parses and dumps the file into stdout" dumped = binary.dump_file(click.format_filename(file)) outfile.write(dumped)
def rpg(pass_length: int, number: int, output: click.File, exclude_charsets: str, no_safe: bool, verbose: bool) -> None: """ Generate random, entropic, complex and safe password. \f :param int pass_length: desire password length :param int number: number of password to generate. Default is 1 :param click.File output: output file :param str exclude_charsets: comma-separated charsets to exclude. Default is None :param bool no_safe: do not check password in Have I Been Pwned db. Default is False :param bool verbose: print verbose output. Default is False :return: None """ # Check pass_length validity msg.Prints.verbose( "Checking <pass-length> ({}) validity".format(pass_length), verbose) if pass_length > 90 or pass_length < 12: raise click.BadArgumentUsage( msg.Echoes.error( "Invalid value for \"<pass-length>\": {} is not in the valid range of 12 to 90." ).format(pass_length)) # Check number validity msg.Prints.verbose("Checking <pass-number> ({}) validity".format(number), verbose) if number > 50: raise click.BadOptionUsage( "number", msg.Echoes.error( "Invalid value for \"<pass-number>\": the maximum value accepted is 50." )) # Load charsets and check the validity msg.Prints.verbose("Loading charsets", verbose) chars = _get_char_list(exclude_charsets) msg.Prints.verbose("Charsets loaded\nChecking charsets validity", verbose) # Check at least one charsets type has been selected if not chars: raise click.BadOptionUsage( "--exclude-charsets", msg.Echoes.error( "RPG needs at least one charsets type to generate password.")) else: if not len(chars) == 4: # User chose to not use any charsets, print warning message msg.Prints.warning( "You are going to generate passwords without one or more of default charsets!" ) msg.Prints.warning( "RPG cares a lot for your security, it's recommended to avoid this practice if possible!\n" ) # Check if --no-safe option is in use, if so, print a warning message if no_safe: msg.Prints.warning( "You are going to generate passwords without checking if they have been already leaked!" ) msg.Prints.warning( "RPG cares a lot for your security, it's recommended to avoid this practice if possible!\n" ) msg.Prints.verbose("Start to generate passwords", verbose) # Print loading pw_list = [] with click.progressbar(length=number, label="Generating passwords", show_pos=True) as pw_bar: for _ in pw_bar: pw = _generate_random_password(pass_length, chars, no_safe) if pw is not None: pw_list.append(pw) else: raise click.ClickException( msg.Echoes.error( "An error occurred while querying Have I Been Pwned API. Please retry or use --no-safe option" )) # Print generated passwords if output: output.write("Passwords:\n") else: msg.Prints.emphasis("Passwords:") for pw in pw_list: if output: output.write("{}\n".format(pw)) else: msg.Prints.info(pw) # Calculate entropy and print it entropy = _get_entropy(pass_length, chars) if output: output.write("\nEntropy: {}".format(entropy)) else: msg.Prints.emphasis( "\nThe entropy of generated password is: {}".format(entropy)) # Print summary table, only if --verbose or --output if output: output.write("\n{}".format(_password_entropy_table)) else: msg.Prints.verbose(_password_entropy_table, verbose)