コード例 #1
0
def secret():
    secret = {
        'name': 'test',
        'version': '0000000000000000000',
        'value': 'secret'
    }
    credstash.putSecret(secret['name'], secret['value'])
    try:
        yield secret
    finally:
        credstash.deleteSecrets("test")
コード例 #2
0
 def credstash_put(self, key, secret, version=""):
     return credstash.putSecret(key,
                                secret,
                                version,
                                kms_key=self.credstash_key,
                                region=self.instance_region,
                                table=self.credstash_table)
コード例 #3
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            secret=dict(required=True, type='str'),
            fact=dict(default=None, type='str'),
            fact_type=dict(default=None, choices=['yaml', 'json']),
            mode=dict(default='get', choices=['get', 'put']),
            value=dict(default=None, type='str'),
            key=dict(default='alias/credstash', type='str'),
            region=dict(default='us-east-1', type='str'),
            table=dict(default='credential-store', type='str'),
            version=dict(default='', type='str'),
            context=dict(default=None, type='dict')
        )
    )

    result = dict(changed=False, failed=False)

    if module.params.get('mode') == 'put':
        result['output'] = credstash.putSecret(
            module.params.get('secret'),
            module.params.get('value'),
            module.params.get('version'),
            module.params.get('key'),
            module.params.get('region'),
            module.params.get('table'),
            module.params.get('context')
        )
        result['changed'] = True

    try:
        result['output'] = credstash.getSecret(
            module.params.get('secret'),
            module.params.get('version'),
            module.params.get('region'),
            module.params.get('table'),
            module.params.get('context')
        )
    except credstash.ItemNotFound:
        module.fail_json(msg="credstash secret not found")

    fact = module.params.get('fact')
    fact_type = module.params.get('fact_type')

    if fact is not None:
        if fact_type == 'yaml':
            result['ansible_facts'] = {
                fact: yaml.safe_load(result['output'])
            }
        elif fact_type == 'json':
            result['ansible_facts'] = {
                fact: json.load(result['output'])
            }
        else:
            result['ansible_facts'] = {
                fact: result['output']
            }

    module.exit_json(**result)
コード例 #4
0
ファイル: alohomora.py プロジェクト: srinidhis05/alohomora
 def store(self, key, secret):
     msg = ''
     try:
         credstash.putSecret(
             table=self.make_table_name(),
             region=self.region,
             name=key,
             secret=secret,
         )
         msg = "secret saved"
     except Exception as e:
         if (e.response["Error"]["Code"] ==
                 "ConditionalCheckFailedException"):
             msg = ("store command failed\n"
                    "Please try the command: credstash -r {0}"
                    " -t {1} put -a {2} [secret]").format(
                        self.region, self.make_table_name(), key)
     finally:
         return msg
コード例 #5
0
def set_secret(secret_key, secret_value):
    next_version = credstash.paddedInt(int(credstash.getHighestVersion(
        name=secret_key
    )) + 1)

    result = credstash.putSecret(
        name=secret_key,
        secret=secret_value,
        version=next_version
    )

    return True if result['ResponseMetadata']['HTTPStatusCode'] < 300 else False
コード例 #6
0
def credstash_push(args, key, value, ver=0):
    if args.verbose:
        print('Pushing secret {secret} to "{table}"'.format(
            secret=key, table=args.tar_table))
    session_params = credstash.get_session_params(None, None)
    if ver == 0:
        pushed_secret = credstash.putSecret(key,
                                            value,
                                            region=args.region,
                                            table=args.tar_table,
                                            kms_key=args.kms_key_alias,
                                            **session_params)
    else:
        pushed_secret = credstash.putSecret(key,
                                            value,
                                            version=ver,
                                            region=args.region,
                                            table=args.tar_table,
                                            kms_key=args.kms_key_alias,
                                            **session_params)
    return pushed_secret
