summaryrefslogtreecommitdiffstats
path: root/ipaserver/plugins/caacl.py
blob: 3f813a7efb9e554abcb8dd2946eea73065c93414 (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
#
# Copyright (C) 2015  FreeIPA Contributors see COPYING for license
#

import pyhbac
import six

from ipalib import api, errors, output
from ipalib import Bool, Str, StrEnum
from ipalib.constants import IPA_CA_CN
from ipalib.plugable import Registry
from .baseldap import (
    LDAPObject, LDAPSearch, LDAPCreate, LDAPDelete, LDAPQuery,
    LDAPUpdate, LDAPRetrieve, LDAPAddMember, LDAPRemoveMember,
    global_output_params, pkey_to_value)
from .hbacrule import is_all
from ipalib import _, ngettext
from ipapython.dn import DN

if six.PY3:
    unicode = str

__doc__ = _("""
Manage CA ACL rules.

This plugin is used to define rules governing which principals are
permitted to have certificates issued using a given certificate
profile.

PROFILE ID SYNTAX:

A Profile ID is a string without spaces or punctuation starting with a letter
and followed by a sequence of letters, digits or underscore ("_").

EXAMPLES:

  Create a CA ACL "test" that grants all users access to the
  "UserCert" profile on all CAs:
    ipa caacl-add test --usercat=all --cacat=all
    ipa caacl-add-profile test --certprofiles UserCert

  Display the properties of a named CA ACL:
    ipa caacl-show test

  Create a CA ACL to let user "alice" use the "DNP3" profile on "DNP3-CA":
    ipa caacl-add alice_dnp3
    ipa caacl-add-ca alice_dnp3 --cas DNP3-CA
    ipa caacl-add-profile alice_dnp3 --certprofiles DNP3
    ipa caacl-add-user alice_dnp3 --user=alice

  Disable a CA ACL:
    ipa caacl-disable test

  Remove a CA ACL:
    ipa caacl-del test
""")

register = Registry()


def _acl_make_request(principal_type, principal, ca_id, profile_id):
    """Construct HBAC request for the given principal, CA and profile"""

    req = pyhbac.HbacRequest()
    req.targethost.name = ca_id
    req.service.name = profile_id
    if principal_type == 'user' or principal_type == 'host':
        req.user.name = principal.username
    elif principal_type == 'service':
        req.user.name = unicode(principal)
    groups = []
    if principal_type == 'user':
        user_obj = api.Command.user_show(principal.username)['result']
        groups = user_obj.get('memberof_group', [])
        groups += user_obj.get('memberofindirect_group', [])
    elif principal_type == 'host':
        host_obj = api.Command.host_show(principal.hostname)['result']
        groups = host_obj.get('memberof_hostgroup', [])
        groups += host_obj.get('memberofindirect_hostgroup', [])
    req.user.groups = sorted(set(groups))
    return req


def _acl_make_rule(principal_type, obj):
    """Turn CA ACL object into HBAC rule.

    ``principal_type``
        String in {'user', 'host', 'service'}
    """
    rule = pyhbac.HbacRule(obj['cn'][0])
    rule.enabled = obj['ipaenabledflag'][0]
    rule.srchosts.category = {pyhbac.HBAC_CATEGORY_ALL}

    # add CA(s)
    if 'ipacacategory' in obj and obj['ipacacategory'][0].lower() == 'all':
        rule.targethosts.category = {pyhbac.HBAC_CATEGORY_ALL}
    else:
        # For compatibility with pre-lightweight-CAs CA ACLs,
        # no CA members implies the host authority (only)
        rule.targethosts.names = obj.get('ipamemberca_ca', [IPA_CA_CN])

    # add profiles
    if ('ipacertprofilecategory' in obj
            and obj['ipacertprofilecategory'][0].lower() == 'all'):
        rule.services.category = {pyhbac.HBAC_CATEGORY_ALL}
    else:
        attr = 'ipamembercertprofile_certprofile'
        rule.services.names = obj.get(attr, [])

    # add principals and principal's groups
    m = {'user': 'group', 'host': 'hostgroup', 'service': None}
    category_attr = '{}category'.format(principal_type)
    if category_attr in obj and obj[category_attr][0].lower() == 'all':
        rule.users.category = {pyhbac.HBAC_CATEGORY_ALL}
    else:
        principal_attr = 'member{}_{}'.format(principal_type, principal_type)
        rule.users.names = obj.get(principal_attr, [])
        if m[principal_type] is not None:
            group_attr = 'member{}_{}'.format(principal_type, m[principal_type])
            rule.users.groups = obj.get(group_attr, [])

    return rule


def acl_evaluate(principal_type, principal, ca_id, profile_id):
    req = _acl_make_request(principal_type, principal, ca_id, profile_id)
    acls = api.Command.caacl_find(no_members=False)['result']
    rules = [_acl_make_rule(principal_type, obj) for obj in acls]
    return req.evaluate(rules) == pyhbac.HBAC_EVAL_ALLOW


@register()
class caacl(LDAPObject):
    """
    CA ACL object.
    """
    container_dn = api.env.container_caacl
    object_name = _('CA ACL')
    object_name_plural = _('CA ACLs')
    object_class = ['ipaassociation', 'ipacaacl']
    permission_filter_objectclasses = ['ipacaacl']
    default_attributes = [
        'cn', 'description', 'ipaenabledflag',
        'ipacacategory', 'ipamemberca',
        'ipacertprofilecategory', 'ipamembercertprofile',
        'usercategory', 'memberuser',
        'hostcategory', 'memberhost',
        'servicecategory', 'memberservice',
    ]
    uuid_attribute = 'ipauniqueid'
    rdn_attribute = 'ipauniqueid'
    attribute_members = {
        'memberuser': ['user', 'group'],
        'memberhost': ['host', 'hostgroup'],
        'memberservice': ['service'],
        'ipamemberca': ['ca'],
        'ipamembercertprofile': ['certprofile'],
    }
    managed_permissions = {
        'System: Read CA ACLs': {
            'replaces_global_anonymous_aci': True,
            'ipapermbindruletype': 'all',
            'ipapermright': {'read', 'search', 'compare'},
            'ipapermdefaultattr': {
                'cn', 'description', 'ipaenabledflag',
                'ipacacategory', 'ipamemberca',
                'ipacertprofilecategory', 'ipamembercertprofile',
                'usercategory', 'memberuser',
                'hostcategory', 'memberhost',
                'servicecategory', 'memberservice',
                'ipauniqueid',
                'objectclass', 'member',
            },
        },
        'System: Add CA ACL': {
            'ipapermright': {'add'},
            'replaces': [
                '(target = "ldap:///ipauniqueid=*,cn=caacls,cn=ca,$SUFFIX")(version 3.0;acl "permission:Add CA ACL";allow (add) groupdn = "ldap:///cn=Add CA ACL,cn=permissions,cn=pbac,$SUFFIX";)',
            ],
            'default_privileges': {'CA Administrator'},
        },
        'System: Delete CA ACL': {
            'ipapermright': {'delete'},
            'replaces': [
                '(target = "ldap:///ipauniqueid=*,cn=caacls,cn=ca,$SUFFIX")(version 3.0;acl "permission:Delete CA ACL";allow (delete) groupdn = "ldap:///cn=Delete CA ACL,cn=permissions,cn=pbac,$SUFFIX";)',
            ],
            'default_privileges': {'CA Administrator'},
        },
        'System: Manage CA ACL Membership': {
            'ipapermright': {'write'},
            'ipapermdefaultattr': {
                'ipacacategory', 'ipamemberca',
                'ipacertprofilecategory', 'ipamembercertprofile',
                'usercategory', 'memberuser',
                'hostcategory', 'memberhost',
                'servicecategory', 'memberservice'
            },
            'replaces': [
                '(targetattr = "ipamemberca || ipamembercertprofile || memberuser || memberservice || memberhost || ipacacategory || ipacertprofilecategory || usercategory || hostcategory || servicecategory")(target = "ldap:///ipauniqueid=*,cn=caacls,cn=ca,$SUFFIX")(version 3.0;acl "permission:Manage CA ACL membership";allow (write) groupdn = "ldap:///cn=Manage CA ACL membership,cn=permissions,cn=pbac,$SUFFIX";)',
            ],
            'default_privileges': {'CA Administrator'},
        },
        'System: Modify CA ACL': {
            'ipapermright': {'write'},
            'ipapermdefaultattr': {
                'cn', 'description', 'ipaenabledflag',
            },
            'replaces': [
                '(targetattr = "cn || description || ipaenabledflag")(target = "ldap:///ipauniqueid=*,cn=caacls,cn=ca,$SUFFIX")(version 3.0;acl "permission:Modify CA ACL";allow (write) groupdn = "ldap:///cn=Modify CA ACL,cn=permissions,cn=pbac,$SUFFIX";)',
            ],
            'default_privileges': {'CA Administrator'},
        },
    }

    label = _('CA ACLs')
    label_singular = _('CA ACL')

    takes_params = (
        Str('cn',
            cli_name='name',
            label=_('ACL name'),
            primary_key=True,
        ),
        Str('description?',
            cli_name='desc',
            label=_('Description'),
        ),
        Bool('ipaenabledflag?',
             label=_('Enabled'),
             flags=['no_option'],
        ),
        StrEnum('ipacacategory?',
            cli_name='cacat',
            label=_('CA category'),
            doc=_('CA category the ACL applies to'),
            values=(u'all', ),
        ),
        StrEnum('ipacertprofilecategory?',
            cli_name='profilecat',
            label=_('Profile category'),
            doc=_('Profile category the ACL applies to'),
            values=(u'all', ),
        ),
        StrEnum('usercategory?',
            cli_name='usercat',
            label=_('User category'),
            doc=_('User category the ACL applies to'),
            values=(u'all', ),
        ),
        StrEnum('hostcategory?',
            cli_name='hostcat',
            label=_('Host category'),
            doc=_('Host category the ACL applies to'),
            values=(u'all', ),
        ),
        StrEnum('servicecategory?',
            cli_name='servicecat',
            label=_('Service category'),
            doc=_('Service category the ACL applies to'),
            values=(u'all', ),
        ),
        Str('ipamemberca_ca?',
            label=_('CAs'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
        Str('ipamembercertprofile_certprofile?',
            label=_('Profiles'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
        Str('memberuser_user?',
            label=_('Users'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
        Str('memberuser_group?',
            label=_('User Groups'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
        Str('memberhost_host?',
            label=_('Hosts'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
        Str('memberhost_hostgroup?',
            label=_('Host Groups'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
        Str('memberservice_service?',
            label=_('Services'),
            flags=['no_create', 'no_update', 'no_search'],
        ),
    )


@register()
class caacl_add(LDAPCreate):
    __doc__ = _('Create a new CA ACL.')

    msg_summary = _('Added CA ACL "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        # CA ACLs are enabled by default
        entry_attrs['ipaenabledflag'] = ['TRUE']
        return dn


@register()
class caacl_del(LDAPDelete):
    __doc__ = _('Delete a CA ACL.')

    msg_summary = _('Deleted CA ACL "%(value)s"')

    def pre_callback(self, ldap, dn, *keys, **options):
        if keys[0] == 'hosts_services_caIPAserviceCert':
            raise errors.ProtectedEntryError(
                label=_("CA ACL"),
                key=keys[0],
                reason=_("default CA ACL can be only disabled"))
        return dn


@register()
class caacl_mod(LDAPUpdate):
    __doc__ = _('Modify a CA ACL.')

    msg_summary = _('Modified CA ACL "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        assert isinstance(dn, DN)
        try:
            entry_attrs = ldap.get_entry(dn, attrs_list)
            dn = entry_attrs.dn
        except errors.NotFound:
            self.obj.handle_not_found(*keys)

        if is_all(options, 'ipacacategory') and 'ipamemberca' in entry_attrs:
            raise errors.MutuallyExclusiveError(reason=_(
                "CA category cannot be set to 'all' "
                "while there are allowed CAs"))
        if (is_all(options, 'ipacertprofilecategory')
                and 'ipamembercertprofile' in entry_attrs):
            raise errors.MutuallyExclusiveError(reason=_(
                "profile category cannot be set to 'all' "
                "while there are allowed profiles"))
        if is_all(options, 'usercategory') and 'memberuser' in entry_attrs:
            raise errors.MutuallyExclusiveError(reason=_(
                "user category cannot be set to 'all' "
                "while there are allowed users"))
        if is_all(options, 'hostcategory') and 'memberhost' in entry_attrs:
            raise errors.MutuallyExclusiveError(reason=_(
                "host category cannot be set to 'all' "
                "while there are allowed hosts"))
        if is_all(options, 'servicecategory') and 'memberservice' in entry_attrs:
            raise errors.MutuallyExclusiveError(reason=_(
                "service category cannot be set to 'all' "
                "while there are allowed services"))
        return dn


@register()
class caacl_find(LDAPSearch):
    __doc__ = _('Search for CA ACLs.')

    msg_summary = ngettext(
        '%(count)d CA ACL matched', '%(count)d CA ACLs matched', 0
    )


@register()
class caacl_show(LDAPRetrieve):
    __doc__ = _('Display the properties of a CA ACL.')


@register()
class caacl_enable(LDAPQuery):
    __doc__ = _('Enable a CA ACL.')

    msg_summary = _('Enabled CA ACL "%(value)s"')
    has_output = output.standard_value

    def execute(self, cn, **options):
        ldap = self.obj.backend

        dn = self.obj.get_dn(cn)
        try:
            entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
        except errors.NotFound:
            self.obj.handle_not_found(cn)

        entry_attrs['ipaenabledflag'] = ['TRUE']

        try:
            ldap.update_entry(entry_attrs)
        except errors.EmptyModlist:
            pass

        return dict(
            result=True,
            value=pkey_to_value(cn, options),
        )


@register()
class caacl_disable(LDAPQuery):
    __doc__ = _('Disable a CA ACL.')

    msg_summary = _('Disabled CA ACL "%(value)s"')
    has_output = output.standard_value

    def execute(self, cn, **options):
        ldap = self.obj.backend

        dn = self.obj.get_dn(cn)
        try:
            entry_attrs = ldap.get_entry(dn, ['ipaenabledflag'])
        except errors.NotFound:
            self.obj.handle_not_found(cn)

        entry_attrs['ipaenabledflag'] = ['FALSE']

        try:
            ldap.update_entry(entry_attrs)
        except errors.EmptyModlist:
            pass

        return dict(
            result=True,
            value=pkey_to_value(cn, options),
        )


@register()
class caacl_add_user(LDAPAddMember):
    __doc__ = _('Add users and groups to a CA ACL.')

    member_attributes = ['memberuser']
    member_count_out = (
        _('%i user or group added.'),
        _('%i users or groups added.'))

    def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
        assert isinstance(dn, DN)
        try:
            entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
            dn = entry_attrs.dn
        except errors.NotFound:
            self.obj.handle_not_found(*keys)
        if is_all(entry_attrs, 'usercategory'):
            raise errors.MutuallyExclusiveError(
                reason=_("users cannot be added when user category='all'"))
        return dn


@register()
class caacl_remove_user(LDAPRemoveMember):
    __doc__ = _('Remove users and groups from a CA ACL.')

    member_attributes = ['memberuser']
    member_count_out = (
        _('%i user or group removed.'),
        _('%i users or groups removed.'))


@register()
class caacl_add_host(LDAPAddMember):
    __doc__ = _('Add target hosts and hostgroups to a CA ACL.')

    member_attributes = ['memberhost']
    member_count_out = (
        _('%i host or hostgroup added.'),
        _('%i hosts or hostgroups added.'))

    def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
        assert isinstance(dn, DN)
        try:
            entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
            dn = entry_attrs.dn
        except errors.NotFound:
            self.obj.handle_not_found(*keys)
        if is_all(entry_attrs, 'hostcategory'):
            raise errors.MutuallyExclusiveError(
                reason=_("hosts cannot be added when host category='all'"))
        return dn


@register()
class caacl_remove_host(LDAPRemoveMember):
    __doc__ = _('Remove target hosts and hostgroups from a CA ACL.')

    member_attributes = ['memberhost']
    member_count_out = (
        _('%i host or hostgroup removed.'),
        _('%i hosts or hostgroups removed.'))


@register()
class caacl_add_service(LDAPAddMember):
    __doc__ = _('Add services to a CA ACL.')

    member_attributes = ['memberservice']
    member_count_out = (_('%i service added.'), _('%i services added.'))

    def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
        assert isinstance(dn, DN)
        try:
            entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
            dn = entry_attrs.dn
        except errors.NotFound:
            self.obj.handle_not_found(*keys)
        if is_all(entry_attrs, 'servicecategory'):
            raise errors.MutuallyExclusiveError(reason=_(
                "services cannot be added when service category='all'"))
        return dn


@register()
class caacl_remove_service(LDAPRemoveMember):
    __doc__ = _('Remove services from a CA ACL.')

    member_attributes = ['memberservice']
    member_count_out = (_('%i service removed.'), _('%i services removed.'))


caacl_output_params = global_output_params + (
    Str('ipamembercertprofile',
        label=_('Failed profiles'),
    ),
    Str('ipamemberca',
        label=_('Failed CAs'),
    ),
)


@register()
class caacl_add_profile(LDAPAddMember):
    __doc__ = _('Add profiles to a CA ACL.')

    has_output_params = caacl_output_params

    member_attributes = ['ipamembercertprofile']
    member_count_out = (_('%i profile added.'), _('%i profiles added.'))

    def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
        assert isinstance(dn, DN)
        try:
            entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
            dn = entry_attrs.dn
        except errors.NotFound:
            self.obj.handle_not_found(*keys)
        if is_all(entry_attrs, 'ipacertprofilecategory'):
            raise errors.MutuallyExclusiveError(reason=_(
                "profiles cannot be added when profile category='all'"))
        return dn


@register()
class caacl_remove_profile(LDAPRemoveMember):
    __doc__ = _('Remove profiles from a CA ACL.')

    has_output_params = caacl_output_params

    member_attributes = ['ipamembercertprofile']
    member_count_out = (_('%i profile removed.'), _('%i profiles removed.'))


@register()
class caacl_add_ca(LDAPAddMember):
    __doc__ = _('Add CAs to a CA ACL.')

    has_output_params = caacl_output_params

    member_attributes = ['ipamemberca']
    member_count_out = (_('%i CA added.'), _('%i CAs added.'))

    def pre_callback(self, ldap, dn, found, not_found, *keys, **options):
        assert isinstance(dn, DN)
        try:
            entry_attrs = ldap.get_entry(dn, self.obj.default_attributes)
            dn = entry_attrs.dn
        except errors.NotFound:
            self.obj.handle_not_found(*keys)
        if is_all(entry_attrs, 'ipacacategory'):
            raise errors.MutuallyExclusiveError(reason=_(
                "CAs cannot be added when CA category='all'"))
        return dn


@register()
class caacl_remove_ca(LDAPRemoveMember):
    __doc__ = _('Remove CAs from a CA ACL.')

    has_output_params = caacl_output_params

    member_attributes = ['ipamemberca']
    member_count_out = (_('%i CA removed.'), _('%i CAs removed.'))