summaryrefslogtreecommitdiff
path: root/python/samba/netcmd/domain/kds/root_key.py
blob: f375c0d6c04e96df395785803f69a964796ba28e (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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# Unix SMB/CIFS implementation.
#
# samba-tool commands for Key Distribution Services
#
# Copyright © Catalyst.Net Ltd. 2024
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import samba.getopt as options
from ldb import SCOPE_SUBTREE
from samba.netcmd import Command, CommandError, Option, SuperCommand
from samba.dcerpc import misc
from ldb import MessageElement, LdbError
from samba import string_is_guid


from samba.nt_time import (string_from_nt_time,
                           nt_time_from_string,
                           nt_now,
                           timedelta_from_nt_time_delta)


def root_key_base_dn(ldb):
    base_dn = ldb.get_config_basedn()
    base_dn.add_child(
        "CN=Master Root Keys,CN=Group Key Distribution Service,CN=Services")
    return base_dn


def get_root_key_by_name_or_dn(ldb, name, attrs=None):
    if string_is_guid(str(name)):
        key = 'name'
    else:
        key = 'dn'

    if attrs is None:
        attrs = ['*']

    base_dn = root_key_base_dn(ldb)

    expression = ("(&(objectClass = msKds-ProvRootKey)"
                  f"({key} = {name}))")

    res = ldb.search(base_dn,
                     scope=SCOPE_SUBTREE,
                     expression=expression,
                     attrs=attrs)

    if len(res) == 0:
        raise CommandError(f"no such root key: {name}")
    if len(res) != 1:
        # the database is in a sorry state
        raise CommandError(f"duplicate root keys matching {name}")

    return res[0]


def get_sorted_root_keys(ldb, attrs=None, n=None):
    if attrs is None:
        attrs = ['*']

    base_dn = root_key_base_dn(ldb)

    res = ldb.search(base_dn,
                     scope=SCOPE_SUBTREE,
                     expression="(objectClass = msKds-ProvRootKey)",
                     attrs=attrs,
                     controls=["server_sort:1:1:msKds-UseStartTime"])

    return res


def delta_string(d):
    """Turn a datetime.timedelta into an approximate string."""
    td = timedelta_from_nt_time_delta(d)
    secs = td.total_seconds()
    absolute = abs(secs)
    if absolute < 2:
        return 'about now'
    s = 'about '
    if absolute < 120:
        s += f'{int(absolute)} seconds'
    elif absolute < 7200:
        s += f'{int(absolute / 60)} minutes'
    elif absolute < 48 * 3600:
        s += f'{int(absolute / 3600)} hours'
    else:
        s += f'{int(absolute / (24 * 3600))} days'

    if secs <= 0:
        s += ' ago'
    else:
        s += ' in the FUTURE'

    return s


# These next ridiculously simple looking functions are for the
# ENCODERS mapping below.

def guid_to_string(v):
    return str(misc.GUID(v))


def string_from_nt_time_string(nt_time):
    nt_time = int(nt_time)
    return string_from_nt_time(nt_time)


# ENCODERS is a mapping of attribute names to encoding functions for
# the corresponding values. Anything not mentioned will go through
# str(), which for MessageElements is the same as bytes.decode().
ENCODERS = {
    "msKds-UseStartTime": string_from_nt_time_string,
    "msKds-CreateTime": string_from_nt_time_string,
    "msKds-RootKeyData": bytes.hex,
    "msKds-SecretAgreementParam": bytes.hex,
    "objectGUID": guid_to_string,
    "msKds-KDFParam": bytes.hex,
    "msKds-PublicKeyLength": int,
    "msKds-PrivateKeyLength": int,
    "msKds-Version": int,
}


def encode_by_key(k, v):
    """Convert an attribute into a printable form, using the attribute
    name to guess the best format."""
    fn = ENCODERS.get(k, lambda x: str(x))

    if not isinstance(v, MessageElement):  # probably Dn
        return fn(v)

    if len(v) == 1:
        return fn(v[0])

    return [fn(x) for x in v]


# these attributes we normally want to show. 'name' is a GUID string
# (and has the same value as cn, the rdn).
BASE_ATTRS = ["name",
              "msKds-UseStartTime",
              "msKds-CreateTime",
              ]

# these attributes are secret, and also pretty opaque and useless to
# look at (unless you want to steal the secret).
SECRET_ATTRS = ["msKds-RootKeyData",
                "msKds-SecretAgreementParam"]

# these are things you might want to look at, but  generally don't.
VERBOSE_ATTRS = ["whenCreated",
                 "whenChanged",
                 "objectGUID",
                 "msKds-KDFAlgorithmID",
                 "msKds-KDFParam",
                 "msKds-SecretAgreementAlgorithmID",
                 "msKds-PublicKeyLength",
                 "msKds-PrivateKeyLength",
                 "msKds-Version",
                 "msKds-DomainID",
                 "cn",
                 ]


class RootKeyCommand(Command):
    """Base class with a common method for presenting root key data."""
    def show_root_key_message(self, msg,
                              output_format=None,
                              show_secrets=False,
                              preamble=None,
                              now=None):
        if output_format == 'json':
            out = {}
            if preamble is not None:
                out['message'] = preamble
            for k, v in msg.items():
                if not show_secrets and k in SECRET_ATTRS:
                    continue
                out[k] = encode_by_key(k, v)
            self.print_json(out)
            return

        if now is None:
            now = nt_now()
        create_time = int(msg['msKds-createTime'][0])
        start_time = int(msg['msKds-UseStartTime'][0])
        create_delta_string = delta_string(create_time - now)
        start_delta_string = delta_string(start_time - now)

        if preamble is not None:
            self.message(preamble)

        self.message(f"name {msg['name']}")
        self.message(f"   created        {string_from_nt_time(create_time)} ({create_delta_string})")
        self.message(f"   usable from    {string_from_nt_time(start_time)} ({start_delta_string})")

        if show_secrets:
            for k in SECRET_ATTRS:
                v = msg[k][0].hex()
                self.message(f"   {k:14} {v}")

        remaining_keys = [k for k in msg if k not in BASE_ATTRS + SECRET_ATTRS]

        for k in remaining_keys:
            v = encode_by_key(k, msg[k])
            self.message(f"   {k:14} {v}")

        self.message('')


class cmd_domain_kds_root_key_create(RootKeyCommand):
    """Create a KDS root key object."""

    synopsis = "%prog [-H <URL>] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "credopts": options.CredentialsOptions,
        "hostopts": options.HostOptions,
    }

    takes_options = [
        Option("--json", help="Output results in JSON format.",
               dest="output_format", action="store_const", const="json"),
        Option("--use-start-time", help="Use of the key begins at this time."),
        Option("-v", "--verbose", help="Be verbose", action="store_true"),
    ]

    def run(self, hostopts=None, sambaopts=None, credopts=None,
            output_format=None, use_start_time=None, verbose=None):
        kwargs = {}
        if use_start_time is not None:
            try:
                nt_use = nt_time_from_string(use_start_time)
                kwargs['use_start_time'] = nt_use
            except ValueError as e:
                raise CommandError(e) from None

        ldb = self.ldb_connect(hostopts, sambaopts, credopts)
        dn = ldb.new_gkdi_root_key(**kwargs)
        guid = dn.get_rdn_value()

        attrs = BASE_ATTRS[:]
        if verbose:
            attrs += VERBOSE_ATTRS

        msg = get_root_key_by_name_or_dn(ldb, guid, attrs=attrs)
        start_time = int(msg['msKds-UseStartTime'][0])
        used_from_string = (f"usable from {string_from_nt_time(start_time)} "
                            f"({delta_string(start_time - nt_now())})")

        message = f"created root key {guid}, {used_from_string}"

        if verbose:
            self.show_root_key_message(msg,
                                       output_format,
                                       preamble=f"{message}\n")

        elif output_format == 'json':
            kwargs = {k: msg[k] for k in attrs}
            self.print_json_status(message=message, dn=str(dn), **kwargs)
        else:
            self.message(message)