コード例 #7
0
def main():
  module = AnsibleModule(
    argument_spec = dict(
      secret = dict(required=True, type='str'),
      fact = dict(default=None, type='str'),
      fact_type = dict(default=None, choices=['yaml','json']),
      mode = dict(default='get', choices=['get', 'put']),
      value = dict(default=None, type='str'),
      key = dict(default='alias/credstash', type='str'),
      region = dict(default='us-east-1', type='str'),
      table = dict(default='credential-store', type='str'),
      version = dict(default='', type='str'),
      context = dict(default=None, type='dict')
    )
  )

  result = dict(changed=False, failed=False)

  if module.params.get('mode') == 'put':
    result['output'] = credstash.putSecret(module.params.get('secret'), module.params.get('value'), \
      module.params.get('version'), module.params.get('key'), module.params.get('region'), \
      module.params.get('table'), module.params.get('context'))
    result['changed'] = True

  try: 
    result['output'] = credstash.getSecret(module.params.get('secret'), module.params.get('version'), \
      module.params.get('region'), module.params.get('table'), module.params.get('context')) 
  except credstash.ItemNotFound:
    module.fail_json(msg="credstash secret not found")
  
  if module.params.get('fact') is not None:
    if module.params.get('fact_type') == 'yaml':
      result['ansible_facts'] = { module.params.get('fact'): yaml.safe_load(result['output']) }
    elif module.params.get('fact_type') == 'json':
      result['ansible_facts'] = { module.params.get('fact'): json.load(result['output']) } 
    else:
      result['ansible_facts'] = { module.params.get('fact'): result['output'] }

  module.exit_json(**result)
コード例 #8
0
def run(args):
    """Handle credstash script."""
    parser = argparse.ArgumentParser(
        description=("Modify Home Assistant secrets in credstash."
                     "Use the secrets in configuration files with: "
                     "!secret <name>"))
    parser.add_argument("--script", choices=["credstash"])
    parser.add_argument(
        "action",
        choices=["get", "put", "del", "list"],
        help="Get, put or delete a secret, or list all available secrets",
    )
    parser.add_argument("name",
                        help="Name of the secret",
                        nargs="?",
                        default=None)
    parser.add_argument("value",
                        help="The value to save when putting a secret",
                        nargs="?",
                        default=None)

    # pylint: disable=import-error, no-member
    import credstash

    args = parser.parse_args(args)
    table = _SECRET_NAMESPACE

    try:
        credstash.listSecrets(table=table)
    except Exception:  # pylint: disable=broad-except
        credstash.createDdbTable(table=table)

    if args.action == "list":
        secrets = [i["name"] for i in credstash.listSecrets(table=table)]
        deduped_secrets = sorted(set(secrets))

        print("Saved secrets:")
        for secret in deduped_secrets:
            print(secret)
        return 0

    if args.name is None:
        parser.print_help()
        return 1

    if args.action == "put":
        if args.value:
            the_secret = args.value
        else:
            the_secret = getpass.getpass(
                f"Please enter the secret for {args.name}: ")
        current_version = credstash.getHighestVersion(args.name, table=table)
        credstash.putSecret(args.name,
                            the_secret,
                            version=int(current_version) + 1,
                            table=table)
        print(f"Secret {args.name} put successfully")
    elif args.action == "get":
        the_secret = credstash.getSecret(args.name, table=table)
        if the_secret is None:
            print(f"Secret {args.name} not found")
        else:
            print(f"Secret {args.name}={the_secret}")
    elif args.action == "del":
        credstash.deleteSecrets(args.name, table=table)
        print(f"Deleted secret {args.name}")
