-
Notifications
You must be signed in to change notification settings - Fork 1
/
pymaidentity.py
290 lines (258 loc) · 11 KB
/
pymaidentity.py
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
import pwd, grp, sys, os
from Collaboration import CBUserIdentity, CBGroupIdentity, CBIdentityAuthority
from SystemConfiguration import SCDynamicStoreCopyConsoleUser
from objc import NULL
from ctypes import *
def CurrentDesktopUser():
# User account currently logged in locally to the machine, sitting at the Desktop
# This works even with Fast User Switching
# http://developer.apple.com/library/mac/#qa/qa1133/_index.html
current_user = (SCDynamicStoreCopyConsoleUser(NULL, NULL, NULL) or [NULL])[0]
if (current_user == u'loginwindow') or (current_user == NULL):
current_user = None
return User(current_user)
def CurrentEffectiveUser():
# User account we're currently running this script with
try:
return User(os.geteuid())
except:
return User(None)
class Group:
_fields = ('name', 'gid', 'hidden', 'uuid', 'fullname', '_id_obj')
_gr_map = {'name': 'gr_name', 'gid': 'gr_gid'}
def _init_with_grp(self, grp_entry):
if isinstance(grp_entry, grp.struct_group):
for key in self._gr_map.keys():
setattr(self,key,getattr(grp_entry, self._gr_map[key]))
if self.gid is not None:
# Group exists, find extended information
id_auth = CBIdentityAuthority.defaultIdentityAuthority()
self._id_obj = CBGroupIdentity.groupIdentityWithPosixGID_authority_(self.gid, id_auth)
if self._id_obj:
# Make copies of the data as pure python objects, rather than keep translating
if self._id_obj.UUIDString() is not None:
self.uuid = str(self._id_obj.UUIDString())
if self._id_obj.fullName() is not None:
self.fullname = str(self._id_obj.fullName())
self.hidden = bool(self._id_obj.isHidden())
def __nonzero__(self):
for i in self._fields:
if getattr(self,i) is not None:
return True
return False
def __str__(self):
return self.name or ''
def __int__(self):
if self.gid is None:
return -(sys.maxint)-1
return self.gid
def __hash__(self):
return hash("%s %s" % (int(self),str(self)))
def __eq__(self, other):
if isinstance(other, Group):
for i in self._fields:
if getattr(self,i) != getattr(other,i):
return False
return True
elif other is None:
if (self.name is None) and (self.gid is None):
return True
return False
elif isinstance(other, basestring):
if self.name == other:
return True
return False
elif isinstance(other, (int,long)):
if self.gid == other:
return True
return False
return False
def __ne__(self, other):
return not self.__eq__(other)
def __init__(self, name_or_gid = None):
# If passed a string, assume group name
# If passed a number, assume gid
# If None, leave everything with a value of None
# Initialize everything to None
for i in self._fields:
setattr(self, i, None)
# Determine whether we were passed a name or a gid or a Group
if isinstance(name_or_gid, Group):
# Guessing it's a Group object - clone the settings
# Clone if user name or gid present, otherwise None
if name_or_gid != None:
if name_or_gid.name is not None:
gr_info = grp.getgrnam(name_or_gid.name)
else:
gr_info = grp.getgrgid(name_or_gid.gid)
self._init_with_grp(gr_info)
elif isinstance(name_or_gid, (int,long)):
# Guessing it's a gid
try:
gr_info = grp.getgrgid(name_or_gid)
self._init_with_grp(gr_info)
except KeyError:
self.gid = None
elif isinstance(name_or_gid, basestring):
# Guessing it's a group name
try:
gr_info = grp.getgrnam(name_or_gid)
self._init_with_grp(gr_info)
except KeyError:
self.name = None
def is_member(self, user_info):
# If we're an invalid group or it's an invalid user, they're not a member of anything
if not self:
return False
if not user_info:
return False
# If passed a string, assume user name
# If passed a number, assume uid
# If passed a User object, use the .uid of it
if isinstance(user_info, User):
return user_info.is_member(self)
elif isinstance(user_info, basestring) or isinstance(user_info, (int,long)):
return User(user_info).is_member(self)
else:
# Not sure what we were passed, fail to False
return False
class User:
_fields = ('name', 'uid', 'gid', 'home', 'email', 'hidden', 'enabled',
'uuid', 'fullname', '_id_obj', 'groups')
_pw_map = {'name': 'pw_name', 'uid': 'pw_uid',
'gid': 'pw_gid', 'home': 'pw_dir'}
def _init_with_pwd(self, pwd_entry):
if isinstance(pwd_entry, pwd.struct_passwd):
for key in self._pw_map.keys():
setattr(self,key,getattr(pwd_entry, self._pw_map[key]))
if self.uid is not None:
# User exists, find extended information
id_auth = CBIdentityAuthority.defaultIdentityAuthority()
self._id_obj = CBUserIdentity.userIdentityWithPosixUID_authority_(self.uid, id_auth)
if self._id_obj:
# Make copies of the data as pure python objects, rather than keep translating
if self._id_obj.emailAddress() is not None:
self.email = str(self._id_obj.emailAddress())
if self._id_obj.UUIDString() is not None:
self.uuid = str(self._id_obj.UUIDString())
if self._id_obj.fullName() is not None:
self.fullname = str(self._id_obj.fullName())
self.hidden = bool(self._id_obj.isHidden())
self.enabled = bool(self._id_obj.isEnabled())
# Find extended group membership information
# Load up OS X libc
libc = CDLL("/usr/lib/libc.dylib")
# define access to an undocumented Apple function 'getgrouplist_2'
# Based on the example from:
# http://opensource.apple.com/source/shell_cmds/shell_cmds-162/id/id.c
getgrouplist_2 = libc.getgrouplist_2
# Create the function prototype
getgrouplist_2.argtypes = [c_char_p, c_uint32, POINTER(POINTER(c_uint32))]
# Initialize pointer to array of gid information
groups = POINTER(c_uint32)()
# Get number of groups and gid list
ngroups = getgrouplist_2(self.name, self.gid, byref(groups))
# Make explicit copies prior to freeing the allocated pointer array
if ngroups > 0:
self.groups = [Group(int(groups[i])) for i in range(ngroups)]
# Clean up after ourselves and free up the array, ignoring result
_ = libc.free(groups)
def __nonzero__(self):
for i in self._fields:
if getattr(self,i) is not None:
return True
return False
def __str__(self):
return self.name or ''
def __int__(self):
if self.uid is None:
return -(sys.maxint)-1
return self.uid
def __hash__(self):
return hash("%s %s" % (int(self),str(self)))
def __eq__(self, other):
if isinstance(other, User):
for i in self._fields:
if getattr(self,i) != getattr(other,i):
return False
return True
elif other is None:
if (self.name is None) and (self.uid is None):
return True
return False
elif isinstance(other, basestring):
if self.name == other:
return True
return False
elif isinstance(other, (int,long)):
if self.uid == other:
return True
return False
return False
def __ne__(self, other):
return not self.__eq__(other)
def __init__(self, name_or_uid = None):
# If passed a string, assume user name
# If passed a number, assume uid
# If None, leave everything with a value of None
# Initialize everything to None
for i in self._fields:
setattr(self, i, None)
# Determine whether we were passed a name or a uid or a User
if isinstance(name_or_uid, User):
# Guessing it's a User object - clone the settings
# Clone if user name or uid present, otherwise None
if name_or_uid != None:
if name_or_uid.name is not None:
pw_info = pwd.getpwnam(name_or_uid.name)
else:
pw_info = pwd.getpwuid(name_or_uid.uid)
self._init_with_pwd(pw_info)
elif isinstance(name_or_uid, (int,long)):
# Guessing it's a uid
try:
pw_info = pwd.getpwuid(name_or_uid)
self._init_with_pwd(pw_info)
except KeyError:
self.uid = None
elif isinstance(name_or_uid, basestring):
# Guessing it's a user name
try:
pw_info = pwd.getpwnam(name_or_uid)
self._init_with_pwd(pw_info)
except KeyError:
self.name = None
def _is_member(self, group_obj):
if not group_obj:
return False
# Try two paths here -
# 1st check if recursive member, via .groups
if group_obj in self.groups:
return True
else:
return bool(self._id_obj.isMemberOfGroup_(group_obj._id_obj))
def is_member(self, group_info):
# If we're an invalid user or it's an invalid group, we're not a member of anything
if not self:
return False
if not group_info:
return False
# If passed a string, assume group name
# If passed a number, assume gid
# If passed a Group object, use the .gid of it
if isinstance(group_info, Group):
return self._is_member(group_info)
elif isinstance(group_info, basestring) or isinstance(group_info, (int,long)):
return self._is_member(Group(group_info))
else:
# Not sure what we were passed, fail to False
return False
def group_names(self):
if self.groups:
return [x.name for x in self.groups]
def group_ids(self):
if self.groups:
return [x.gid for x in self.groups]
def group_objs(self):
# Just for completeness against the other convenience functions
return self.groups