Beispiel #1
0
def test():
    from custodia.compat import configparser
    from custodia.log import setup_logging
    from .interface import IPA_SECTIONNAME

    parser = configparser.ConfigParser(
        interpolation=configparser.ExtendedInterpolation()
    )
    parser.read_string(u"""
    [auth:ipa]
    handler = IPAInterface
    [store:ipa_vault]
    handler = IPAVault
    """)

    setup_logging(debug=True, auditfile=None)
    config = {
        'authenticators': {
            'ipa': IPAInterface(parser, IPA_SECTIONNAME)
        }
    }
    v = IPAVault(parser, 'store:ipa_vault')
    v.finalize_init(config, parser, None)
    v.set('foo', 'bar', replace=True)
    print(v.get('foo'))
    print(v.list())
    v.cut('foo')
    print(v.list())
Beispiel #2
0
 def setUpClass(cls):
     cls.tmpdir = tempfile.mkdtemp()
     cls.parser = configparser.ConfigParser(
         interpolation=configparser.ExtendedInterpolation(),
         defaults={'tmpdir': cls.tmpdir})
     cls.parser.read_string(CONFIG)
     cls.backing_store = SqliteStore(cls.parser, 'store:teststore')
def generate_all_keys(custodia_conf):
    parser = configparser.ConfigParser(
        interpolation=configparser.ExtendedInterpolation())
    with open(custodia_conf) as f:
        parser.read_file(f)

    filename = parser.get('store:encgen', 'master_key')
    key = jwk.JWK(generate='oct', size=256)
    with open(filename, 'w+') as keyfile:
        keyfile.write(key.export())

    store = SqliteStore(parser, 'store:simple')

    srv_kid = "srvkid"
    cli_kid = "clikid"
    ss_key = jwk.JWK(generate='RSA', kid=srv_kid, use="sig")
    se_key = jwk.JWK(generate='RSA', kid=srv_kid, use="enc")
    store.set('kemkeys/sig/%s' % srv_kid, ss_key.export())
    store.set('kemkeys/enc/%s' % srv_kid, se_key.export())

    cs_key = jwk.JWK(generate='RSA', kid=cli_kid, use="sig")
    ce_key = jwk.JWK(generate='RSA', kid=cli_kid, use="enc")
    store.set('kemkeys/sig/%s' % cli_kid, cs_key.export_public())
    store.set('kemkeys/enc/%s' % cli_kid, ce_key.export_public())
    return ([ss_key.export_public(),
             se_key.export_public()], [cs_key.export(),
                                       ce_key.export()])
Beispiel #4
0
def test():
    from custodia.compat import configparser
    from custodia.log import setup_logging
    from .interface import IPA_SECTIONNAME
    from .vault import IPAVault

    parser = configparser.ConfigParser(
        interpolation=configparser.ExtendedInterpolation())
    parser.read_string(u"""
    [auth:ipa]
    handler = IPAInterface
    [store:ipa_vault]
    handler = IPAVault
    [store:ipa_certreq]
    handler = IPAVault
    backing_store = ipa_vault
    """)

    setup_logging(debug=True, auditfile=None)
    config = {'authenticators': {'ipa': IPAInterface(parser, IPA_SECTIONNAME)}}
    vault = IPAVault(parser, 'store:ipa_vault')
    vault.finalize_init(config, parser, None)
    s = IPACertRequest(parser, 'store:ipa_certreq')
    s.store = vault
    s.finalize_init(config, parser, None)
    print(s.get('keys/HTTP/client1.ipa.example'))
    print(s.get('keys/HTTP/client1.ipa.example'))
    print(s.cut('keys/HTTP/client1.ipa.example'))