コード例 #9
0
    def run(self, terms, variables, **kwargs):

        if not CREDSTASH_INSTALLED:
            raise AnsibleError(
                'The credstash lookup plugin requires credstash to be installed.'
            )

        ret = []
        for term in terms:
            version = kwargs.pop('version', '')
            region = kwargs.pop('region', None)
            table = kwargs.pop('table', 'credential-store')
            kms_alias = kwargs.pop('kms_alias', 'alias/credstash')
            keytype = kwargs.pop('keytype', 'password')
            secret = kwargs.pop('secret', None)
            digest = kwargs.pop('digest', 'SHA512')
            context = kwargs.pop('context', None)
            cert_request = kwargs.pop('cert_request', None)
            transient = kwargs.pop(
                'transient', False)  # if transient we don't save certificates

            # Deal with credstash version numbers...
            if version == '':
                version = self.paddedInt(1)
            else:
                version = self.paddedInt(version)

            if 'alias/' not in kms_alias:
                kms_alias = 'alias/{0}'.format(kms_alias)

            try:
                if keytype == 'password' or keytype == 'manual' or keytype == 'consul-gossip-encryption-key' or keytype == 'uuid':
                    val = credstash.getSecret(term,
                                              version,
                                              region,
                                              table,
                                              context=context)
                elif keytype == 'ssh-key':
                    id_rsa = credstash.getSecret(term + '_private',
                                                 version,
                                                 region,
                                                 table,
                                                 context=context)
                    id_rsa_pub = credstash.getSecret(term + '_public',
                                                     version,
                                                     region,
                                                     table,
                                                     context=context)
                    val = [id_rsa_pub, id_rsa]
                elif keytype == 'x509':
                    ca_ser = credstash.getSecret(term + '_serial',
                                                 version,
                                                 region,
                                                 table,
                                                 context=context)
                    ca_key = credstash.getSecret(term + '_key',
                                                 version,
                                                 region,
                                                 table,
                                                 context=context)
                    ca_csr = credstash.getSecret(term + '_csr',
                                                 version,
                                                 region,
                                                 table,
                                                 context=context)
                    ca_crt = credstash.getSecret(term + '_crt',
                                                 version,
                                                 region,
                                                 table,
                                                 context=context)
                    val = [ca_ser, ca_key, ca_csr, ca_crt]
                else:
                    raise AnsibleError(
                        'Invalid password type: {0}'.format(keytype))
            except credstash.ItemNotFound:
                if keytype == 'password':
                    secret = self.random_password()
                    rc = credstash.putSecret(name=term,
                                             secret=secret,
                                             version=version,
                                             kms_key=kms_alias,
                                             region=region,
                                             table=table,
                                             digest=digest,
                                             context=context)
                    val = secret
                elif keytype == 'uuid':
                    secret = self.random_uuid()
                    rc = credstash.putSecret(name=term,
                                             secret=secret,
                                             version=version,
                                             kms_key=kms_alias,
                                             region=region,
                                             table=table,
                                             digest=digest,
                                             context=context)
                    val = secret
                elif keytype == 'ssh-key':
                    (id_rsa, id_rsa_pub) = self.random_rsa()
                    rc_rsa = credstash.putSecret(name=term + '_private',
                                                 secret=id_rsa,
                                                 version=version,
                                                 kms_key=kms_alias,
                                                 region=region,
                                                 table=table,
                                                 digest=digest,
                                                 context=context)
                    rc_rsa_pub = credstash.putSecret(name=term + '_public',
                                                     secret=id_rsa_pub,
                                                     version=version,
                                                     kms_key=kms_alias,
                                                     region=region,
                                                     table=table,
                                                     digest=digest,
                                                     context=context)
                    val = [id_rsa_pub, id_rsa]
                elif keytype == 'x509':
                    # For use in creating a PKI, we can create x509 requests
                    bits = cert_request.get('bits', 4096)
                    cert_digest = cert_request.get('hash', 'sha256')
                    extensions = cert_request.get('extensions', [])
                    subject = cert_request.get('subject', {'CN': term})
                    subject_alt_names = cert_request.get(
                        'subject_alt_names', '')
                    days = cert_request.get('days', 3650)
                    ca = cert_request.get('ca', None)
                    cert_version = int(cert_request.get('version', 1))

                    # Get the latest version of the ca_serial ca_key and ca_crt
                    if ca:
                        ca_ser = int(
                            credstash.getSecret(ca + '_serial',
                                                '',
                                                region,
                                                table,
                                                context=context))
                        ca_key = crypto.load_privatekey(
                            crypto.FILETYPE_PEM,
                            credstash.getSecret(ca + '_key',
                                                '',
                                                region,
                                                table,
                                                context=context))
                        ca_crt = crypto.load_certificate(
                            crypto.FILETYPE_PEM,
                            credstash.getSecret(ca + '_crt',
                                                '',
                                                region,
                                                table,
                                                context=context))

                    # handle any weird unicode conversion issues on subjects and extensions and subjectaltnames
                    subject = dict(
                        (str(k), str(v)) for (k, v) in subject.items())
                    extensions = [
                        dict((str(k), str(v)) for (k, v) in i.items())
                        for i in extensions
                    ]
                    subject_alt_names = [str(x) for x in subject_alt_names]

                    # create the key and certificate signing request
                    key = self.create_key_pair(bits=bits)
                    csr = self.create_certificate_request(key,
                                                          digest=cert_digest,
                                                          **subject)

                    # if this certificate needs to be signed, the 'ca' attribute will be set to the name of the CA.
                    # use the ca_key and ca_crt to sign, and increment the serial number associated with the ca_ser.
                    if ca:
                        rc_ser = int(ca_ser) + 1
                        crt = self.create_certificate(
                            csr,
                            ca_crt,
                            ca_key,
                            int(rc_ser),
                            days=days,
                            digest=cert_digest,
                            extensions=extensions,
                            subject_alt_names=subject_alt_names,
                            version=cert_version)
                        if not transient:
                            credstash.putSecret(name=ca + '_serial',
                                                secret=str(rc_ser),
                                                version=self.paddedInt(rc_ser),
                                                kms_key=kms_alias,
                                                region=region,
                                                table=table,
                                                digest=digest,
                                                context=context)
                    else:
                        rc_ser = "1"
                        crt = self.create_certificate(
                            csr,
                            csr,
                            key,
                            int(rc_ser),
                            days=days,
                            digest=cert_digest,
                            extensions=extensions,
                            subject_alt_names=subject_alt_names,
                            version=cert_version)

                    # write the configuration for this x509 certificate to credstash if not transient
                    rc_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
                    rc_csr = crypto.dump_certificate_request(
                        crypto.FILETYPE_PEM, csr)
                    rc_crt = crypto.dump_certificate(crypto.FILETYPE_PEM, crt)

                    if not transient:
                        credstash.putSecret(name=term + '_serial',
                                            secret=str(rc_ser),
                                            version=version,
                                            kms_key=kms_alias,
                                            region=region,
                                            table=table,
                                            digest=digest,
                                            context=context)
                        credstash.putSecret(name=term + '_key',
                                            secret=rc_key,
                                            version=version,
                                            kms_key=kms_alias,
                                            region=region,
                                            table=table,
                                            digest=digest,
                                            context=context)
                        credstash.putSecret(name=term + '_csr',
                                            secret=rc_csr,
                                            version=version,
                                            kms_key=kms_alias,
                                            region=region,
                                            table=table,
                                            digest=digest,
                                            context=context)
                        credstash.putSecret(name=term + '_crt',
                                            secret=rc_crt,
                                            version=version,
                                            kms_key=kms_alias,
                                            region=region,
                                            table=table,
                                            digest=digest,
                                            context=context)

                    val = [rc_ser, rc_key, rc_csr, rc_crt]
                elif keytype == 'consul-gossip-encryption-key':
                    # Consul Gossip Encryption keys are 16-byte base64 encoded numbers
                    key = os.urandom(16)
                    secret = base64.b64encode(key)
                    rc = credstash.putSecret(name=term,
                                             secret=secret,
                                             version=version,
                                             kms_key=kms_alias,
                                             region=region,
                                             table=table,
                                             digest=digest,
                                             context=context)
                    val = secret
                elif keytype == 'manual':
                    if secret is not None:
                        rc = credstash.putSecret(name=term,
                                                 secret=secret,
                                                 version=version,
                                                 kms_key=kms_alias,
                                                 region=region,
                                                 table=table,
                                                 digest=digest,
                                                 context=context)
                        val = secret
                    else:
                        raise AnsibleError(
                            'Key {0} is flagged as manually set, but has not yet been set'
                            .format(term))
                else:
                    raise AnsibleError(
                        'Invalid password type: {0}'.format(keytype))
            except Exception as e:
                raise AnsibleError(
                    'Encountered exception while fetching {0}: {1}'.format(
                        term, e.message))
            ret.append(val)

        return ret
