summaryrefslogtreecommitdiff
path: root/python/samba/netcmd/domain/auth/silo/silo.py
blob: 2963ede64d41b31d0d291ea730d82d439d58de14 (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
# Unix SMB/CIFS implementation.
#
# authentication silos - authentication silo management
#
# Copyright (C) Catalyst.Net Ltd. 2023
#
# Written by Rob van der Linde <rob@catalyst.net.nz>
#
# 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 samba.domain.models import AuthenticationPolicy, AuthenticationSilo
from samba.domain.models.exceptions import ModelError
from samba.netcmd import Command, CommandError, Option


class cmd_domain_auth_silo_list(Command):
    """List authentication silos on the domain."""

    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"),
    ]

    def run(self, hostopts=None, sambaopts=None, credopts=None,
            output_format=None):

        ldb = self.ldb_connect(hostopts, sambaopts, credopts)

        try:
            silos = AuthenticationSilo.query(ldb)
        except ModelError as e:
            raise CommandError(e)

        # Using json output format gives more detail.
        if output_format == "json":
            self.print_json({silo.name: silo for silo in silos})
        else:
            for silo in silos:
                print(silo.name, file=self.outf)


class cmd_domain_auth_silo_view(Command):
    """View an authentication silo on the domain."""

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

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

    takes_options = [
        Option("--name",
               help="Name of authentication silo to view (required).",
               dest="name", action="store", type=str, required=True),
    ]

    def run(self, hostopts=None, sambaopts=None, credopts=None, name=None):

        ldb = self.ldb_connect(hostopts, sambaopts, credopts)

        try:
            silo = AuthenticationSilo.get(ldb, cn=name)
        except ModelError as e:
            raise CommandError(e)

        # Check if silo exists first.
        if silo is None:
            raise CommandError(f"Authentication silo {name} not found.")

        # Display silo as JSON.
        self.print_json(silo.as_dict())


class cmd_domain_auth_silo_create(Command):
    """Create a new authentication silo on the domain."""

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

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

    takes_options = [
        Option("--name", help="Name of authentication silo (required).",
               dest="name", action="store", type=str, required=True),
        Option("--description",
               help="Optional description for authentication silo.",
               dest="description", action="store", type=str),
        Option("--user-authentication-policy",
               help="User account authentication policy.",
               dest="user_authentication_policy", action="store", type=str,
               metavar="USER_POLICY"),
        Option("--service-authentication-policy",
               help="Managed service account authentication policy.",
               dest="service_authentication_policy", action="store", type=str,
               metavar="SERVICE_POLICY"),
        Option("--computer-authentication-policy",
               help="Computer authentication policy.",
               dest="computer_authentication_policy", action="store", type=str,
               metavar="COMPUTER_POLICY"),
        Option("--protect",
               help="Protect authentication silo from accidental deletion.",
               dest="protect", action="store_true"),
        Option("--unprotect",
               help="Unprotect authentication silo from accidental deletion.",
               dest="unprotect", action="store_true"),
        Option("--audit",
               help="Only audit silo policies.",
               dest="audit", action="store_true"),
        Option("--enforce",
               help="Enforce silo policies.",
               dest="enforce", action="store_true")
    ]

    @staticmethod
    def get_policy(ldb, name):
        """Helper function to fetch auth policy or raise CommandError.

        :param ldb: Ldb connection
        :param name: Either the DN or name of authentication policy
        """
        try:
            return AuthenticationPolicy.find(ldb, name)
        except (ModelError, ValueError) as e:
            raise CommandError(e)

    def run(self, hostopts=None, sambaopts=None, credopts=None,
            name=None, description=None,
            user_authentication_policy=None,
            service_authentication_policy=None,
            computer_authentication_policy=None,
            protect=None, unprotect=None,
            audit=None, enforce=None):

        if protect and unprotect:
            raise CommandError("--protect and --unprotect cannot be used together.")
        if audit and enforce:
            raise CommandError("--audit and --enforce cannot be used together.")

        ldb = self.ldb_connect(hostopts, sambaopts, credopts)

        try:
            silo = AuthenticationSilo.get(ldb, cn=name)
        except ModelError as e:
            raise CommandError(e)

        # Make sure silo doesn't already exist.
        if silo is not None:
            raise CommandError(f"Authentication silo {name} already exists.")

        # New silo object.
        silo = AuthenticationSilo(cn=name, description=description)

        # Set user policy
        if user_authentication_policy:
            silo.user_authentication_policy = \
                self.get_policy(ldb, user_authentication_policy).dn

        # Set service policy
        if service_authentication_policy:
            silo.service_authentication_policy = \
                self.get_policy(ldb, service_authentication_policy).dn

        # Set computer policy
        if computer_authentication_policy:
            silo.computer_authentication_policy = \
                self.get_policy(ldb, computer_authentication_policy).dn

        # Either --enforce will be set or --audit but never both.
        # The default if both are missing is enforce=True.
        if enforce is not None:
            silo.enforced = enforce
        else:
            silo.enforced = not audit

        # Create silo
        try:
            silo.save(ldb)

            if protect:
                silo.protect(ldb)
        except ModelError as e:
            raise CommandError(e)

        # Authentication silo created successfully.
        print(f"Created authentication silo: {name}", file=self.outf)


