summaryrefslogtreecommitdiffstats
path: root/ipaserver/secrets/store.py
blob: b40008c182e47846fc70adf1b304748e5f408055 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# Copyright (C) 2015  IPA Project Contributors, see COPYING for license

from __future__ import print_function, absolute_import
import os
import sys

from custodia.plugin import CSStore

from ipaplatform.paths import paths
from ipaplatform.constants import constants
from ipapython import ipautil


class UnknownKeyName(Exception):
    pass


class DBMAPHandler:
    dbtype = None

    def __init__(self, config, dbmap, nickname):
        dbtype = dbmap.get('type')
        if dbtype is None or dbtype != self.dbtype:
            raise ValueError(
                "Invalid type '{}', expected '{}'".format(
                    dbtype, self.dbtype
                )
            )
        self.config = config
        self.dbmap = dbmap
        self.nickname = nickname

    def export_key(self):
        raise NotImplementedError

    def import_key(self, value):
        raise NotImplementedError


class DBMAPCommandHandler(DBMAPHandler):
    def __init__(self, config, dbmap, nickname):
        super().__init__(config, dbmap, nickname)
        self.runas = dbmap.get('runas')
        self.command = os.path.join(
            paths.IPA_CUSTODIA_HANDLER,
            dbmap['command']
        )

    def run_handler(self, extra_args=(), stdin=None):
        """Run handler script to export / import key material
        """
        args = [self.command]
        args.extend(extra_args)
        kwargs = dict(
            runas=self.runas,
            encoding='utf-8',
        )

        if stdin:
            args.extend(['--import', '-'])
            kwargs.update(stdin=stdin)
        else:
            args.extend(['--export', '-'])
            kwargs.update(capture_output=True)

        result = ipautil.run(args, **kwargs)

        if stdin is None:
            return result.output
        else:
            return None


def log_error(error):
    print(error, file=sys.stderr)


class NSSWrappedCertDB(DBMAPCommandHandler):
    """
    Store that extracts private keys from an NSSDB, wrapped with the
    private key of the primary CA.
    """
    dbtype = 'NSSDB'

    def export_key(self):
        return self.run_handler(['--nickname', self.nickname])


class NSSCertDB(DBMAPCommandHandler):
    dbtype = 'NSSDB'

    def export_key(self):
        return self.run_handler(['--nickname', self.nickname])

    def import_key(self, value):
        return self.run_handler(
            ['--nickname', self.nickname],
            stdin=value
        )


# Exfiltrate the DM password Hash so it can be set in replica's and this
# way let a replica be install without knowing the DM password and yet
# still keep the DM password synchronized across replicas
class DMLDAP(DBMAPCommandHandler):
    dbtype = 'DMLDAP'

    def __init__(self, config, dbmap, nickname):
        super().__init__(config, dbmap, nickname)
        if nickname != 'DMHash':
            raise UnknownKeyName("Unknown Key Named '%s'" % nickname)

    def export_key(self):
        return self.run_handler()

    def import_key(self, value):
        self.run_handler(stdin=value)


class PEMFileHandler(DBMAPCommandHandler):
    dbtype = 'PEM'

    def export_key(self):
        return self.run_handler()

    def import_key(self, value):
        return self.run_handler(stdin=value)


NAME_DB_MAP = {
    'ca': {
        'type': 'NSSDB',
        'handler': NSSCertDB,
        'command': 'ipa-custodia-pki-tomcat',
        'runas': constants.PKI_USER,
    },
    'ca_wrapped': {
        'type': 'NSSDB',
        'handler': NSSWrappedCertDB,
        'command': 'ipa-custodia-pki-tomcat-wrapped',
        'runas': constants.PKI_USER,
    },
    'ra': {
        'type': 'PEM',
        'handler': PEMFileHandler,
        'command': 'ipa-custodia-ra-agent',
        'runas': None,  # import needs root permission to write to directory
    },
    'dm': {
        'type': 'DMLDAP',
        'handler': DMLDAP,
        'command': 'ipa-custodia-dmldap',
        'runas': None,  # root
    }
}


class IPASecStore(CSStore):

    def __init__(self, config=None):
        self.config = config

    def _get_handler(self, key):
        path = key.split('/', 3)
        if len(path) != 3 or path[0] != 'keys':
            raise ValueError('Invalid name')
        if path[1] not in NAME_DB_MAP:
            raise UnknownKeyName("Unknown DB named '%s'" % path[1])
        dbmap = NAME_DB_MAP[path[1]]
        return dbmap['handler'](self.config, dbmap, path[2])

    def get(self, key):
        try:
            key_handler = self._get_handler(key)
            value = key_handler.export_key()
        except Exception as e:  # pylint: disable=broad-except
            log_error('Error retrieving key "%s": %s' % (key, str(e)))
            value = None
        return value

    def set(self, key, value, replace=False):
        try:
            key_handler = self._get_handler(key)
            key_handler.import_key(value)
        except Exception as e:  # pylint: disable=broad-except
            log_error('Error storing key "%s": %s' % (key, str(e)))

    def list(self, keyfilter=None):
        raise NotImplementedError

    def cut(self, key):
        raise NotImplementedError

    def span(self, key):
        raise NotImplementedError


# backwards compatibility with FreeIPA 4.3 and 4.4.
iSecStore = IPASecStore