class cmd_domain_kds_root_key_delete(RootKeyCommand):
    """Delete a KDS root key."""

    synopsis = "%prog [-H <URL>] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "credopts": options.CredentialsOptions,
        "hostopts": options.HostOptions,
    }

    takes_options = [
        Option("--name", help="The key to delete"),
        Option("--json", help="Output results in JSON format.",
               dest="output_format", action="store_const", const="json"),
    ]

    def run(self, hostopts=None, sambaopts=None, credopts=None, name=None, output_format=None):
        ldb = self.ldb_connect(hostopts, sambaopts, credopts)
        try:
            root_key = get_root_key_by_name_or_dn(ldb, name)
        except LdbError as e:
            raise CommandError(e)

        ldb.delete(root_key.dn)

        guid = root_key.dn.get_rdn_value()
        message = f"deleted root key {guid}"

        if output_format == 'json':
            self.print_json_status(message)
        else:
            self.message(message)


class cmd_domain_kds_root_key_list(RootKeyCommand):
    """List KDS root keys."""

    synopsis = "%prog [-H <URL>] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "credopts": options.CredentialsOptions,
        "hostopts": options.HostOptions,
    }

    takes_options = [
        Option("-v", "--verbose", help="Be verbose", action="store_true"),
        Option("--show-secrets", help="Show root key hash", action="store_true"),
        Option("--json", help="Output results in JSON format.",
               dest="output_format", action="store_const", const="json"),
    ]

    def run(self, hostopts=None, sambaopts=None, credopts=None, verbose=None,
            show_secrets=None, output_format=None):
        ldb = self.ldb_connect(hostopts, sambaopts, credopts)

        attrs = BASE_ATTRS[:]

        if show_secrets:
            attrs += SECRET_ATTRS

        if verbose:
            attrs += VERBOSE_ATTRS

        res = get_sorted_root_keys(ldb, attrs)

        if output_format == 'json':
            out = []
            for msg in res.msgs:
                m = {}
                out.append(m)
                for k, v in msg.items():
                    m[k] = encode_by_key(k, v)

            self.print_json(out)
            return

        if len(res) == 0:
            self.message("no root keys found.")
            return

        self.message(f"{len(res)} root key{'s' if len(res) > 1 else ''} found.\n")

        now = nt_now()
        for msg in res:
            self.show_root_key_message(msg,
                                       output_format,
                                       show_secrets=show_secrets,
                                       now=now)
            self.message('')