class cmd_domain_auth_silo_modify(Command):
    """Modify an authentication silo on the domain."""

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

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

    takes_options = [
        Option("--name", help="Name of authentication silo (required).",
               dest="name", action="store", type=str, required=True),
        Option("--description",
               help="Optional description for authentication silo.",
               dest="description", action="store", type=str),
        Option("--user-authentication-policy",
               help="User account authentication policy.",
               dest="user_authentication_policy", action="store", type=str,
               metavar="USER_POLICY"),
        Option("--service-authentication-policy",
               help="Managed service account authentication policy.",
               dest="service_authentication_policy", action="store", type=str,
               metavar="SERVICE_POLICY"),
        Option("--computer-authentication-policy",
               help="Computer authentication policy.",
               dest="computer_authentication_policy", action="store", type=str,
               metavar="COMPUTER_POLICY"),
        Option("--protect",
               help="Protect authentication silo from accidental deletion.",
               dest="protect", action="store_true"),
        Option("--unprotect",
               help="Unprotect authentication silo from accidental deletion.",
               dest="unprotect", action="store_true"),
        Option("--audit",
               help="Only audit silo policies.",
               dest="audit", action="store_true"),
        Option("--enforce",
               help="Enforce silo policies.",
               dest="enforce", action="store_true")
    ]

    @staticmethod
    def get_policy(ldb, name):
        """Helper function to fetch auth policy or raise CommandError.

        :param ldb: Ldb connection
        :param name: Either the DN or name of authentication policy
        """
        try:
            return AuthenticationPolicy.find(ldb, name)
        except (ModelError, ValueError) as e:
            raise CommandError(e)

    def run(self, hostopts=None, sambaopts=None, credopts=None,
            name=None, description=None,
            user_authentication_policy=None,
            service_authentication_policy=None,
            computer_authentication_policy=None,
            protect=None, unprotect=None,
            audit=None, enforce=None):

        if audit and enforce:
            raise CommandError("--audit and --enforce cannot be used together.")
        if protect and unprotect:
            raise CommandError("--protect and --unprotect cannot be used together.")

        ldb = self.ldb_connect(hostopts, sambaopts, credopts)

        try:
            silo = AuthenticationSilo.get(ldb, cn=name)
        except ModelError as e:
            raise CommandError(e)

        # Check if silo exists first.
        if silo is None:
            raise CommandError(f"Authentication silo {name} not found.")

        # Either --enforce will be set or --audit but never both.
        if enforce:
            silo.enforced = True
        elif audit:
            silo.enforced = False

        # Update the description.
        if description is not None:
            silo.description = description

        # Set or unset user policy.
        if user_authentication_policy == "":
            silo.user_authentication_policy = None
        elif user_authentication_policy:
            silo.user_authentication_policy = \
                self.get_policy(ldb, user_authentication_policy).dn

        # Set or unset service policy.
        if service_authentication_policy == "":
            silo.service_authentication_policy = None
        elif service_authentication_policy:
            silo.service_authentication_policy = \
                self.get_policy(ldb, service_authentication_policy).dn

        # Set or unset computer policy.
        if computer_authentication_policy == "":
            silo.computer_authentication_policy = None
        elif computer_authentication_policy:
            silo.computer_authentication_policy = \
                self.get_policy(ldb, computer_authentication_policy).dn

        # Update silo
        try:
            silo.save(ldb)

            if protect:
                silo.protect(ldb)
            elif unprotect:
                silo.unprotect(ldb)
        except ModelError as e:
            raise CommandError(e)

        # Silo updated successfully.
        print(f"Updated authentication silo: {name}", file=self.outf)


class cmd_domain_auth_silo_delete(Command):
    """Delete an authentication silo on the domain."""

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

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

    takes_options = [
        Option("--name", help="Name of authentication silo (required).",
               dest="name", action="store", type=str, required=True),
        Option("--force", help="Force delete protected authentication silo.",
               dest="force", action="store_true")
    ]

    def run(self, hostopts=None, sambaopts=None, credopts=None, name=None,
            force=None):

        ldb = self.ldb_connect(hostopts, sambaopts, credopts)

        try:
            silo = AuthenticationSilo.get(ldb, cn=name)
        except ModelError as e:
            raise CommandError(e)

        # Check if silo exists first.
        if silo is None:
            raise CommandError(f"Authentication silo {name} not found.")

        # Delete silo
        try:
            if force:
                silo.unprotect(ldb)

            silo.delete(ldb)
        except ModelError as e:
            if not force:
                raise CommandError(
                    f"{e}\nTry --force to delete protected authentication silos.")

            raise CommandError(e)

        # Authentication silo deleted successfully.
        print(f"Deleted authentication silo: {name}", file=self.outf)