summaryrefslogtreecommitdiffstats
path: root/python/samba/netcmd/delegation.py
blob: 840be2088a322240e8aae0d9bf8912ee3b10658d (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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
# delegation management
#
# Copyright Matthieu Patou mat@samba.org 2010
# Copyright Stefan Metzmacher metze@samba.org 2011
# Copyright Bjoern Baumbach bb@sernet.de 2011
#
# 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
import ldb
from samba import provision
from samba import dsdb
from samba.samdb import SamDB
from samba.auth import system_session
from samba.dcerpc import security
from samba.ndr import ndr_pack, ndr_unpack
from samba.netcmd.common import _get_user_realm_domain
from samba.netcmd import (
    Command,
    CommandError,
    SuperCommand,
    Option
)


class cmd_delegation_show(Command):
    """Show the delegation setting of an account."""

    synopsis = "%prog <accountname> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "credopts": options.CredentialsOptions,
        "versionopts": options.VersionOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
               metavar="URL", dest="H"),
    ]

    takes_args = ["accountname"]

    def show_security_descriptor(self, sam, security_descriptor):
        dacl = security_descriptor.dacl
        desc_type = security_descriptor.type

        warning_info = ('Security Descriptor of attribute '
                        'msDS-AllowedToActOnBehalfOfOtherIdentity')

        if dacl is None or not desc_type & security.SEC_DESC_DACL_PRESENT:
            self.errf.write(f'Warning: DACL not present in {warning_info}!\n')
            return

        if not desc_type & security.SEC_DESC_SELF_RELATIVE:
            self.errf.write(f'Warning: DACL in {warning_info} lacks '
                            f'SELF_RELATIVE flag!\n')
            return

        first = True

        for ace in dacl.aces:
            trustee = ace.trustee

            # Convert the trustee SID into a DN if we can.
            try:
                res = sam.search(f'<SID={trustee}>',
                                 scope=ldb.SCOPE_BASE)
            except ldb.LdbError as err:
                num, _ = err.args
                if num != ldb.ERR_NO_SUCH_OBJECT:
                    raise
            else:
                if len(res) == 1:
                    trustee = res[0].dn

            ignore = False

            if (ace.type == security.SEC_ACE_TYPE_ACCESS_DENIED
                    or ace.type == security.SEC_ACE_TYPE_ACCESS_DENIED_OBJECT):
                self.errf.write(f'Warning: ACE in {warning_info} denies '
                                f'access for trustee {trustee}!\n')
                # Ignore the ACE if it denies access
                ignore = True
            elif (ace.type != security.SEC_ACE_TYPE_ACCESS_ALLOWED
                    and ace.type != security.SEC_ACE_TYPE_ACCESS_ALLOWED_OBJECT):
                # Ignore the ACE if it doesn't explicitly allow access
                ignore = True

            inherit_only = ace.flags & security.SEC_ACE_FLAG_INHERIT_ONLY
            object_inherit = ace.flags & security.SEC_ACE_FLAG_OBJECT_INHERIT
            container_inherit = (
                ace.flags & security.SEC_ACE_FLAG_CONTAINER_INHERIT)
            inherited_ace = ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE

            if inherit_only and not object_inherit and not container_inherit:
                # Ignore the ACE if it is propagated only to child objects, but
                # neither of the object and container inherit flags are set.
                ignore = True
            else:
                if container_inherit:
                    self.errf.write(f'Warning: ACE for trustee {trustee} has '
                                    f'unexpected CONTAINER_INHERIT flag set in '
                                    f'{warning_info}!\n')
                    ignore = True

                if inherited_ace:
                    self.errf.write(f'Warning: ACE for trustee {trustee} has '
                                    f'unexpected INHERITED_ACE flag set in '
                                    f'{warning_info}!\n')
                    ignore = True

            if not ace.access_mask:
                # Ignore the ACE if it doesn't grant any permissions.
                ignore = True

            if not ignore:
                if first:
                    self.outf.write('  Principals that may delegate to this '
                                    'account:\n')
                    first = False

                self.outf.write(f'msDS-AllowedToActOnBehalfOfOtherIdentity: '
                                f'{trustee}\n')


    def run(self, accountname, H=None, credopts=None, sambaopts=None, versionopts=None):
        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)
        paths = provision.provision_paths_from_lp(lp, lp.get("realm"))

        if H is None:
            path = paths.samdb
        else:
            path = H

        sam = SamDB(path, session_info=system_session(),
                    credentials=creds, lp=lp)
        # TODO once I understand how, use the domain info to naildown
        # to the correct domain
        (cleanedaccount, realm, domain) = _get_user_realm_domain(accountname,
                                                                 sam)

        res = sam.search(expression="sAMAccountName=%s" %
                         ldb.binary_encode(cleanedaccount),
                         scope=ldb.SCOPE_SUBTREE,
                         attrs=["userAccountControl", "msDS-AllowedToDelegateTo",
                                "msDS-AllowedToActOnBehalfOfOtherIdentity"])
        if len(res) == 0:
            raise CommandError("Unable to find account name '%s'" % accountname)
        assert(len(res) == 1)

        uac = int(res[0].get("userAccountControl")[0])
        allowed = res[0].get("msDS-AllowedToDelegateTo")
        allowed_from = res[0].get("msDS-AllowedToActOnBehalfOfOtherIdentity", idx=0)

        self.outf.write("Account-DN: %s\n" % str(res[0].dn))
        self.outf.write("UF_TRUSTED_FOR_DELEGATION: %s\n"
                        % bool(uac & dsdb.UF_TRUSTED_FOR_DELEGATION))
        self.outf.write("UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: %s\n" %
                        bool(uac & dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION))

        if allowed:
            self.outf.write("  Services this account may delegate to:\n")
            for a in allowed:
                self.outf.write("msDS-AllowedToDelegateTo: %s\n" % a)
        if allowed_from is not None:
            try:
                security_descriptor = ndr_unpack(security.descriptor, allowed_from)
            except RuntimeError:
                self.errf.write("Warning: Security Descriptor of attribute "
                                "msDS-AllowedToActOnBehalfOfOtherIdentity "
                                "could not be unmarshalled!\n")
            else:
                self.show_security_descriptor(sam, security_descriptor)