Beispiel #5
0
 def setup_method(self, method):
     self.parser = configparser.ConfigParser(
         interpolation=configparser.ExtendedInterpolation(), )
     self.parser.read_string(CONFIG)
     # config
     self.config = {
         'debug': False,
         'authenticators': {},
         'stores': {},
     }
     # mocked ipalib.api
     self.p_api = mock.patch('ipalib.api', autospec=ipalib.api)
     self.m_api = self.p_api.start()
     self.m_api.isdone.return_value = False
     self.m_api.env = mock.Mock()
     self.m_api.env.server = 'server.ipa.example'
     self.m_api.env.realm = u'IPA.EXAMPLE'
     self.m_api.Backend = mock.Mock()
     self.m_api.Command = mock.Mock()
     self.m_api.Command.ping.return_value = {
         u'summary': u'IPA server version 4.4.3. API version 2.215',
     }
     self.m_api.Command.vaultconfig_show.return_value = {
         u'result': {
             u'kra_server_server': [u'ipa.example'],
         }
     }
     # mocked get_principal
     self.p_get_principal = mock.patch(
         'custodia.ipa.interface.get_principal')
     self.m_get_principal = self.p_get_principal.start()
     self.m_get_principal.return_value = None
     # mocked environ (empty dict)
     self.p_env = mock.patch.dict('os.environ', clear=True)
     self.p_env.start()
Beispiel #6
0
 def setUpClass(cls):
     cls.parser = configparser.ConfigParser(
         interpolation=configparser.ExtendedInterpolation())
     cls.parser.read_string(CONFIG)
     cls.log_handlers = log.auditlog.logger.handlers[:]
     log.auditlog.logger.handlers = [logging.NullHandler()]
     cls.secrets = Secrets(cls.parser, 'authz:secrets')
     cls.secrets.root.store = SqliteStore(cls.parser, 'store:sqlite')
     cls.authz = UserNameSpace(cls.parser, 'authz:user')
Beispiel #7
0
def _parse_config(args, config):
    """Parse arguments and create basic configuration
    """
    defaults = {
        # Do not use getfqdn(). Internaly it calls gethostbyaddr which might
        # perform a DNS query.
        'hostname': socket.gethostname(),
    }

    parser = configparser.ConfigParser(
        interpolation=configparser.ExtendedInterpolation(), defaults=defaults)
    parser.optionxform = str

    with args.configfile as f:
        parser.read_file(f)

    for s in CONFIG_SPECIALS:
        config[s] = dict()

    # add env
    parser['ENV'] = {
        k: v.replace('$', '$$')
        for k, v in os.environ.items() if not set(v).intersection('\r\n\x00')
    }

    # parse globals first
    if parser.has_section('global'):
        for opt, val in parser.items('global'):
            if opt in CONFIG_SPECIALS:
                raise ValueError('"%s" is an invalid ' '[global] option' % opt)
            config[opt] = val

        config['tls_verify_client'] = parser.getboolean('global',
                                                        'tls_verify_client',
                                                        fallback=False)
        config['debug'] = parser.getboolean('global', 'debug', fallback=False)
        if args.debug:
            config['debug'] = True
        config['auditlog'] = os.path.abspath(
            config.get('auditlog', 'custodia.audit.log'))
        config['umask'] = int(config.get('umask', '027'), 8)

        url = config.get('server_url')
        sock = config.get('server_socket')
        if bool(url) == bool(sock):
            raise ValueError("Exactly one of 'server_url' or "
                             "'server_socket' is required.")
        if sock:
            server_socket = os.path.abspath(sock)
            config['server_url'] = 'http+unix://{}/'.format(
                url_escape(server_socket, ''))

    return parser
Beispiel #8
0
    def setUpClass(cls):
        cls.parser = configparser.ConfigParser(
            interpolation=configparser.ExtendedInterpolation())
        cls.parser.read_string(CONFIG)

        config = {'server_keys': test_keys[0]['kid']}
        with open('examples/client_enc.key') as f:
            data = f.read()
            cls.client_keys = json_decode(data)

        cls.kk = kem.KEMKeysStore(config)
        cls.kk.store = SqliteStore(cls.parser, 'store:sqlite')

        _store_keys(cls.kk.store, kem.KEY_USAGE_SIG, test_keys)
        _store_keys(cls.kk.store, kem.KEY_USAGE_ENC, test_keys)
        _store_keys(cls.kk.store, kem.KEY_USAGE_SIG, cls.client_keys)
        _store_keys(cls.kk.store, kem.KEY_USAGE_ENC, cls.client_keys)
    def setUpClass(cls):
        # Tests are depending on two existing and distinct users and groups.
        # We chose 'root' with uid/gid 0 and 'nobody', because both exist on
        # all relevant platforms. Tests use a mocked request so they run
        # under any user.
        cls.user = user = pwd.getpwnam('nobody')
        cls.group = group = grp.getgrgid(user.pw_gid)

        cls.parser = configparser.ConfigParser(
            interpolation=configparser.ExtendedInterpolation(),
            defaults={
                'other_uid': str(user.pw_uid),
                'other_username': user.pw_name,
                'other_gid': str(group.gr_gid),
                'other_groupname': group.gr_name,
            })
        cls.parser.read_string(CONFIG)