コード例 #10
0
def run(args):
    """Handle credstash script."""
    parser = argparse.ArgumentParser(
        description=("Modify Home Assistant secrets in credstash."
                     "Use the secrets in configuration files with: "
                     "!secret <name>"))
    parser.add_argument('--script', choices=['credstash'])
    parser.add_argument(
        'action',
        choices=['get', 'put', 'del', 'list'],
        help="Get, put or delete a secret, or list all available secrets")
    parser.add_argument('name',
                        help="Name of the secret",
                        nargs='?',
                        default=None)
    parser.add_argument('value',
                        help="The value to save when putting a secret",
                        nargs='?',
                        default=None)

    # pylint: disable=import-error, no-member
    import credstash

    args = parser.parse_args(args)
    table = _SECRET_NAMESPACE

    try:
        credstash.listSecrets(table=table)
    except Exception:  # pylint: disable=broad-except
        credstash.createDdbTable(table=table)

    if args.action == 'list':
        secrets = [i['name'] for i in credstash.listSecrets(table=table)]
        deduped_secrets = sorted(set(secrets))

        print('Saved secrets:')
        for secret in deduped_secrets:
            print(secret)
        return 0

    if args.name is None:
        parser.print_help()
        return 1

    if args.action == 'put':
        if args.value:
            the_secret = args.value
        else:
            the_secret = getpass.getpass(
                'Please enter the secret for {}: '.format(args.name))
        current_version = credstash.getHighestVersion(args.name, table=table)
        credstash.putSecret(args.name,
                            the_secret,
                            version=int(current_version) + 1,
                            table=table)
        print('Secret {} put successfully'.format(args.name))
    elif args.action == 'get':
        the_secret = credstash.getSecret(args.name, table=table)
        if the_secret is None:
            print('Secret {} not found'.format(args.name))
        else:
            print('Secret {}={}'.format(args.name, the_secret))
    elif args.action == 'del':
        credstash.deleteSecrets(args.name, table=table)
        print('Deleted secret {}'.format(args.name))