class cmd_delegation_for_any_service(Command):
    """Set/unset UF_TRUSTED_FOR_DELEGATION for an account."""

    synopsis = "%prog <accountname> [(on|off)] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "credopts": options.CredentialsOptions,
        "versionopts": options.VersionOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
               metavar="URL", dest="H"),
    ]

    takes_args = ["accountname", "onoff"]

    def run(self, accountname, onoff, H=None, credopts=None, sambaopts=None,
            versionopts=None):

        on = False
        if onoff == "on":
            on = True
        elif onoff == "off":
            on = False
        else:
            raise CommandError("invalid argument: '%s' (choose from 'on', 'off')" % onoff)

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)
        paths = provision.provision_paths_from_lp(lp, lp.get("realm"))
        if H is None:
            path = paths.samdb
        else:
            path = H

        sam = SamDB(path, session_info=system_session(),
                    credentials=creds, lp=lp)
        # TODO once I understand how, use the domain info to naildown
        # to the correct domain
        (cleanedaccount, realm, domain) = _get_user_realm_domain(accountname,
                                                                 sam)

        search_filter = "sAMAccountName=%s" % ldb.binary_encode(cleanedaccount)
        flag = dsdb.UF_TRUSTED_FOR_DELEGATION
        try:
            sam.toggle_userAccountFlags(search_filter, flag,
                                        flags_str="Trusted-for-Delegation",
                                        on=on, strict=True)
        except Exception as err:
            raise CommandError(err)


class cmd_delegation_for_any_protocol(Command):
    """Set/unset UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION (S4U2Proxy) for an account."""

    synopsis = "%prog <accountname> [(on|off)] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "credopts": options.CredentialsOptions,
        "versionopts": options.VersionOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
               metavar="URL", dest="H"),
    ]

    takes_args = ["accountname", "onoff"]

    def run(self, accountname, onoff, H=None, credopts=None, sambaopts=None,
            versionopts=None):

        on = False
        if onoff == "on":
            on = True
        elif onoff == "off":
            on = False
        else:
            raise CommandError("invalid argument: '%s' (choose from 'on', 'off')" % onoff)

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp, fallback_machine=True)
        paths = provision.provision_paths_from_lp(lp, lp.get("realm"))
        if H is None:
            path = paths.samdb
        else:
            path = H

        sam = SamDB(path, session_info=system_session(),
                    credentials=creds, lp=lp)
        # TODO once I understand how, use the domain info to naildown
        # to the correct domain
        (cleanedaccount, realm, domain) = _get_user_realm_domain(accountname,
                                                                 sam)

        search_filter = "sAMAccountName=%s" % ldb.binary_encode(cleanedaccount)
        flag = dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
        try:
            sam.toggle_userAccountFlags(search_filter, flag,
                                        flags_str="Trusted-to-Authenticate-for-Delegation",
                                        on=on, strict=True)
        except Exception as err:
            raise CommandError(err)