Beispiel #10
0
                                 cert[u'serial_number'], cert[u'subject'],
                                 cert[u'issuer'])
                ipa.Command.cert_revoke(
                    cert[u'serial_number'],
                    revocation_reason=self.revocation_reason,
                )
            return certs


if __name__ == '__main__':
    from custodia.compat import configparser
    from custodia.log import setup_logging
    from custodia.store.sqlite import SqliteStore

    parser = configparser.ConfigParser(
        interpolation=configparser.ExtendedInterpolation())
    parser.read_string(u"""
    [auth:ipa]
    handler = IPAInterface
    [store:sqlite]
    handler = SqliteStore
    dburi = /tmp/test.sqlite
    [store:ipa_certreq]
    handler = IPAVault
    backing_store = sqlite
    """)

    setup_logging(debug=True, auditfile=None)
    IPAInterface(parser, 'auth:ipa')
    s = IPACertRequest(parser, 'store:ipa_certreq')
    s.store = SqliteStore(parser, 'store:sqlite')
Beispiel #11
0
class CustodiaConfigParser(configparser.ConfigParser):
    """Python 3 like config parser with Custodia support.

    Example config::

        [custodia_client]
        url = https://custodia.example/secrets
        [example]
        password = test/key
        [interpolation]
        password = ${CUSTODIA:test/key}

    parser = CustodiaConfigParser()
    secret = parser.getsecret('example', 'password')
    secret = parser.get('interpolation', 'password')

    The Custodia client instance can either be passed to CustodiaConfigParser
    or loaded from the [custodia_client] section.

    """
    _DEFAULT_INTERPOLATION = configparser.ExtendedInterpolation()
    custodia_client_section = 'custodia_client'
    custodia_section = 'CUSTODIA'

    def __init__(self,
                 defaults=None,
                 dict_type=collections.OrderedDict,
                 allow_no_value=False,
                 custodia_client=None,
                 **kwargs):
        super(CustodiaConfigParser,
              self).__init__(defaults=defaults,
                             dict_type=dict_type,
                             allow_no_value=allow_no_value,
                             **kwargs)
        self._sections[self.custodia_section] = CustodiaMapping(self)
        self._custodia_client = custodia_client

    def __getitem__(self, key):
        item = super(CustodiaConfigParser, self).__getitem__(key)
        # wrap SectionProxy in CustodiaSectionProxy
        if not isinstance(item, CustodiaSectionProxy):
            item = CustodiaSectionProxy(item.parser, item.name)
            self._proxies[key] = item
        return item

    @property
    def custodia_client(self):
        if self._custodia_client is None:
            sec = self.custodia_client_section
            url = self.get(sec, 'url')
            client = CustodiaSimpleClient(url)
            headers = self.get(sec, 'headers', fallback=None)
            if headers:
                headers = json.loads(headers)
                client.headers.update(headers)
            tls_cafile = self.get(sec, 'tls_cafile', fallback=None)
            if tls_cafile:
                client.set_ca_cert(tls_cafile)
            certfile = self.get(sec, 'tls_certfile', fallback=None)
            keyfile = self.get(sec, 'tls_keyfile', fallback=None)
            if certfile:
                client.set_client_cert(certfile, keyfile)
            self._custodia_client = client

        return self._custodia_client

    def getsecret(self, section, option, **kwargs):
        """Get a secret from Custodia
        """
        # keyword-only arguments, vars and fallback are directly passed through
        raw = kwargs.get('raw', False)
        value = self.get(section, option, **kwargs)
        if raw:
            return value
        return self.custodia_client.get_secret(value)
Beispiel #12
0
def parser():
    parser = configparser.ConfigParser(
        interpolation=configparser.ExtendedInterpolation(),
    )
    parser.read_string(CONFIG)
    return parser