コード例 #11
0
ファイル: Squirrel.py プロジェクト: eddo888/Spanners
 def put(self, name, value):
     return credstash.putSecret(name,
                                value,
                                region=region(),
                                table=table())
コード例 #12
0
ファイル: credstash.py プロジェクト: Landrash/home-assistant
def run(args):
    """Handle credstash script."""
    parser = argparse.ArgumentParser(
        description=("Modify Home Assistant secrets in credstash."
                     "Use the secrets in configuration files with: "
                     "!secret <name>"))
    parser.add_argument(
        '--script', choices=['credstash'])
    parser.add_argument(
        'action', choices=['get', 'put', 'del', 'list'],
        help="Get, put or delete a secret, or list all available secrets")
    parser.add_argument(
        'name', help="Name of the secret", nargs='?', default=None)
    parser.add_argument(
        'value', help="The value to save when putting a secret",
        nargs='?', default=None)

    import credstash
    import botocore

    args = parser.parse_args(args)
    table = _SECRET_NAMESPACE

    try:
        credstash.listSecrets(table=table)
    except botocore.errorfactory.ClientError:
        credstash.createDdbTable(table=table)

    if args.action == 'list':
        secrets = [i['name'] for i in credstash.listSecrets(table=table)]
        deduped_secrets = sorted(set(secrets))

        print('Saved secrets:')
        for secret in deduped_secrets:
            print(secret)
        return 0

    if args.name is None:
        parser.print_help()
        return 1

    if args.action == 'put':
        if args.value:
            the_secret = args.value
        else:
            the_secret = getpass.getpass('Please enter the secret for {}: '
                                         .format(args.name))
        current_version = credstash.getHighestVersion(args.name, table=table)
        credstash.putSecret(args.name,
                            the_secret,
                            version=int(current_version) + 1,
                            table=table)
        print('Secret {} put successfully'.format(args.name))
    elif args.action == 'get':
        the_secret = credstash.getSecret(args.name, table=table)
        if the_secret is None:
            print('Secret {} not found'.format(args.name))
        else:
            print('Secret {}={}'.format(args.name, the_secret))
    elif args.action == 'del':
        credstash.deleteSecrets(args.name, table=table)
        print('Deleted secret {}'.format(args.name))
