-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.py
executable file
·379 lines (296 loc) · 10.3 KB
/
index.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
372
373
374
375
376
377
378
379
#!/usr/bin/env python
"""
Password changer for Linux user
To allow users to change their own password without superuser/root privileges.
Usage:
index.py [-s SERVER -H DBHOST -p port -P DBPORT]
index.py [-h | --help]
index.py --version
Options:
-h --help Show this screen.
-v --version Show version.
-s --server SERVER Web server host [default: 0.0.0.0]
-p --port PORT Web server port [default: 8001].
-H --dbhost DBHOST Database host [default: localhost].
-P --dbport DBPORT Database port [default: 27017].
"""
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
activate_this = os.path.join(base_dir, 'venv/bin/activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
from bottle import run, route, abort, request, template, static_file, app, redirect
from pymongo import MongoClient, errors as e
from docopt import docopt
import spwd
import crypt
import random
import string
import fileinput
'''
____ _
| _ \ __ _ ___ _____ _____ _ __ __| |
| |_) / _` / __/ __\ \ /\ / / _ \| '__/ _` |
| __/ (_| \__ \__ \\ V V / (_) | | | (_| |
|_| _ \__,_|___/___/ \_/\_/ \___/|_| \__,_|
| | | | __ _ _ __ __| | | ___ _ __
| |_| |/ _` | '_ \ / _` | |/ _ \ '__|
| _ | (_| | | | | (_| | | __/ |
|_| |_|\__,_|_| |_|\__,_|_|\___|_|
'''
class PasswordHandler(object):
def __init__(self,
username=None,
previous_passwd=None,
new_passwd=None,
**kwargs):
"""
Class initialization
Args:
username: Username
previous_passwd: Current/previous password
new_passwd: New password
"""
self.username = username
self.previous_passwd = previous_passwd
self.new_passwd = new_passwd
self.shadow_hashed = None
self.previous_salt = None
self.previous_hashed = None
def check_input(self):
"""Check input
Validate input given by user
Args:
None - use class variable:
self.username,
self.previous_passwd,
self.new_passwd
Returns:
None - just checking for:
1 - all fields filled up
2 - username exists, password match.
if user doesn't exist or password doesn't match,
raise HTTP error 400.
Raises:
None
"""
if not self.previous_passwd:
abort(400, "Current password required")
if not self.username:
abort(400, "Name required")
else:
self.getshadow(self.username)
if not self.new_passwd:
abort(400, "Password required")
def compare(self):
"""Compare passwords
Comparing password given by user
with the one currently in shadown file
Args:
None
Returns:
True boolean if both passwords are match
Error 400 if doesn't match
Raises:
None
"""
self.getshadow(self.username)
self.getsalt(self.username)
self.previous_hashed = self.hashing(self.previous_passwd, "$6$" + self.previous_salt + "$")
if self.shadow_hashed == self.previous_hashed:
return True
else:
abort(400, "Current password are incorrect")
def getshadow(self, username=None):
"""Get hashed from shadow file
Retrieve hashed stored in shadow file for given username
Args:
username: (Optional) username to be check
Returns:
Hashed string from shadow file
Raises:
KeyError
"""
try:
print "username = {}".format(username)
if username:
self.shadow_hashed = spwd.getspnam(username)[1]
else:
self.shadow_hashed = spwd.getspnam(self.username)[1]
return self.shadow_hashed
except KeyError:
abort(400, "User %s doesn't exist" % self.username)
def getsalt(self, username=None):
"""Get salt from shadow file
Retrieve salt used to hashing the password
for given username
Args:
username: (Optional) username of which salt to be retrieved.
If no username given, will use class self.username
Returns:
Salt used in shadow file
Raises:
None
"""
if username:
shadow_hashed = self.getshadow(username)
self.previous_salt = shadow_hashed.split("$")[2]
else:
self.previous_salt = self.shadow_hashed.split("$")[2]
return self.previous_salt
def hashing(self, passwd, salt=None):
"""Hashing password with salt
Generate a hashed value for given password and salt
Args:
passwd: Password to be hashed
salt: (Optional) Salt to be use when hashing
Returns:
Hashed value
Raises:
None
"""
print salt
if not salt:
hashed = crypt.crypt(passwd, str(self.generate_salt()))
else:
hashed = crypt.crypt(passwd, salt)
return hashed
def generate_salt(self):
"""Generate salt
Generate salt to be use with hashing()
Args:
None
Returns:
Salt value
Raises:
None
"""
salt = ([random.choice(string.ascii_letters +
string.digits) for _ in range(16)])
salt = "$6$" + ''.join(salt) + "$"
return salt
def change_passwd(self, prev_hashed, new_hashed):
"""Change password
Search and replace /etc/shadow file with newly generated hashed value
Args:
prev_hashed: Hashed from current/previous password
new_hashed: Hashed from new password
Returns:
None
Raises:
None
"""
# TODO: Retrieve hashed value from DB and write to /etc/shadow ,
# instead of directly write
shadow_file = "/etc/shadow"
for line in fileinput.input(shadow_file, inplace=True, backup='.bak'):
line = line.replace(prev_hashed, new_hashed)
print line,
fileinput.close()
root_uid = 0
shadow_gid = 42
os.chown(shadow_file, root_uid, shadow_gid)
"""
____ _ _
| _ \ __ _| |_ __ _| |__ __ _ ___ ___
| | | |/ _` | __/ _` | '_ \ / _` / __|/ _ \
| |_| | (_| | || (_| | |_) | (_| \__ \ __/
|____/ \__,_|\__\__,_|_.__/ \__,_|___/\___|
| | | | __ _ _ __ __| | | ___ _ __
| |_| |/ _` | '_ \ / _` | |/ _ \ '__|
| _ | (_| | | | | (_| | | __/ |
|_| |_|\__,_|_| |_|\__,_|_|\___|_|
"""
class DatabaseHandler(object):
def __init__(self,
username=None,
previous_passwd=None,
new_passwd=None,
**kwargs):
"""
Class initialization
Args:
username: Username
previous_passwd: Current/previous password
new_passwd: New password
"""
self.pwhandler = PasswordHandler(username, previous_passwd, new_passwd)
self.username = username
self.new_passwd = new_passwd
self.new_salt = None
self.new_hashed = None
self.connection = None
self.db = None
self.userdata = None
def connect(self):
"""Connect to database
Establish new connection to Mongo database
Args:
None - use class variable:
self.connection
Returns:
None
Raises:
None
"""
try:
self.connection = MongoClient(
host=args['--dbhost'],
port=int(args['--dbport']),
ServerSelectionTimeoutMS=1
)
self.connection.server_info()
except Exception:
abort(500, "Could not establish connection to database")
def store(self):
self.connect()
try:
# TODO: store or replace. check the id/username
# DB Name : passwd_webui
# Collection : users
self.db = self.connection.passwd_webui.users
self.previous_hashed = self.pwhandler.getshadow(self.username)
self.previous_salt = self.pwhandler.getsalt(self.username)
self.new_salt = self.pwhandler.generate_salt()
self.new_hashed = self.pwhandler.hashing(self.new_passwd,
self.new_salt)
self.userdata = {
'username': self.username,
'previous_salt': self.previous_salt,
'previous_hashed': self.previous_hashed,
'new_salt': self.new_salt,
'new_hashed': self.new_hashed
}
self.db.insert_one(self.userdata)
self.pwhandler.change_passwd(self.previous_hashed,
self.new_hashed)
except Exception as err:
abort(500, "Operation failed: %s" % err)
@route('/')
def index():
return template('index.html')
@route('/css/<filepath>')
def css(filepath):
return static_file(filepath, root=os.path.join(base_dir, 'views/css'))
@route('/modify_user', method='POST')
def modify_user():
username = request.forms.get('username').lower()
previous_passwd = request.forms.get('previous_passwd')
new_passwd = request.forms.get('new_passwd')
pwhandler = PasswordHandler(username,
previous_passwd,
new_passwd)
dbhandler = DatabaseHandler(username,
previous_passwd,
new_passwd)
pwhandler.check_input()
if pwhandler.compare():
dbhandler.store()
return template('modified.html', username=username)
if __name__ == "__main__":
args = docopt(__doc__, version="FIXME")
app = app()
run(host=args['--server'],
port=int(args['--port']),
app=app,
reloader=True,
debug=True)