How to use the securesystemslib.formats function in securesystemslib

To help you get started, we’ve selected a few securesystemslib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github secure-systems-lab / securesystemslib / tests / test_ed25519_keys.py View on Github external
def test_create_signature(self):
    global public
    global private
    data = b'The quick brown fox jumps over the lazy dog'
    scheme = 'ed25519'
    signature, scheme = securesystemslib.ed25519_keys.create_signature(public,
        private, data, scheme)

    # Verify format of returned values.
    self.assertEqual(True,
        securesystemslib.formats.ED25519SIGNATURE_SCHEMA.matches(signature))

    self.assertEqual(True, securesystemslib.formats.ED25519_SIG_SCHEMA.matches(scheme))
    self.assertEqual('ed25519', scheme)

    # Check for improperly formatted argument.
    self.assertRaises(securesystemslib.exceptions.FormatError,
        securesystemslib.ed25519_keys.create_signature, 123, private, data,
        scheme)

    self.assertRaises(securesystemslib.exceptions.FormatError,
        securesystemslib.ed25519_keys.create_signature, public, 123, data,
        scheme)

    # Check for invalid 'data'.
    self.assertRaises(securesystemslib.exceptions.CryptoError,
        securesystemslib.ed25519_keys.create_signature, public, private, 123,
github secure-systems-lab / securesystemslib / securesystemslib / process.py View on Github external
subprocess.TimeoutExpired:
            If the process does not terminate after timeout seconds. Default
            is `settings.SUBPROCESS_TIMEOUT`

  
    The side effects of executing the given command in this environment.

  
    A subprocess.CompletedProcess instance.

  """
  # Make list of command passed as string for convenience
  if isinstance(cmd, six.string_types):
    cmd = shlex.split(cmd)
  else:
    securesystemslib.formats.LIST_OF_ANY_STRING_SCHEMA.check_match(cmd)

  # NOTE: The CPython implementation would raise a ValueError here, we just
  # don't pass on `stdin` if the user passes `input` and `stdin`
  # https://github.com/python/cpython/blob/3.5/Lib/subprocess.py#L378-L381
  if kwargs.get("input") is not None and "stdin" in kwargs:
    log.debug("stdin and input arguments may not both be used. "
        "Ignoring passed stdin: " + str(kwargs["stdin"]))
    del kwargs["stdin"]

  return subprocess.run(cmd, check=check, timeout=timeout, **kwargs)
github secure-systems-lab / securesystemslib / securesystemslib / keys.py View on Github external
securesystemslib.exceptions.FormatError, if 'pem' is improperly formatted.

  
    None

  
    True if 'pem' is public and false otherwise.
  """

  # Do the arguments have the correct format?
  # This check will ensure arguments have the appropriate number
  # of objects and object types, and that all dict keys are properly named.
  # Raise 'securesystemslib.exceptions.FormatError' if the check fails.
  securesystemslib.formats.PEMRSA_SCHEMA.check_match(pem)

  pem_header = '-----BEGIN PUBLIC KEY-----'
  pem_footer = '-----END PUBLIC KEY-----'

  try:
    header_start = pem.index(pem_header)
    pem.index(pem_footer, header_start + len(pem_header))

  except ValueError:
    return False

  return True
github secure-systems-lab / securesystemslib / securesystemslib / keys.py View on Github external
securesystemslib.exceptions.FormatError, if any of the arguments are
    improperly formatted.

  
    None

  
    True if 'pem' is private and false otherwise.
  """

  # Do the arguments have the correct format?
  # This check will ensure arguments have the appropriate number
  # of objects and object types, and that all dict keys are properly named.
  # Raise 'securesystemslib.exceptions.FormatError' if the check fails.
  securesystemslib.formats.PEMRSA_SCHEMA.check_match(pem)
  securesystemslib.formats.NAME_SCHEMA.check_match(keytype)

  if keytype == 'rsa':
    pem_header = '-----BEGIN RSA PRIVATE KEY-----'
    pem_footer = '-----END RSA PRIVATE KEY-----'

  elif keytype == 'ec':
    pem_header = '-----BEGIN EC PRIVATE KEY-----'
    pem_footer = '-----END EC PRIVATE KEY-----'

  else:
    raise securesystemslib.exceptions.FormatError('Unsupported key'
      ' type: ' + repr(keytype) + '.  Supported keytypes: ["rsa", "ec"]')

  try:
    header_start = pem.index(pem_header)
    pem.index(pem_footer, header_start + len(pem_header))
github secure-systems-lab / securesystemslib / securesystemslib / keys.py View on Github external
None.

  
    A 'securesystemslib.formats.KEY_SCHEMA' dictionary.
  """

  # Does 'keytype' have the correct format?
  # This check will ensure 'keytype' has the appropriate number
  # of objects and object types, and that all dict keys are properly named.
  # Raise 'securesystemslib.exceptions.FormatError' if the check fails.
  securesystemslib.formats.KEYTYPE_SCHEMA.check_match(keytype)

  # Does 'scheme' have the correct format?
  securesystemslib.formats.SCHEME_SCHEMA.check_match(scheme)

  # Does 'key_value' have the correct format?
  securesystemslib.formats.KEYVAL_SCHEMA.check_match(key_value)

  if private is True:
    # If the caller requests (via the 'private' argument) to include a private
    # key in the returned dictionary, ensure the private key is actually
    # present in 'key_val' (a private key is optional for 'KEYVAL_SCHEMA'
    # dicts).
    if 'private' not in key_value:
      raise securesystemslib.exceptions.FormatError('The required private key'
        ' is missing from: ' + repr(key_value))

    else:
      return {'keytype': keytype, 'scheme': scheme, 'keyval': key_value}
github theupdateframework / tuf / tuf / developer_tool.py View on Github external
def __init__(self, project_name, metadata_directory, targets_directory,
      file_prefix, repository_name='default'):

    # Do the arguments have the correct format?
    # Ensure the arguments have the appropriate number of objects and object
    # types, and that all dict keys are properly named.  Raise
    # 'securesystemslib.exceptions.FormatError' if any are improperly
    # formatted.
    securesystemslib.formats.NAME_SCHEMA.check_match(project_name)
    securesystemslib.formats.PATH_SCHEMA.check_match(metadata_directory)
    securesystemslib.formats.PATH_SCHEMA.check_match(targets_directory)
    securesystemslib.formats.PATH_SCHEMA.check_match(file_prefix)
    securesystemslib.formats.NAME_SCHEMA.check_match(repository_name)

    self.metadata_directory = metadata_directory
    self.targets_directory = targets_directory
    self.project_name = project_name
    self.prefix = file_prefix
    self.repository_name = repository_name

    # Layout type defaults to "flat" unless explicitly specified in
    # create_new_project().
    self.layout_type = 'flat'

    # Set the top-level Targets object.  Set the rolename to be the project's
    # name.
github secure-systems-lab / securesystemslib / securesystemslib / gpg / common.py View on Github external
If no master key or subkeys could be found that matches the passed
          keyid.

    securesystemslib.exceptions.FormatError
          If the passed keyid does not match
          securesystemslib.formats.KEYID_SCHEMA

  
    None.

  
    A public key in the format securesystemslib.formats.GPG_PUBKEY_SCHEMA with
    optional subkeys.

  """
  securesystemslib.formats.KEYID_SCHEMA.check_match(keyid)
  if not data:
    raise KeyNotFoundError("Could not find gpg key '{}' in empty exported key "
        "data.".format(keyid))

  # Parse out master key and subkeys (enriched and verified via certificates
  # and binding signatures)
  raw_key_bundle = parse_pubkey_bundle(data)
  master_public_key = _assign_certified_key_info(raw_key_bundle)
  sub_public_keys = _get_verified_subkeys(raw_key_bundle)

  # Since GPG returns all pubkeys associated with a keyid (master key and
  # subkeys) we check which key matches the passed keyid.
  # If the matching key is a subkey, we warn the user because we return
  # the whole bundle (master plus all subkeys) and not only the subkey.
  # If no matching key is found we raise a KeyNotFoundError.
  for idx, public_key in enumerate(
github in-toto / in-toto / in_toto / runlib.py View on Github external
If a key parameter is passed for signing, the newly created link metadata
    file is written to disk using the filename scheme: `link.FILENAME_FORMAT`

  
    Newly created Metablock object containing a Link object

  """
  LOG.info("Running '{}'...".format(name))

  # Check key formats to fail early
  if signing_key:
    _check_match_signing_key(signing_key)
  if gpg_keyid:
    securesystemslib.formats.KEYID_SCHEMA.check_match(gpg_keyid)

  if exclude_patterns:
    securesystemslib.formats.NAMES_SCHEMA.check_match(exclude_patterns)

  if base_path:
    securesystemslib.formats.PATH_SCHEMA.check_match(base_path)

  if material_list:
    LOG.info("Recording materials '{}'...".format(", ".join(material_list)))

  materials_dict = record_artifacts_as_dict(material_list,
      exclude_patterns=exclude_patterns, base_path=base_path,
      follow_symlink_dirs=True, normalize_line_endings=normalize_line_endings,
      lstrip_paths=lstrip_paths)

  if link_cmd_args:
github secure-systems-lab / securesystemslib / securesystemslib / keys.py View on Github external
None.

  
    A dictionary containing the ECDSA keys and other identifying information.
    Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
  """

  # Does 'pem' have the correct format?
  # This check will ensure 'pem' conforms to
  # 'securesystemslib.formats.ECDSARSA_SCHEMA'.
  securesystemslib.formats.PEMECDSA_SCHEMA.check_match(pem)

  # Is 'scheme' properly formatted?
  securesystemslib.formats.ECDSA_SCHEME_SCHEMA.check_match(scheme)

  if password is not None:
    securesystemslib.formats.PASSWORD_SCHEMA.check_match(password)

  else:
    logger.debug('The password/passphrase is unset.  The PEM is expected'
      ' to be unencrypted.')

  # Begin building the ECDSA key dictionary.
  ecdsakey_dict = {}
  keytype = 'ecdsa-sha2-nistp256'
  public = None
  private = None

  public, private = \
      securesystemslib.ecdsa_keys.create_ecdsa_public_and_private_from_pem(pem,
github secure-systems-lab / securesystemslib / securesystemslib / ecdsa_keys.py View on Github external
None.

  
    A dictionary containing the ECDSA keys and other identifying information.
    Conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA'.
  """

  if not CRYPTO: # pragma: no cover
    raise securesystemslib.exceptions.UnsupportedLibraryError(NO_CRYPTO_MSG)

  # Does 'pem' have the correct format?
  # This check will ensure 'pem' conforms to
  # 'securesystemslib.formats.ECDSARSA_SCHEMA'.
  securesystemslib.formats.PEMECDSA_SCHEMA.check_match(pem)

  if password is not None:
    securesystemslib.formats.PASSWORD_SCHEMA.check_match(password)
    password = password.encode('utf-8')

  else:
    logger.debug('The password/passphrase is unset.  The PEM is expected'
      ' to be unencrypted.')

  public = None
  private = None

  # Generate the public and private ECDSA keys.  The pyca/cryptography library
  # performs the actual import operation.
  try:
    private = load_pem_private_key(pem.encode('utf-8'), password=password,