-
Notifications
You must be signed in to change notification settings - Fork 8
/
usergroup-management.py
executable file
·371 lines (287 loc) · 12 KB
/
usergroup-management.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
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
#!/usr/bin/env python3
#
# Copyright 2018 Nicholas de Jong <contact[at]nicholasdejong.com>
#
# 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.
#
import os, sys, json
import bcrypt # pip install bcrypt
try:
from PfsenseFauxapi.PfsenseFauxapi import PfsenseFauxapi
except:
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from PfsenseFauxapi.PfsenseFauxapi import PfsenseFauxapi
def usage():
print()
print('usage: ' + sys.argv[0] + ' <host>')
print()
print(' Environment variables containing credentials MUST be set before use!')
print(' $ export FAUXAPI_APIKEY=PFFAyourkeyvalue')
print(' $ export FAUXAPI_APISECRET=devtrashdevtrashdevtrashdevtrashdevtrash')
print()
print('pipe JSON output through jq for easy pretty print output:-')
print(' $ ' + sys.argv[0] + ' <host> | jq .')
print()
sys.exit(1)
# check args and env exist
if(len(sys.argv) != 2) or not os.getenv('FAUXAPI_APIKEY') or not os.getenv('FAUXAPI_APISECRET'):
usage()
# config
fauxapi_host=sys.argv[1]
fauxapi_apikey=os.getenv('FAUXAPI_APIKEY')
fauxapi_apisecret=os.getenv('FAUXAPI_APISECRET')
class UserGroupManagementFauxapiException(Exception):
pass
class UserGroupManagementFauxapi():
fauxapi_host = None
fauxapi_apikey = None
fauxapi_apisecret = None
system_config= None
FauxapiLib = None
def __init__(self, fauxapi_host, fauxapi_apikey, fauxapi_apisecret, debug=False):
self.FauxapiLib = PfsenseFauxapi(fauxapi_host, fauxapi_apikey, fauxapi_apisecret, debug)
# user functions
# =========================================================================
def get_users(self):
self._reload_system_config()
response_data = {}
for user in self.system_config['system']['user']:
response_data[user['name']] = user
del(response_data[user['name']]['name'])
return response_data
def add_user(self, username):
self._reload_system_config()
user_index, user = self._get_entity('user', username)
if user_index is not None:
raise UserGroupManagementFauxapiException('user already exists', username)
user = {
'scope': 'user',
'bcrypt-hash': 'no-password-set',
'descr': '',
'name': username,
'expires': '',
'dashboardcolumns': '2',
'authorizedkeys': '',
'ipsecpsk': '',
'webguicss': 'pfSense.css',
'uid': self._get_next_id('uid'),
}
patch_system_user = {
'system': {
'user': self.system_config['system']['user']
}
}
patch_system_user['system']['user'].append(user)
response = self.FauxapiLib.config_patch(patch_system_user)
if response['message'] != 'ok':
raise UserGroupManagementFauxapiException('unable to add user', response['message'])
self._increment_next_id('uid')
return user
def manage_user(self, username, attributes):
self._reload_system_config()
valid_attributes = ['password','descr','expires','dashboardcolumns','authorizedkeys','ipsecpsk','webguicss','disabled','priv']
user_index, user = self._get_entity('user', username)
if user_index is None:
raise UserGroupManagementFauxapiException('user does not exist', username)
if type(attributes) != dict:
raise UserGroupManagementFauxapiException('attributes is incorrect type')
for attribute, value in attributes.items():
if attribute not in valid_attributes:
raise UserGroupManagementFauxapiException('unsupported attribute type', attribute)
if attribute == 'disabled':
if value is True:
user[attribute] = ''
else:
if attribute in user:
del(user[attribute])
elif attribute == 'password':
user['bcrypt-hash'] = bcrypt.hashpw(value.encode('utf8'), bcrypt.gensalt()).decode('utf8')
else:
if len(value) == 0 and attribute in user:
del(user[attribute])
elif len(value) > 0:
user[attribute] = value
patch_system_user = {
'system': {
'user': self.system_config['system']['user']
}
}
patch_system_user['system']['user'][user_index] = user
response = self.FauxapiLib.config_patch(patch_system_user)
if response['message'] != 'ok':
raise UserGroupManagementFauxapiException('unable to manage user', response['message'])
return user
def remove_user(self, username):
self._reload_system_config()
user_index, user = self._get_entity('user', username)
if user_index is None:
raise UserGroupManagementFauxapiException('user does not exist', username)
patch_system_user = {
'system': {
'user': self.system_config['system']['user']
}
}
del(patch_system_user['system']['user'][user_index])
response = self.FauxapiLib.config_patch(patch_system_user)
if response['message'] != 'ok':
raise UserGroupManagementFauxapiException('unable to remove user', response['message'])
return user
# group functions
# =========================================================================
def get_groups(self):
self._reload_system_config()
response_data = {}
for group in self.system_config['system']['group']:
response_data[group['name']] = group
del(response_data[group['name']]['name'])
return response_data
def add_group(self, groupname):
self._reload_system_config()
group_index, group = self._get_entity('group', groupname)
if group_index is not None:
raise UserGroupManagementFauxapiException('group already exists', groupname)
group = {
'scope': 'local',
'description': '',
'name': groupname,
'gid': self._get_next_id('gid'),
}
patch_system_group = {
'system': {
'group': self.system_config['system']['group']
}
}
patch_system_group['system']['group'].append(group)
response = self.FauxapiLib.config_patch(patch_system_group)
if response['message'] != 'ok':
raise UserGroupManagementFauxapiException('unable to add group', response['message'])
self._increment_next_id('gid')
return group
def manage_group(self, groupname, attributes):
self._reload_system_config()
valid_attributes = ['description','member','priv']
group_index, group = self._get_entity('group', groupname)
if group_index is None:
raise UserGroupManagementFauxapiException('group does not exist', groupname)
if type(attributes) != dict:
raise UserGroupManagementFauxapiException('attributes is incorrect type')
for attribute, value in attributes.items():
if attribute not in valid_attributes:
raise UserGroupManagementFauxapiException('unsupported attribute type', attribute)
if attribute == 'member':
if type(value) != list:
raise UserGroupManagementFauxapiException('member attribute is incorrect type')
elif attribute == 'priv':
if type(value) != list:
raise UserGroupManagementFauxapiException('priv attribute is incorrect type')
if len(value) == 0 and attribute in group:
del(group[attribute])
elif len(value) > 0:
group[attribute] = value
patch_system_group = {
'system': {
'group': self.system_config['system']['group']
}
}
patch_system_group['system']['group'][group_index] = group
response = self.FauxapiLib.config_patch(patch_system_group)
if response['message'] != 'ok':
raise UserGroupManagementFauxapiException('unable to manage group', response['message'])
return group
def remove_group(self, groupname):
self._reload_system_config()
group_index, group = self._get_entity('group', groupname)
if group_index is None:
raise UserGroupManagementFauxapiException('group does not exist', groupname)
patch_system_group = {
'system': {
'group': self.system_config['system']['group']
}
}
del(patch_system_group['system']['group'][group_index])
response = self.FauxapiLib.config_patch(patch_system_group)
if response['message'] != 'ok':
raise UserGroupManagementFauxapiException('unable to remove group', response['message'])
return group
# internal helper functions
# =========================================================================
def _get_entity(self, entity_type, entity_name):
entity = None
entity_index = 0
for entity_data in self.system_config['system'][entity_type]:
if entity_data['name'] == entity_name:
entity = entity_data
break
entity_index += 1
if entity is None:
return None, None
return entity_index, entity
def _get_next_id(self, id_type):
id_name = 'next{}'.format(id_type)
return self.system_config['system'][id_name]
def _increment_next_id(self, id_type):
id_name = 'next{}'.format(id_type)
next_id = int(self._get_next_id(id_type)) + 1
patch_system_nextid = {
'system': {
id_name: str(next_id)
}
}
response = self.FauxapiLib.config_patch(patch_system_nextid)
if response['message'] != 'ok':
raise UserGroupManagementFauxapiException('unable to increment the nextid', id_type)
return next_id
def _reload_system_config(self):
self.system_config = self.FauxapiLib.config_get()
if __name__ == '__main__':
UGMF = UserGroupManagementFauxapi(fauxapi_host, fauxapi_apikey, fauxapi_apisecret)
# get_users
users = UGMF.get_users()
print(json.dumps(users))
# get_groups
groups = UGMF.get_groups()
print(json.dumps(groups))
# =========================================================================
# add_user
user = UGMF.add_user('someuser')
print(json.dumps(user))
# manage_user attributes
attributes = {
'disabled': False,
'descr': 'some new name',
'password': 'awesomepassword',
'expires': '12/25/2020',
'authorizedkeys': 'insert-ssh-key-material-here',
'priv': ['page-all'],
}
user = UGMF.manage_user('someuser', attributes)
print(json.dumps(user))
# =========================================================================
# add_group
group = UGMF.add_group('somegroup')
print(json.dumps(group))
# manage_group attributes
attributes = {
'description': 'some new group name',
'member': [user['uid']],
'priv': ['page-all'],
}
group = UGMF.manage_group('somegroup', attributes)
print(json.dumps(group))
# =========================================================================
# remove_group
group = UGMF.remove_group('somegroup')
print(json.dumps(group))
# remove_user
user = UGMF.remove_user('someuser')
print(json.dumps(user))