class cmd_delegation_add_service(Command):
    """Add a service principal to msDS-AllowedToDelegateTo so that an account may delegate to it."""

    synopsis = "%prog <accountname> <principal> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "credopts": options.CredentialsOptions,
        "versionopts": options.VersionOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
               metavar="URL", dest="H"),
    ]

    takes_args = ["accountname", "principal"]

    def run(self, accountname, principal, H=None, credopts=None, sambaopts=None,
            versionopts=None):

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)
        paths = provision.provision_paths_from_lp(lp, lp.get("realm"))
        if H is None:
            path = paths.samdb
        else:
            path = H

        sam = SamDB(path, session_info=system_session(),
                    credentials=creds, lp=lp)
        # TODO once I understand how, use the domain info to naildown
        # to the correct domain
        (cleanedaccount, realm, domain) = _get_user_realm_domain(accountname,
                                                                 sam)

        res = sam.search(expression="sAMAccountName=%s" %
                         ldb.binary_encode(cleanedaccount),
                         scope=ldb.SCOPE_SUBTREE,
                         attrs=["msDS-AllowedToDelegateTo"])
        if len(res) == 0:
            raise CommandError("Unable to find account name '%s'" % accountname)
        assert(len(res) == 1)

        msg = ldb.Message()
        msg.dn = res[0].dn
        msg["msDS-AllowedToDelegateTo"] = ldb.MessageElement([principal],
                                                             ldb.FLAG_MOD_ADD,
                                                             "msDS-AllowedToDelegateTo")
        try:
            sam.modify(msg)
        except Exception as err:
            raise CommandError(err)


class cmd_delegation_del_service(Command):
    """Delete a service principal from msDS-AllowedToDelegateTo so that an account may no longer delegate to it."""

    synopsis = "%prog <accountname> <principal> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "credopts": options.CredentialsOptions,
        "versionopts": options.VersionOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server", type=str,
               metavar="URL", dest="H"),
    ]

    takes_args = ["accountname", "principal"]

    def run(self, accountname, principal, H=None, credopts=None, sambaopts=None,
            versionopts=None):

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)
        paths = provision.provision_paths_from_lp(lp, lp.get("realm"))
        if H is None:
            path = paths.samdb
        else:
            path = H

        sam = SamDB(path, session_info=system_session(),
                    credentials=creds, lp=lp)
        # TODO once I understand how, use the domain info to naildown
        # to the correct domain
        (cleanedaccount, realm, domain) = _get_user_realm_domain(accountname,
                                                                 sam)

        res = sam.search(expression="sAMAccountName=%s" %
                         ldb.binary_encode(cleanedaccount),
                         scope=ldb.SCOPE_SUBTREE,
                         attrs=["msDS-AllowedToDelegateTo"])
        if len(res) == 0:
            raise CommandError("Unable to find account name '%s'" % accountname)
        assert(len(res) == 1)

        msg = ldb.Message()
        msg.dn = res[0].dn
        msg["msDS-AllowedToDelegateTo"] = ldb.MessageElement([principal],
                                                             ldb.FLAG_MOD_DELETE,
                                                             "msDS-AllowedToDelegateTo")
        try:
            sam.modify(msg)
        except Exception as err:
            raise CommandError(err)