class cmd_domain_kds_root_key_view(RootKeyCommand):
    """View a root key object."""

    synopsis = "%prog [-H <URL>] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "credopts": options.CredentialsOptions,
        "hostopts": options.HostOptions,
    }

    takes_options = [
        Option("--name", help="Choose thhe key to view (by GUID)"),
        Option("--latest", help="View the latest key", action="store_true"),
        Option("-v", "--verbose", help="Be verbose", action="store_true"),
        Option("--show-secrets", help="Show root key hash", action="store_true"),
        Option("--json", help="Output results in JSON format.",
               dest="output_format", action="store_const", const="json"),
    ]

    def run(self, hostopts=None, sambaopts=None, credopts=None,
            name=None, output_format=None, show_secrets=None, verbose=None,
            latest=None):
        ldb = self.ldb_connect(hostopts, sambaopts, credopts)

        # The default behaviour is to show quite a lot of information,
        # equal to that seen with `list --verbose`, but leaving out
        # uninteresting attributes like "showInAdvancedViewOnly" and
        # tautological ones like "objectClass".
        #
        #  <no extra flags>          -> selected attributes
        #  --show-secrets            -> selected attributes and secrets
        #  --verbose                 -> all attributes EXCEPT secrets
        #  --verbose --show-secrets  -> all attributes
        attrs = BASE_ATTRS + VERBOSE_ATTRS
        if show_secrets:
            attrs += SECRET_ATTRS
        if verbose:
            attrs += ["*"]

        if latest:
            if name is not None:
                raise CommandError("It makes no sense to combine --name and --latest")
            res = get_sorted_root_keys(ldb, attrs)
            if len(res) == 0:
                raise CommandError("no root keys found")
            msg = res[0]

        elif name is not None:
            msg = get_root_key_by_name_or_dn(ldb, name, attrs)
        else:
            raise CommandError("PLease use '--name <GUID>' or '--latest' "
                               " (try the 'list' command to find names)")

        self.show_root_key_message(msg,
                                   output_format,
                                   show_secrets=show_secrets)


class cmd_domain_kds_root_key(SuperCommand):
    """Manage key distribution service root keys."""

    subcommands = {
        "create": cmd_domain_kds_root_key_create(),
        "delete": cmd_domain_kds_root_key_delete(),
        "list": cmd_domain_kds_root_key_list(),
        "view": cmd_domain_kds_root_key_view(),
    }