summaryrefslogtreecommitdiffstats
path: root/ipalib/plugins/netgroup.py
blob: 8901ac92c183a42db28e464799e73d18d8cdd7ff (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
# Authors:
#   Rob Crittenden <rcritten@redhat.com>
#   Pavel Zuna <pzuna@redhat.com>
#
# Copyright (C) 2009  Red Hat
# see file 'COPYING' for use and warranty information
#
# 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/>.


from ipalib import api, errors
from ipalib import Str, StrEnum
from ipalib.plugins.baseldap import *
from ipalib import _, ngettext
from ipalib.plugins.hbacrule import is_all

__doc__ = _("""
Netgroups

A netgroup is a group used for permission checking. It can contain both
user and host values.

EXAMPLES:

 Add a new netgroup:
   ipa netgroup-add --desc="NFS admins" admins

 Add members to the netgroup:
   ipa netgroup-add-member --users=tuser1,tuser2 admins

 Remove a member from the netgroup:
   ipa netgroup-remove-member --users=tuser2 admins

 Display information about a netgroup:
   ipa netgroup-show admins

 Delete a netgroup:
   ipa netgroup-del admins
""")

output_params = (
        Str('memberuser_user?',
            label='Member User',
        ),
        Str('memberuser_group?',
            label='Member Group',
        ),
        Str('memberhost_host?',
            label=_('Member Host'),
        ),
        Str('memberhost_hostgroup?',
            label='Member Hostgroup',
        ),
    )

class netgroup(LDAPObject):
    """
    Netgroup object.
    """
    container_dn = api.env.container_netgroup
    object_name = _('netgroup')
    object_name_plural = _('netgroups')
    object_class = ['ipaobject', 'ipaassociation', 'ipanisnetgroup']
    default_attributes = [
        'cn', 'description', 'memberof', 'externalhost', 'nisdomainname',
        'memberuser', 'memberhost', 'member', 'memberindirect',
        'usercategory', 'hostcategory',
    ]
    uuid_attribute = 'ipauniqueid'
    rdn_attribute = 'ipauniqueid'
    attribute_members = {
        'member': ['netgroup'],
        'memberof': ['netgroup'],
        'memberindirect': ['netgroup'],
        'memberuser': ['user', 'group'],
        'memberhost': ['host', 'hostgroup'],
    }
    relationships = {
        'member': ('Member', '', 'no_'),
        'memberof': ('Member Of', 'in_', 'not_in_'),
        'memberindirect': (
            'Indirect Member', None, 'no_indirect_'
        ),
        'memberuser': ('Member', '', 'no_'),
        'memberhost': ('Member', '', 'no_'),
    }

    label = _('Netgroups')
    label_singular = _('Netgroup')

    takes_params = (
        Str('cn',
            cli_name='name',
            label=_('Netgroup name'),
            primary_key=True,
            normalizer=lambda value: value.lower(),
        ),
        Str('description',
            cli_name='desc',
            label=_('Description'),
            doc=_('Netgroup description'),
        ),
        Str('nisdomainname?',
            cli_name='nisdomain',
            label=_('NIS domain name'),
        ),
        Str('ipauniqueid?',
            cli_name='uuid',
            label='IPA unique ID',
            doc=_('IPA unique ID'),
            flags=['no_create', 'no_update'],
        ),
        StrEnum('usercategory?',
            cli_name='usercat',
            label=_('User category'),
            doc=_('User category the rule applies to'),
            values=(u'all', ),
        ),
        StrEnum('hostcategory?',
            cli_name='hostcat',
            label=_('Host category'),
            doc=_('Host category the rule applies to'),
            values=(u'all', ),
        ),
    )

api.register(netgroup)


class netgroup_add(LDAPCreate):
    __doc__ = _('Add a new netgroup.')

    has_output_params = LDAPCreate.has_output_params + output_params
    msg_summary = _('Added netgroup "%(value)s"')
    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        entry_attrs.setdefault('nisdomainname', self.api.env.domain)
        return dn

api.register(netgroup_add)


class netgroup_del(LDAPDelete):
    __doc__ = _('Delete a netgroup.')

    msg_summary = _('Deleted netgroup "%(value)s"')

api.register(netgroup_del)


class netgroup_mod(LDAPUpdate):
    __doc__ = _('Modify a netgroup.')

    has_output_params = LDAPUpdate.has_output_params + output_params
    msg_summary = _('Modified netgroup "%(value)s"')

    def pre_callback(self, ldap, dn, entry_attrs, attrs_list, *keys, **options):
        (dn, entry_attrs) = ldap.get_entry(dn, attrs_list)
        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")
        return dn

api.register(netgroup_mod)


class netgroup_find(LDAPSearch):
    __doc__ = _('Search for a netgroup.')

    member_attributes = ['member', 'memberuser', 'memberhost', 'memberof']
    has_output_params = LDAPSearch.has_output_params + output_params
    msg_summary = ngettext(
        '%(count)d netgroup matched', '%(count)d netgroups matched', 0
    )

    takes_options = LDAPSearch.takes_options + (
        Flag('private',
            exclude='webui',
            flags=['no_option', 'no_output'],
        ),
        Flag('managed',
            cli_name='managed',
            doc=_('search for managed groups'),
            default_from=lambda private: private,
        ),
    )

    def pre_callback(self, ldap, filter, attrs_list, base_dn, scope, *args, **options):
        # Do not display private mepManagedEntry netgroups by default
        # If looking for managed groups, we need to omit the negation search filter

        search_kw = {}
        search_kw['objectclass'] = ['mepManagedEntry']
        if not options['managed']:
            local_filter = ldap.make_filter(search_kw, rules=ldap.MATCH_NONE)
        else:
            local_filter = ldap.make_filter(search_kw, rules=ldap.MATCH_ALL)
        filter = ldap.combine_filters((local_filter, filter), rules=ldap.MATCH_ALL)
        return (filter, base_dn, scope)

api.register(netgroup_find)


class netgroup_show(LDAPRetrieve):
    __doc__ = _('Display information about a netgroup.')

    has_output_params = LDAPRetrieve.has_output_params + output_params

api.register(netgroup_show)


class netgroup_add_member(LDAPAddMember):
    __doc__ = _('Add members to a netgroup.')

    member_attributes = ['memberuser', 'memberhost', 'member']
    has_output_params = LDAPAddMember.has_output_params + output_params
    def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
        completed_external = 0
        # Sift through the host failures. We assume that these are all
        # hosts that aren't stored in IPA, aka external hosts.
        if 'memberhost' in failed and 'host' in failed['memberhost']:
            (dn, entry_attrs_) = ldap.get_entry(dn, ['externalhost'])
            members = entry_attrs.get('memberhost', [])
            external_hosts = entry_attrs_.get('externalhost', [])
            failed_hosts = []
            for host in failed['memberhost']['host']:
                hostname = host[0].lower()
                host_dn = self.api.Object['host'].get_dn(hostname)
                if hostname not in external_hosts and host_dn not in members:
                    external_hosts.append(hostname)
                    completed_external += 1
                else:
                    failed_hosts.append(hostname)
            if completed_external:
                try:
                    ldap.update_entry(dn, {'externalhost': external_hosts})
                except errors.EmptyModlist:
                    pass
                failed['memberhost']['host'] = failed_hosts
                entry_attrs['externalhost'] = external_hosts
        return (completed + completed_external, dn)


api.register(netgroup_add_member)


class netgroup_remove_member(LDAPRemoveMember):
    __doc__ = _('Remove members from a netgroup.')

    member_attributes = ['memberuser', 'memberhost', 'member']
    has_output_params = LDAPRemoveMember.has_output_params + output_params
    def post_callback(self, ldap, completed, failed, dn, entry_attrs, *keys, **options):
        # Run through the host failures and gracefully remove any defined as
        # as an externalhost.
        if 'memberhost' in failed and 'host' in failed['memberhost']:
            (dn, entry_attrs_) = ldap.get_entry(dn, ['externalhost'])
            external_hosts = entry_attrs_.get('externalhost', [])
            failed_hosts = []
            completed_external = 0
            for host in failed['memberhost']['host']:
                hostname = host[0].lower()
                if hostname in external_hosts:
                    external_hosts.remove(hostname)
                    completed_external += 1
                else:
                    failed_hosts.append(hostname)
            if completed_external:
                try:
                    ldap.update_entry(dn, {'externalhost': external_hosts})
                except errors.EmptyModlist:
                    pass
                failed['memberhost']['host'] = failed_hosts
                entry_attrs['externalhost'] = external_hosts
        return (completed + completed_external, dn)

api.register(netgroup_remove_member)
char(wh->type), maj, min, acc); } rcu_read_unlock(); return 0; } /* * may_access_whitelist: * does the access granted to dev_cgroup c contain the access * requested in whitelist item refwh. * return 1 if yes, 0 if no. * call with devcgroup_mutex held */ static int may_access_whitelist(struct dev_cgroup *c, struct dev_whitelist_item *refwh) { struct dev_whitelist_item *whitem; list_for_each_entry(whitem, &c->whitelist, list) { if (whitem->type & DEV_ALL) return 1; if ((refwh->type & DEV_BLOCK) && !(whitem->type & DEV_BLOCK)) continue; if ((refwh->type & DEV_CHAR) && !(whitem->type & DEV_CHAR)) continue; if (whitem->major != ~0 && whitem->major != refwh->major) continue; if (whitem->minor != ~0 && whitem->minor != refwh->minor) continue; if (refwh->access & (~whitem->access)) continue; return 1; } return 0; } /* * parent_has_perm: * when adding a new allow rule to a device whitelist, the rule * must be allowed in the parent device */ static int parent_has_perm(struct dev_cgroup *childcg, struct dev_whitelist_item *wh) { struct cgroup *pcg = childcg->css.cgroup->parent; struct dev_cgroup *parent; if (!pcg) return 1; parent = cgroup_to_devcgroup(pcg); return may_access_whitelist(parent, wh); } /* * Modify the whitelist using allow/deny rules. * CAP_SYS_ADMIN is needed for this. It's at least separate from CAP_MKNOD * so we can give a container CAP_MKNOD to let it create devices but not * modify the whitelist. * It seems likely we'll want to add a CAP_CONTAINER capability to allow * us to also grant CAP_SYS_ADMIN to containers without giving away the * device whitelist controls, but for now we'll stick with CAP_SYS_ADMIN * * Taking rules away is always allowed (given CAP_SYS_ADMIN). Granting * new access is only allowed if you're in the top-level cgroup, or your * parent cgroup has the access you're asking for. */ static int devcgroup_update_access(struct dev_cgroup *devcgroup, int filetype, const char *buffer) { const char *b; char *endp; int count; struct dev_whitelist_item wh; if (!capable(CAP_SYS_ADMIN)) return -EPERM; memset(&wh, 0, sizeof(wh)); b = buffer; switch (*b) { case 'a': wh.type = DEV_ALL; wh.access = ACC_MASK; wh.major = ~0; wh.minor = ~0; goto handle; case 'b': wh.type = DEV_BLOCK; break; case 'c': wh.type = DEV_CHAR; break; default: return -EINVAL; } b++; if (!isspace(*b)) return -EINVAL; b++; if (*b == '*') { wh.major = ~0; b++; } else if (isdigit(*b)) { wh.major = simple_strtoul(b, &endp, 10); b = endp; } else { return -EINVAL; } if (*b != ':') return -EINVAL; b++; /* read minor */ if (*b == '*') { wh.minor = ~0; b++; } else if (isdigit(*b)) { wh.minor = simple_strtoul(b, &endp, 10); b = endp; } else { return -EINVAL; } if (!isspace(*b)) return -EINVAL; for (b++, count = 0; count < 3; count++, b++) { switch (*b) { case 'r': wh.access |= ACC_READ; break; case 'w': wh.access |= ACC_WRITE; break; case 'm': wh.access |= ACC_MKNOD; break; case '\n': case '\0': count = 3; break; default: return -EINVAL; } } handle: switch (filetype) { case DEVCG_ALLOW: if (!parent_has_perm(devcgroup, &wh)) return -EPERM; return dev_whitelist_add(devcgroup, &wh); case DEVCG_DENY: dev_whitelist_rm(devcgroup, &wh); break; default: return -EINVAL; } return 0; } static int devcgroup_access_write(struct cgroup *cgrp, struct cftype *cft, const char *buffer) { int retval; mutex_lock(&devcgroup_mutex); retval = devcgroup_update_access(cgroup_to_devcgroup(cgrp), cft->private, buffer); mutex_unlock(&devcgroup_mutex); return retval; } static struct cftype dev_cgroup_files[] = { { .name = "allow", .write_string = devcgroup_access_write, .private = DEVCG_ALLOW, }, { .name = "deny", .write_string = devcgroup_access_write, .private = DEVCG_DENY, }, { .name = "list", .read_seq_string = devcgroup_seq_read, .private = DEVCG_LIST, }, }; static int devcgroup_populate(struct cgroup_subsys *ss, struct cgroup *cgroup) { return cgroup_add_files(cgroup, ss, dev_cgroup_files, ARRAY_SIZE(dev_cgroup_files)); } struct cgroup_subsys devices_subsys = { .name = "devices", .can_attach = devcgroup_can_attach, .create = devcgroup_create, .destroy = devcgroup_destroy, .populate = devcgroup_populate, .subsys_id = devices_subsys_id, }; int devcgroup_inode_permission(struct inode *inode, int mask) { struct dev_cgroup *dev_cgroup; struct dev_whitelist_item *wh; dev_t device = inode->i_rdev; if (!device) return 0; if (!S_ISBLK(inode->i_mode) && !S_ISCHR(inode->i_mode)) return 0; rcu_read_lock(); dev_cgroup = task_devcgroup(current); list_for_each_entry_rcu(wh, &dev_cgroup->whitelist, list) { if (wh->type & DEV_ALL) goto found; if ((wh->type & DEV_BLOCK) && !S_ISBLK(inode->i_mode)) continue;