class cmd_delegation_add_principal(Command):
    """Add a principal to msDS-AllowedToActOnBehalfOfOtherIdentity that may delegate to an account."""

    synopsis = "%prog <accountname> <principal> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "credopts": options.CredentialsOptions,
        "versionopts": options.VersionOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server",
               type=str, metavar="URL", dest="H"),
    ]

    takes_args = ["accountname", "principal"]

    def run(self, accountname, principal, H=None, credopts=None, sambaopts=None,
            versionopts=None):

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)
        paths = provision.provision_paths_from_lp(lp, lp.get("realm"))
        if H is None:
            path = paths.samdb
        else:
            path = H

        sam = SamDB(path, session_info=system_session(),
                    credentials=creds, lp=lp)
        # TODO once I understand how, use the domain info to naildown
        # to the correct domain
        cleanedaccount, _, _ = _get_user_realm_domain(accountname, sam)

        account_res = sam.search(
            expression="sAMAccountName=%s" %
            ldb.binary_encode(cleanedaccount),
            scope=ldb.SCOPE_SUBTREE,
            attrs=["msDS-AllowedToActOnBehalfOfOtherIdentity"])
        if len(account_res) == 0:
            raise CommandError(f"Unable to find account name '{accountname}'")
        assert(len(account_res) == 1)

        data = account_res[0].get(
            "msDS-AllowedToActOnBehalfOfOtherIdentity", idx=0)
        if data is None:
            # Create the security descriptor if it is not present.
            owner_sid = security.dom_sid(security.SID_BUILTIN_ADMINISTRATORS)

            security_desc = security.descriptor()
            security_desc.revision = security.SD_REVISION
            security_desc.type = (security.SEC_DESC_DACL_PRESENT |
                                  security.SEC_DESC_SELF_RELATIVE)
            security_desc.owner_sid = owner_sid

            dacl = None
        else:
            try:
                security_desc = ndr_unpack(security.descriptor, data)
            except RuntimeError:
                raise CommandError(f"Security Descriptor of attribute "
                                   f"msDS-AllowedToActOnBehalfOfOtherIdentity "
                                   f"for account '{accountname}' could not be "
                                   f"unmarshalled!")

            dacl = security_desc.dacl

        if dacl is None:
            # Create the DACL if it is not present.
            dacl = security.acl()
            dacl.revision = security.SECURITY_ACL_REVISION_ADS
            dacl.num_aces = 0

        # TODO once I understand how, use the domain info to naildown
        # to the correct domain
        cleanedprinc, _, _ = _get_user_realm_domain(principal, sam)

        princ_res = sam.search(expression="sAMAccountName=%s" %
                               ldb.binary_encode(cleanedprinc),
                               scope=ldb.SCOPE_SUBTREE,
                               attrs=["objectSid"])
        if len(princ_res) == 0:
            raise CommandError(f"Unable to find principal name '{principal}'")
        assert(len(princ_res) == 1)

        princ_sid = security.dom_sid(
            sam.schema_format_value(
                "objectSID",
                princ_res[0].get("objectSID", idx=0)).decode("utf-8"))

        aces = dacl.aces

        # Check that there is no existing ACE for this principal.
        if any(ace.trustee == princ_sid for ace in aces):
            raise CommandError(
                f"ACE for principal '{principal}' already present in Security "
                f"Descriptor of attribute "
                f"msDS-AllowedToActOnBehalfOfOtherIdentity for account "
                f"'{accountname}'.")

        # Create the new ACE.
        ace = security.ace()
        ace.type = security.SEC_ACE_TYPE_ACCESS_ALLOWED
        ace.flags = 0
        ace.access_mask = security.SEC_ADS_GENERIC_ALL
        ace.trustee = princ_sid

        aces.append(ace)

        dacl.aces = aces
        dacl.num_aces += 1

        security_desc.dacl = dacl

        new_data = ndr_pack(security_desc)

        # Set the new security descriptor. First, delete the original value to
        # detect a race condition if someone else updates the attribute at the
        # same time.
        msg = ldb.Message()
        msg.dn = account_res[0].dn
        if data is not None:
            msg["0"] = ldb.MessageElement(
                data, ldb.FLAG_MOD_DELETE,
                "msDS-AllowedToActOnBehalfOfOtherIdentity")
        msg["1"] = ldb.MessageElement(
            new_data, ldb.FLAG_MOD_ADD,
            "msDS-AllowedToActOnBehalfOfOtherIdentity")
        try:
            sam.modify(msg)
        except ldb.LdbError as err:
            num, _ = err.args
            if num == ldb.ERR_NO_SUCH_ATTRIBUTE:
                raise CommandError(
                    f"Refused to update attribute "
                    f"msDS-AllowedToActOnBehalfOfOtherIdentity for account "
                    f"'{accountname}': a conflicting attribute update "
                    f"occurred simultaneously.")
            else:
                raise CommandError(err)


