File: nss.py

package info (click to toggle)
twextpy 1%3A0.1~git20161216.0.b90293c-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,724 kB
  • sloc: python: 20,458; sh: 742; makefile: 5
file content (208 lines) | stat: -rw-r--r-- 6,822 bytes parent folder | download
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
##
# Copyright (c) 2016 Rahul Amaram <amaramrahul@users.sourceforge.net>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##

"""
NSS Directory service interfaces.

Uses libc's Name Service Switch for user and groups (/etc/nsswitch.conf).
"""

import pwd
import grp
import PAM
from time import time
from uuid import UUID
from zope.interface import implementer

from twisted.internet.defer import succeed
from twext.python.log import Logger
from twistedcaldav.directory.util import uuidFromName
from .idirectory import (
    RecordType,
    FieldName,
    IPlaintextPasswordVerifier
)
from .index import (
    DirectoryService,
    DirectoryRecord,
    FieldName as IndexFieldName,
)
from .util import ConstantsContainer

__all__ = [
    "NssDirectoryService",
]

# Logger
log = Logger()


def _generateUID(serviceGUID, recordType, shortName):
    return unicode(uuidFromName(serviceGUID,
                                "%s:%s" % (recordType, shortName)),
                   "utf-8")


class NssDirectoryService(DirectoryService):

    # Supported record types
    recordType = ConstantsContainer(
        (RecordType.user, RecordType.group)
    )

    _baseGUID = "8EFFFAF1-5221-4813-B971-58506B963573"

    _lastRefresh = 0

    def __init__(self, params):
        """
        @param params: a dictionary containing the following keys:
            realmName, groupPrefix, mailDomain, firstValidUid, lastValidUid,
            firstValidGid, lastValidGid, refreshIntervalThreshold
        """
        self.mailDomain = params["mailDomain"]
        self.groupPrefix = params["groupPrefix"]
        self.firstValidUid = params["firstValidUid"]
        self.firstValidGid = params["firstValidGid"]
        self.lastValidUid = params["lastValidUid"]
        self.lastValidGid = params["lastValidGid"]
        self.refreshIntervalThreshold = params["refreshIntervalThreshold"]
        self.guid = uuidFromName(self._baseGUID, params["realmName"])

        DirectoryService.__init__(self, realmName=params["realmName"])

    def flush(self):
        DirectoryService.flush(self)
        _lastRefresh = 0

    def _isValidUid(self, uid):
        if uid >= self.firstValidUid and uid <= self.lastValidUid:
            return True

    def _isValidGid(self, gid):
        if gid >= self.firstValidGid and gid <= self.lastValidGid:
            return True

    def loadRecords(self):
        now = time()
        if now - self._lastRefresh <= self.refreshIntervalThreshold:
            return

        log.info("Loading and indexing NSS records")
        users = set()
        groups = set()
        records = set()
        for result in pwd.getpwall():
            if self._isValidUid(result[2]):
                record = NssUserRecord.fromUserName(
                            service=self,
                            userName=result[0],
                            gecos=result[4],
                            )
                records.add(record)
                users.add(result[0])
        for result in grp.getgrall():
            if result[0].startswith(self.groupPrefix) and \
                    self._isValidGid(result[2]):
                record = NssGroupRecord.fromGroupName(
                            service=self,
                            groupName=result[0],
                            members=result[3]
                            )
                records.add(record)
                groups.add(result[0])

        log.debug("Processed NSS Users: {}".format(users))
        log.debug("Processed NSS Groups: {}".format(groups))

        # Store results
        self.flush()
        self.indexRecords(records)
        _lastRefresh = now


@implementer(IPlaintextPasswordVerifier)
class NssUserRecord(DirectoryRecord):
    """
    NSS Users implementation of L{IDirectoryRecord}.
    """

    @classmethod
    def fromUserName(cls, service, userName, gecos):
        uid = _generateUID(service.guid, "users", userName)
        guid = UUID(uid)
        shortNames = (unicode(userName, "utf-8"),)
        fullNames = (unicode(gecos.split(",", 1)[0], "utf-8"),)
        emailAddresses = set()
        if service.mailDomain:
            emailAddresses.add(unicode("%s@%s" %
                                       (userName, service.mailDomain), "utf-8"))
        log.debug("Creating user record with uid: %r, guid: %r, "
                  "shortNames: %r, fullNames: %r, emailAddresses: %r" %
                  (uid, guid, shortNames, fullNames, emailAddresses))
        return cls(service,  dict([
            (FieldName.recordType, service.recordType.user),
            (FieldName.uid, uid),
            (FieldName.guid, guid),
            (FieldName.shortNames, shortNames),
            (FieldName.fullNames, fullNames),
            (FieldName.emailAddresses, emailAddresses)
            ])
        )

    def verifyPlaintextPassword(self, password):
        # Authenticate against PAM
        def pam_conv(auth, query_list, userData):
            return [(password, 0)]

        auth = PAM.pam()
        auth.start("caldav")
        auth.set_item(PAM.PAM_USER, self.shortNames[0])
        auth.set_item(PAM.PAM_CONV, pam_conv)
        try:
            auth.authenticate()
        except PAM.error, resp:
            return succeed(False)
        else:
            return succeed(True)


class NssGroupRecord(DirectoryRecord):
    """
    NSS Groups implementation of L{IDirectoryRecord}.
    """

    @classmethod
    def fromGroupName(cls, service, groupName, members=()):
        groupNameWithoutPrefix = groupName.replace(service.groupPrefix, '', 1)
        uid = _generateUID(service.guid, "groups", groupNameWithoutPrefix)
        guid = UUID(uid)
        shortNames = (unicode(groupNameWithoutPrefix, "utf-8"),)
        memberUIDs = tuple([_generateUID(service.guid, "users", userName)
                            for userName in members])
        log.debug("Creating group record with uid: %r, guid: %r, "
                  "shortNames: %r, memberUIDs: %r" %
                  (uid, guid, shortNames, memberUIDs))
        return cls(service, dict([
            (FieldName.recordType, service.recordType.group),
            (FieldName.uid, uid),
            (FieldName.guid, guid),
            (FieldName.shortNames, shortNames),
            (IndexFieldName.memberUIDs, memberUIDs)
            ])
        )