コード例 #13
0
    def create(self, **kwargs):
        secret_name = kwargs.pop('secret_name', None)
        version = kwargs.pop('version', '')
        keytype = kwargs.pop('keytype', 'password')
        region = kwargs.pop('region', None)
        table = kwargs.pop('table', 'credential-store')
        kms_alias = kwargs.pop('kms_alias', 'alias/credstash')
        digest = kwargs.pop('digest', 'SHA512')
        context = kwargs.pop('context', None)
        cert_request = kwargs.pop('cert_request', None)
        transient = kwargs.pop(
            'transient', False)  # if transient we don't save certificates

        val = None

        # Deal with credstash version numbers...
        if version == '':
            version = self.paddedInt(1)
        else:
            version = self.paddedInt(version)

        if 'alias/' not in kms_alias:
            kms_alias = 'alias/{0}'.format(kms_alias)

        try:
            if keytype == 'password':
                secret = credstash.getSecret(secret_name,
                                             version,
                                             region,
                                             table,
                                             context=context)
                val = {"Password": secret}
            elif keytype == 'manual':
                secret = credstash.getSecret(secret_name,
                                             version,
                                             region,
                                             table,
                                             context=context)
                val = {"Manual": secret}
            elif keytype == 'consul-gossip-encryption-key':
                secret = credstash.getSecret(secret_name,
                                             version,
                                             region,
                                             table,
                                             context=context)
                val = {"ConsulGossipEncryptionKey": secret}
            elif keytype == 'uuid':
                secret = credstash.getSecret(secret_name,
                                             version,
                                             region,
                                             table,
                                             context=context)
                val = {"Uuid": secret}
            elif keytype == 'ssh-key':
                id_rsa = credstash.getSecret(secret_name + '_private',
                                             version,
                                             region,
                                             table,
                                             context=context)
                id_rsa_pub = credstash.getSecret(secret_name + '_public',
                                                 version,
                                                 region,
                                                 table,
                                                 context=context)
                val = {"PublicKey": id_rsa_pub}
            else:
                raise Exception('Invalid password type: {0}'.format(keytype))
        except credstash.ItemNotFound:
            if keytype == 'password':
                secret = self.random_password()
                rc = credstash.putSecret(name=secret_name,
                                         secret=secret,
                                         version=version,
                                         kms_key=kms_alias,
                                         region=region,
                                         table=table,
                                         digest=digest,
                                         context=context)
                val = {"Password": secret}
            elif keytype == 'uuid':
                secret = self.random_uuid()
                rc = credstash.putSecret(name=secret_name,
                                         secret=secret,
                                         version=version,
                                         kms_key=kms_alias,
                                         region=region,
                                         table=table,
                                         digest=digest,
                                         context=context)
                val = {"Uuid": secret}
            elif keytype == 'ssh-key':
                (id_rsa, id_rsa_pub) = self.random_rsa()
                rc_rsa = credstash.putSecret(name=secret_name + '_private',
                                             secret=id_rsa,
                                             version=version,
                                             kms_key=kms_alias,
                                             region=region,
                                             table=table,
                                             digest=digest,
                                             context=context)
                rc_rsa_pub = credstash.putSecret(name=secret_name + '_public',
                                                 secret=id_rsa_pub,
                                                 version=version,
                                                 kms_key=kms_alias,
                                                 region=region,
                                                 table=table,
                                                 digest=digest,
                                                 context=context)
                val = {"PublicKey": id_rsa_pub}
            elif keytype == 'consul-gossip-encryption-key':
                # Consul Gossip Encryption keys are 16-byte base64 encoded numbers
                key = os.urandom(16)
                secret = base64.b64encode(key)
                rc = credstash.putSecret(name=secret_name,
                                         secret=secret,
                                         version=version,
                                         kms_key=kms_alias,
                                         region=region,
                                         table=table,
                                         digest=digest,
                                         context=context)
                val = {"ConsulGossipEncryptionKey": secret}
            elif keytype == 'manual':
                if secret is not None:
                    rc = credstash.putSecret(name=secret_name,
                                             secret=secret,
                                             version=version,
                                             kms_key=kms_alias,
                                             region=region,
                                             table=table,
                                             digest=digest,
                                             context=context)
                    val = {"Manual": secret}
                else:
                    raise Exception(
                        'Key {0} is flagged as manually set, but has not yet been set'
                        .format(secret_name))
            else:
                raise Exception('Invalid password type: {0}'.format(keytype))
        except Exception as e:
            raise Exception(
                'Encountered exception while fetching {0}: {1}'.format(
                    secret_name, e.message))

        return val