class cmd_delegation_del_principal(Command):
    """Delete a principal from msDS-AllowedToActOnBehalfOfOtherIdentity that may no longer delegate to an account."""

    synopsis = "%prog <accountname> <principal> [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "credopts": options.CredentialsOptions,
        "versionopts": options.VersionOptions,
    }

    takes_options = [
        Option("-H", "--URL", help="LDB URL for database or target server",
               type=str, metavar="URL", dest="H"),
    ]

    takes_args = ["accountname", "principal"]

    def run(self, accountname, principal, H=None, credopts=None, sambaopts=None,
            versionopts=None):

        lp = sambaopts.get_loadparm()
        creds = credopts.get_credentials(lp)
        paths = provision.provision_paths_from_lp(lp, lp.get("realm"))
        if H is None:
            path = paths.samdb
        else:
            path = H

        sam = SamDB(path, session_info=system_session(),
                    credentials=creds, lp=lp)
        # TODO once I understand how, use the domain info to naildown
        # to the correct domain
        cleanedaccount, _, _ = _get_user_realm_domain(accountname, sam)

        account_res = sam.search(
            expression="sAMAccountName=%s" %
            ldb.binary_encode(cleanedaccount),
            scope=ldb.SCOPE_SUBTREE,
            attrs=["msDS-AllowedToActOnBehalfOfOtherIdentity"])
        if len(account_res) == 0:
            raise CommandError("Unable to find account name '%s'" % accountname)
        assert(len(account_res) == 1)

        data = account_res[0].get(
            "msDS-AllowedToActOnBehalfOfOtherIdentity", idx=0)
        if data is None:
            raise CommandError(f"Attribute "
                               f"msDS-AllowedToActOnBehalfOfOtherIdentity for "
                               f"account '{accountname}' not present!")

        try:
            security_desc = ndr_unpack(security.descriptor, data)
        except RuntimeError:
            raise CommandError(f"Security Descriptor of attribute "
                               f"msDS-AllowedToActOnBehalfOfOtherIdentity for "
                               f"account '{accountname}' could not be "
                               f"unmarshalled!")

        dacl = security_desc.dacl
        if dacl is None:
            raise CommandError(f"DACL not present on Security Descriptor of "
                               f"attribute "
                               f"msDS-AllowedToActOnBehalfOfOtherIdentity for "
                               f"account '{accountname}'!")

        # TODO once I understand how, use the domain info to naildown
        # to the correct domain
        cleanedprinc, _, _ = _get_user_realm_domain(principal, sam)

        princ_res = sam.search(expression="sAMAccountName=%s" %
                               ldb.binary_encode(cleanedprinc),
                               scope=ldb.SCOPE_SUBTREE,
                               attrs=["objectSid"])
        if len(princ_res) == 0:
            raise CommandError(f"Unable to find principal name '{principal}'")
        assert(len(princ_res) == 1)

        princ_sid = security.dom_sid(
            sam.schema_format_value(
                "objectSID",
                princ_res[0].get("objectSID", idx=0)).decode("utf-8"))

        old_aces = dacl.aces

        # Remove any ACEs relating to the specified principal.
        aces = [ace for ace in old_aces if ace.trustee != princ_sid]

        # Raise an error if we didn't find any.
        if len(aces) == len(old_aces):
            raise CommandError(f"Unable to find ACE for principal "
                               f"'{principal}' in Security Descriptor of "
                               f"attribute "
                               f"msDS-AllowedToActOnBehalfOfOtherIdentity for "
                               f"account '{accountname}'.")

        dacl.num_aces = len(aces)
        dacl.aces = aces

        security_desc.dacl = dacl

        new_data = ndr_pack(security_desc)

        # Set the new security descriptor. First, delete the original value to
        # detect a race condition if someone else updates the attribute at the
        # same time.
        msg = ldb.Message()
        msg.dn = account_res[0].dn
        msg["0"] = ldb.MessageElement(
            data, ldb.FLAG_MOD_DELETE,
            "msDS-AllowedToActOnBehalfOfOtherIdentity")
        msg["1"] = ldb.MessageElement(
            new_data, ldb.FLAG_MOD_ADD,
            "msDS-AllowedToActOnBehalfOfOtherIdentity")
        try:
            sam.modify(msg)
        except ldb.LdbError as err:
            num, _ = err.args
            if num == ldb.ERR_NO_SUCH_ATTRIBUTE:
                raise CommandError(
                    f"Refused to update attribute "
                    f"msDS-AllowedToActOnBehalfOfOtherIdentity for account "
                    f"'{accountname}': a conflicting attribute update "
                    f"occurred simultaneously.")
            else:
                raise CommandError(err)


class cmd_delegation(SuperCommand):
    """Delegation management."""

    subcommands = {}
    subcommands["show"] = cmd_delegation_show()
    subcommands["for-any-service"] = cmd_delegation_for_any_service()
    subcommands["for-any-protocol"] = cmd_delegation_for_any_protocol()
    subcommands["add-service"] = cmd_delegation_add_service()
    subcommands["del-service"] = cmd_delegation_del_service()
    subcommands["add-principal"] = cmd_delegation_add_principal()
    subcommands["del-principal"] = cmd_delegation_del_principal()