-
Notifications
You must be signed in to change notification settings - Fork 308
/
skf.py
executable file
·1625 lines (1497 loc) · 68 KB
/
skf.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Security Knowledge Framework is an expert system application
that uses OWASP Application Security Verification Standard, code examples,
helps developers in pre-development and post-development.
Copyright (C) 2015 Glenn ten Cate, Riccardo ten Cate
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os, markdown, datetime, string, base64, re, sys, re, requests, mimetypes, smtplib
from OpenSSL import SSL, rand
from docx import Document
from BeautifulSoup import BeautifulSoup
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Inches
from functools import wraps
from sqlite3 import dbapi2 as sqlite3
from flask.ext.bcrypt import Bcrypt
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash, Markup, make_response
from . import version
# create the application
app = Flask(__name__)
"""Set up bcrypt for passwords encrypting"""
bcrypt = Bcrypt(app)
def add_response_headers(headers={}):
"""This decorator adds the headers passed in to the response"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
resp = make_response(f(*args, **kwargs))
h = resp.headers
for header, value in headers.items():
h[header] = value
return resp
return decorated_function
return decorator
def security(f):
"""This decorator passes multiple security headers and checks log file to block users"""
return add_response_headers({'X-Frame-Options': 'deny', 'X-XSS-Protection': '1', 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store, no-cache','Strict-Transport-Security': 'max-age=16070400; includeSubDomains', 'Server': 'Security Knowledge Framework'})(f)
def check_token():
"""Checks the submitted CSRF token"""
if not session.get('csrf_token') == request.form['csrf_token']:
log("User supplied not valid CSRF token", "FAIL", "HIGH")
session.clear()
return abort(500)(f)
def generate_pass():
chars = string.letters + string.digits + '+/'
assert 256 % len(chars) == 0 # non-biased later modulo
PWD_LEN = 12
generated_pass = ''.join(chars[ord(c) % len(chars)] for c in os.urandom(PWD_LEN))
return generated_pass
def random_token(tokenBytes):
#Create random token
rand.cleanup()
Random_token_raw = rand.bytes(int(tokenBytes))
Random_token = base64.b64encode(Random_token_raw)
result = re.sub("==", "", Random_token)
return result
def log(message, value, threat):
"""Create log file and write events triggerd by the user
The variables: message can be everything, value contains FAIL or SUCCESS and threat LOW MEDIUM HIGH"""
now = datetime.datetime.now()
dateLog = now.strftime("%Y-%m")
dateTime = now.strftime("%Y-%m-%d %H:%M")
ip = request.remote_addr
try:
file = open('logs/'+dateLog+'.txt', 'a+')
except IOError:
# If not exists, create the file
file = open('logs/'+dateLog+'.txt', 'w+')
file.write(dateTime +' '+ message +' ' + ' ' + value + ' ' + threat + ' ' +ip + "\r\n")
file.close()
def blockUsers():
"""Check the log file and based on the FAIL items block a user"""
dateLog = datetime.datetime.now().strftime("%Y-%m")
count = 0
try:
read = open(os.path.join(app.root_path, 'logs/'+dateLog+'.txt'), 'a+')
except IOError:
# If not exists, create the file
read = open(os.path.join(app.root_path, 'logs/'+dateLog+'.txt'), 'w+')
for line in read:
match = re.search('FAIL', line)
# If-statement after search() tests if it succeeded
if match:
count += 1
str(count)
if count > 11:
sys.exit('Due to to many FAILED logs in your logging file we have the suspicion your application has been under attack by hackers. Please check your log files to validate and take repercussions. After validation clear your log or simply change the FAIL items to another value.')
def valAlphaNum(value, countLevel):
match = re.findall(r"[^ a-zA-Z0-9_.-]", value)
if match:
log("User supplied not an a-zA-Z0-9 value", "FAIL", "MEDIUM")
countAttempts(countLevel)
abort(406)
return False
else:
return True
def valNum(value, countLevel):
match = re.findall(r'[a-zA-Z_]', str(value))
if match:
log("malicious input found", "FAIL", "MEDIUM")
countAttempts(countLevel)
abort(406)
return False
else:
return True
def encodeInput(html):
"""Encode evil chars..."""
result = re.sub('"', """, html)
result = re.sub("'", "'", result)
result = re.sub("&", "&", result)
result = re.sub("<", "<", result)
result = re.sub(">", ">", result)
log("User supplied input was encoded", "SUCCESS", "NULL")
return result
#not tested yet, made draft did not needed it so far
def whiteList(allowed, input, countlevel):
splitted = string.split(allowed, ',')
bool = False
for val in splitted:
if val in input:
bool = True
if bool == False:
log("User is tampering whitelist values", "FAIL", "HIGH")
countAttempts(countLevel)
abort(401)
if bool == True:
return bool
#secret key for flask internal session use
rand.cleanup()
secret_key = rand.bytes(512)
mimetypes.add_type('image/svg+xml', '.svg')
bindaddr = '127.0.0.1';
# Load default config and override config from an environment variable
# You can also replace password with static password: PASSWORD='pass!@#example'
app.config.update(dict(
DATABASE=os.path.join(app.root_path, 'skf.db'),
DEBUG=True,
SECRET_KEY=secret_key,
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY = True
))
@app.context_processor
def inject_year():
return dict(year=datetime.datetime.now().strftime("%Y"))
def connect_db():
"""Connects to the specific database."""
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
def init_db():
"""Initializes the database."""
db = get_db()
with app.open_resource('schema.sql') as f:
db.cursor().executescript(f.read())
db.commit()
@app.cli.command('initdb')
def initdb_command():
"""Creates the database tables."""
init_db()
print('Initialized the database.')
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
def get_filepaths(directory):
"""
This function will generate the file names in a directory
tree by walking the tree either top-down or bottom-up. For each
directory in the tree rooted at directory top (including top itself),
it yields a 3-tuple (dirpath, dirnames, filenames).
"""
file_paths = []
for root, directories, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
return file_paths
def get_num(x):
"""get numbers from a string"""
return int(''.join(ele for ele in x if ele.isdigit()))
@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request."""
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
def check_version():
try:
r = requests.get("http://raw.githubusercontent.com/blabla1337/skf-flask/master/setup.py")
items_remote = r.content.split(",")
version_remote = items_remote[1]
version_remote = version_remote.replace(version_remote[:14], '')
version_remote = version_remote[:-1]
with open ("version.txt", "r") as myfile:
version_local = myfile.read().replace('\n', '')
if version_local == version_remote:
return True
else:
return False
except:
return False
def get_version():
return version.__version__
def projects_functions_techlist():
"""get list of technology used for creating project functions"""
if not session.get('logged_in'):
abort(401)
db = get_db()
cur = db.execute('SELECT techID, techName, vulnID from techhacks ORDER BY techID DESC')
entries = cur.fetchall()
return entries
@app.route('/')
@security
def show_landing():
"""show the loging page and set default code language"""
rand.cleanup()
csrf_token_raw = rand.bytes(128)
csrf_token = base64.b64encode(csrf_token_raw)
session['csrf_token'] = csrf_token
session['code_lang'] = "php"
return render_template('login.html', csrf_token=session['csrf_token'])
@app.route('/dashboard', methods=['GET'])
@security
def dashboard():
"""show the landing page"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /dashboard", "FAIL", "HIGH")
abort(401)
permissions("read")
version_check = check_version()
version = get_version()
return render_template('dashboard.html', version=version, version_check=version_check)
@app.route('/first-login', methods=['GET'])
@security
def first_login():
version_check = check_version()
version = get_version()
return render_template('first-login.html', version=version, version_check=version_check)
"""create account for a user"""
@app.route('/create-account', methods=['GET', 'POST'])
@security
def create_account():
"""validate the login data for access dashboard page"""
error = None
db = get_db()
db.commit()
if request.method == 'POST':
"""Username, password, token, email from form"""
token = request.form['token']
email = request.form['email']
password = request.form['password']
#hash the password with Bcrypt, does autosalt
hashed = bcrypt.generate_password_hash(password, 12)
#Do DB query also check for access
cur = db.execute('SELECT accessToken, userID from users where email=? AND accessToken=?',
[email, token])
check = cur.fetchall()
for verify in check:
userID = verify[1]
if str(verify[0]) == token:
#update the counter and blocker table with new values
db.execute('UPDATE users SET access=?, password=?, activated=? WHERE accessToken=? AND userID=?',
["true", hashed, "true", token , userID])
db.commit()
#Insert record in counter table for the counting of malicious inputs
db.execute('INSERT INTO counter (userID, countEvil, block) VALUES (?, ?, ?)',
[userID, 0, 0])
db.commit()
#Create standard group for this user to assign himself to
date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
db.execute('INSERT INTO groups (ownerID, groupName, timestamp) VALUES (?, ?, ?)',
[userID, "privateGroup", date])
db.commit()
#Select this groupID so we can assign the user to this group automatically
cur = db.execute('SELECT groupID from groups where ownerID=?',
[userID])
group = cur.fetchall()
for theID in group:
groupID = theID[0]
#Now we assign the user to the group
date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
db.execute('INSERT INTO groupMembers (userID, groupID, ownerID) VALUES (?, ?, ?)',
[userID, groupID, userID])
db.commit()
if not check:
#if not the right pin, the user account wil be deleted if not exsisting
db.execute('DElETE FROM users where email=? AND activated=?',
[email, "false"])
db.commit()
return render_template('login.html', error=error)
"""First comes the method for login"""
@app.route('/login', methods=['GET', 'POST'])
@security
def login():
"""validate the login data for access dashboard page"""
error = None
db = get_db()
db.commit()
if request.method == 'POST':
"""Username and password from form"""
username = request.form['username']
password = request.form['password']
#Do DB query also check for access
cur = db.execute('SELECT access from users where userName=?',
[username])
check = cur.fetchall()
for verify in check:
if verify[0] == "false":
return render_template('warning.html', error=error)
#Do DB query also check for access
cur = db.execute('SELECT u.userID, u.privilegeID, u.userName, u.password, u.access, priv.privilegeID, priv.privilege from users as u JOIN privileges AS priv ON priv.privilegeID = u.privilegeID where username=? AND access="true"',
[username])
entries = cur.fetchall()
for entry in entries:
passwordHash = entry[3]
userID = entry[0]
#Do encryption
if bcrypt.check_password_hash(passwordHash, password):
log("Valid username/password submit", "SUCCESS", "HIGH")
rand.cleanup()
csrf_token_raw = rand.bytes(128)
csrf_token = base64.b64encode(csrf_token_raw)
session['logged_in'] = True
session['userID'] = userID
session['csrf_token'] = csrf_token
session['code_lang'] = "php"
session['userName'] = entry[2]
valAlphaNum(session['userName'], 12)
session['permissions'] = entry[6]
version_check = check_version()
version = get_version()
#Do DB query also check for access
cur = db.execute('SELECT groupID from groups WHERE groupName=? AND ownerID=?',
["privateGroup", session['userID']])
groupID = cur.fetchall()
for entry in groupID:
session['privateGroup'] = entry[0]
return render_template('dashboard.html', version=version, version_check=version_check)
else:
log("invalid login submit", "FAIL", "HIGH")
return render_template('login.html', error=error)
def countAttempts(counter):
"""We count hacking attempts and block the user if structural"""
if not session.get('logged_in'):
abort(401)
db = get_db()
cur = db.execute('SELECT * FROM counter where userID=?',
[session['userID']])
entries = cur.fetchall()
for entry in entries:
counterDB = entry[2]
blockDB = entry[3]
updateCount = counterDB + counter
updateBlock = blockDB + counter
redirect = False
if updateCount >= 3:
countUpdate = 0
redirect = True
if updateBlock >=12:
redirect = True
db.execute('UPDATE users SET access=? WHERE userID=?',
["false", session['userID']])
db.commit()
renderwhat = "/warning.html"
#update the counter and blocker table with new values
db.execute('UPDATE counter SET countEvil=?, block=? WHERE userID=?',
[updateCount, updateBlock, session['userID']])
db.commit()
if redirect == True:
log( "Authenticated session destroyed by counter class", "SUCCESS", "LOW")
# TO-DO turn on again
#session.pop('logged_in', None)
#session.clear()
if redirect == False:
return True
"""Here is the method for the database enforced privilege based authentication"""
def permissions(fromFunction):
db = get_db()
db.commit()
"""Do DB query to see if username exists"""
cur = db.execute('SELECT a.username, a.userID, a.password, a.privilegeID, b.privilegeID, b.privilege FROM users as a JOIN privileges as b ON a.privilegeID = b.privilegeID WHERE a.userID =? and a.access="true" ',
[session['userID']])
entries = cur.fetchall()
for entry in entries:
permissions = entry[5]
permissionsGranted = string.split(permissions, ':')
permissionsNeeded = string.split(fromFunction, ':')
count = len(permissionsNeeded)
counthits = 0
for val in permissionsGranted:
if val in fromFunction:
counthits +=1
if counthits >= count:
return permissions
else:
log( "User tries to reach functions out of bound no restrictions!!", "FAIL", "HIGH")
abort(401)
@app.route('/logout', methods=['GET', 'POST'])
@security
def logout():
"""logout and destroy session"""
log( "Authenticated session destroyed", "SUCCESS", "LOW")
session.pop('logged_in', None)
session.clear()
return redirect("/")
@app.route('/code/<code_lang>', methods=['GET'])
@security
def set_code_lang(code_lang):
"""set a code language: php java python perl"""
if not session.get('logged_in'):
log( "User with no valid session tries access to page /code", "FAIL", "HIGH")
abort(401)
permissions("read")
allowed = "php java python asp"
valAlphaNum(code_lang, 12)
safe_code_lang = encodeInput(code_lang)
found = allowed.find(safe_code_lang)
if found != -1:
#to do below security issue... Create white-list of the languages
if safe_code_lang == "asp" or safe_code_lang == "php":
session['code_lang'] = safe_code_lang
return redirect(url_for('code_examples'))
@app.route('/code-examples', methods=['GET'])
@security
def code_examples():
"""Shows the knowledge base markdown files."""
if not session.get('logged_in'):
log( "User with no valid session tries access to page /code-examples", "FAIL", "HIGH")
abort(401)
permissions("read")
items = []
id_items = []
full_file_paths = []
allowed = set(string.ascii_lowercase + string.ascii_uppercase + '.')
if set(session['code_lang']) <= allowed:
full_file_paths = get_filepaths(os.path.join(app.root_path, "markdown/code_examples/"+session['code_lang']))
for path in full_file_paths:
id_item = get_num(path)
path = path.split("-")
y = len(path)-3
kb_name_uri = path[(y)]
kb_name = kb_name_uri.replace("_", " ")
items.append(kb_name)
id_items.append(id_item)
return render_template('code-examples.html', items=items, id_items=id_items)
@app.route('/code-item', methods=['POST'])
@security
def show_code_item():
"""show the coding examples page"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /code-item", "FAIL", "HIGH")
abort(401)
permissions("read")
valNum(request.form['id'], 12)
id = int(request.form['id'])
items = []
full_file_paths = []
allowed = set(string.ascii_lowercase + string.ascii_uppercase + '.')
if set(session['code_lang']) <= allowed:
full_file_paths = get_filepaths(os.path.join(app.root_path, "markdown/code_examples/"+session['code_lang']))
for path in full_file_paths:
if id == get_num(path):
filemd = open(path, 'r').read()
content = Markup(markdown.markdown(filemd))
return render_template('code-examples-item.html', **locals())
@app.route('/kb-item', methods=['POST'])
@security
def show_kb_item():
"""show the knowledge base search result page"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /kb-item", "FAIL", "HIGH")
abort(401)
permissions("read")
valNum(request.form['id'], 12)
id = int(request.form['id'])
items = []
full_file_paths = []
full_file_paths = get_filepaths(os.path.join(app.root_path, "markdown"))
for path in full_file_paths:
if id == get_num(path):
filemd = open(path, 'r').read()
content = Markup(markdown.markdown(filemd))
return render_template('knowledge-base-item.html', **locals())
@app.route('/knowledge-base-api', methods=['GET'])
@security
def show_kb_api():
"""show the knowledge base items page"""
log( "User access page /knowledge-base-api", "SUCCESS", "HIGH")
full_file_paths = []
content = []
kb_name = []
full_file_paths = get_filepaths(os.path.join(app.root_path, "markdown/knowledge_base"))
for path in full_file_paths:
filetmp = open(path, 'r').read()
filetmp2 = filetmp.replace("-------", "")
filetmp3 = filetmp2.replace("**", "")
filetmp4 = filetmp3.replace("\"", "")
filetmp5 = filetmp4.replace("\t", "")
content.append(filetmp5.replace("\n", " "))
path = path.split("-")
y = len(path)-3
kb_name_uri = path[(y)]
kb_name.append(kb_name_uri.replace("_", " "))
return render_template('knowledge-base-api.html', **locals())
@app.route('/knowledge-base', methods=['GET'])
@security
def knowledge_base():
"""Shows the knowledge base markdown files."""
if not session.get('logged_in'):
log( "User with no valid session tries access to page /knowledge-base", "FAIL", "HIGH")
abort(401)
permissions("read")
items = []
id_items = []
full_file_paths = []
full_file_paths = get_filepaths(os.path.join(app.root_path, "markdown/knowledge_base"))
for path in full_file_paths:
id_item = get_num(path)
path = path.split("-")
y = len(path)-3
kb_name_uri = path[(y)]
kb_name = kb_name_uri.replace("_", " ")
items.append(kb_name)
id_items.append(id_item)
return render_template('knowledge-base.html', items=items, id_items=id_items)
@app.route('/users-new', methods=['GET'])
@security
def user_new():
"""show the create new project page"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /user-new", "FAIL", "HIGH")
abort(401)
permissions("manage")
return render_template('users-new.html', csrf_token=session['csrf_token'])
@app.route('/users-add', methods=['POST'])
@security
def users_add():
"""add a new project to database"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /users-add", "FAIL", "HIGH")
abort(401)
permissions("manage")
check_token()
db = get_db()
valAlphaNum(request.form['username'], 1)
valNum(request.form['privID'], 12)
valNum(request.form['pincode'], 12)
safe_userName = encodeInput(request.form['username'])
safe_email = encodeInput(request.form['email'])
safe_privID = encodeInput(request.form['privID'])
pincode = encodeInput(request.form['pincode'])
db.execute('INSERT INTO users (privilegeID, userName, email, password, access, accessToken, activated) VALUES (?, ?, ?, ?, ?, ?, ?)',
[safe_privID, safe_userName, safe_email, "none", "false", pincode, "false"])
db.commit()
return redirect(url_for('users_manage'))
@app.route('/users-manage', methods=['GET'])
@security
def users_manage():
"""show the project list page"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /group-manage", "FAIL", "HIGH")
abort(401)
permissions("manage")
db = get_db()
cur = db.execute('SELECT u.userID, u.userName, u.email, u.privilegeID, u.access, p.privilegeID, p.privilege from users as u JOIN privileges as p ON p.privilegeID = u.privilegeID')
users = cur.fetchall()
return render_template('users-manage.html', users=users, csrf_token=session['csrf_token'])
@app.route('/user-access', methods=['POST'])
@security
def user_access():
"""add a new project to database"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /assign-group", "FAIL", "HIGH")
abort(401)
permissions("manage")
check_token()
db = get_db()
valNum(request.form['userID'], 12)
whiteList("false,true", request.form['access'], 12)
safe_userID = encodeInput(request.form['userID'])
safe_access = encodeInput(request.form['access'])
db.execute('UPDATE users SET access=? WHERE userID=?',
[safe_access, safe_userID])
db.execute('UPDATE counter SET countEvil=? AND block=? WHERE userID=?',
[0, 0, safe_userID])
db.commit()
return redirect(url_for('users_manage'))
@app.route('/group-new', methods=['GET'])
@security
def group_new():
"""show the create new project page"""
if not session.get('logged_in'):
log( "User with no valid session tries access to page /group-new", "FAIL", "HIGH")
abort(401)
permissions("edit")
return render_template('group-new.html', csrf_token=session['csrf_token'])
@app.route('/group-add', methods=['POST'])
@security
def group_add():
"""add a new project to database"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /group-add", "FAIL", "HIGH")
abort(401)
permissions("edit")
check_token()
db = get_db()
valAlphaNum(request.form['groupName'], 3)
safe_inputName = encodeInput(request.form['groupName'])
date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
db.execute('INSERT INTO groups (timestamp, groupName, ownerID) VALUES (?, ?, ?)',
[date, safe_inputName, session['userID']])
db.commit()
#than we select the most last group in order to check id
cur2 = db.execute('SELECT groupID from groups WHERE timestamp=? AND ownerID=?',
[date, session['userID']])
group = cur2.fetchall()
#Do actual loop
for value in group:
groupID = value[0]
#Than we insert this back into groupMembers table so the user is added to group
db.execute('INSERT INTO groupMembers (userID, groupID, ownerID, timestamp) VALUES (?, ?, ?, ?)',
[session['userID'], groupID, session['userID'], date])
db.commit()
return redirect(url_for('group_manage'))
@app.route('/group-users', methods=['GET'])
@security
def group_users():
"""show the project list page"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /group-users", "FAIL", "HIGH")
abort(401)
permissions("edit")
db = get_db()
cur = db.execute('SELECT * from groups where ownerID=?',
[session['userID']])
groups = cur.fetchall()
"""Select all users for adding to group"""
cur2 = db.execute('SELECT username, userID from users')
users = cur2.fetchall()
"""select users by assigned groups for display"""
cur3 = db.execute('SELECT u.username, u.userID, g.groupName, g.groupID, m.groupID, m.userID, m.timestamp, g.ownerID from users as u JOIN groups AS g ON g.groupID = m.groupID JOIN groupMembers as m ON u.userID = m.userID WHERE g.ownerID=? AND u.userName !=? ORDER BY g.groupName ',
[session['userID'], session['userName']])
summary = cur3.fetchall()
return render_template('group-users.html', groups=groups, users=users, summary=summary, csrf_token=session['csrf_token'])
@app.route('/group-add-users', methods=['POST'])
@security
def group_add_users():
"""add a project function"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /project-function-add", "FAIL", "HIGH")
abort(401)
permissions("edit")
check_token()
valNum(request.form['groupName'], 12)
safe_groupID = encodeInput(request.form['groupName'])
"""Check is submitted groupID is owned by user"""
db = get_db()
cur3 = db.execute('SELECT groupID from groups where ownerID=?',
[session['userID']])
owner = cur3.fetchall()
for val in owner:
if int(safe_groupID) == int(val[0]):
f = request.form
for key in f.keys():
for value in f.getlist(key):
found = key.find("test")
if found != -1:
db = get_db()
date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
items = value.split("-")
userID = items[0]
valNum(userID, 12)
safe_userID = encodeInput(userID)
db.execute('INSERT INTO groupMembers (timestamp, groupID, userID, ownerID) VALUES (?, ?, ?, ?)',
[date, safe_groupID, safe_userID, session['userID']])
db.commit()
redirect_url = '/group-users'
return redirect(redirect_url)
@app.route('/user-del', methods=['POST'])
@security
def user_del():
"""delete project from database"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /user-del", "FAIL", "HIGH")
abort(401)
permissions("delete")
check_token()
valNum(request.form['userID'], 12)
safe_userID = encodeInput(request.form['userID'])
db = get_db()
db.execute("DELETE FROM users WHERE userID=?",
[safe_userID])
db.commit()
return redirect("/users-manage")
@app.route('/group-manage', methods=['GET'])
@security
def group_manage():
"""show the project list page"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /group-manage", "FAIL", "HIGH")
abort(401)
permissions("edit")
db = get_db()
cur = db.execute('SELECT * from groups where ownerID=?',
[session['userID']])
groups = cur.fetchall()
return render_template('group-manage.html', groups=groups, csrf_token=session['csrf_token'])
@app.route('/group-del', methods=['POST'])
@security
def group_del():
"""delete project from database"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /group-del", "FAIL", "HIGH")
abort(401)
permissions("manage")
check_token()
valNum(request.form['groupID'], 12)
safe_groupID = encodeInput(request.form['groupID'])
db = get_db()
db.execute("DELETE FROM groups WHERE groupID=? AND ownerID=?",
[safe_groupID, session['userID']])
db.commit()
return redirect("/group-manage")
@app.route('/project-new', methods=['GET'])
@security
def projects():
"""show the create new project page"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /project-new", "FAIL", "HIGH")
abort(401)
permissions("edit")
return render_template('project-new.html', csrf_token=session['csrf_token'])
@app.route('/project-add', methods=['POST'])
@security
def add_entry():
"""add a new project to database"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /project-add", "FAIL", "HIGH")
abort(401)
permissions("edit")
check_token()
db = get_db()
valAlphaNum(request.form['inputName'], 1)
valNum(request.form['inputVersion'], 1)
safe_inputName = encodeInput(request.form['inputName'])
safe_inputVersion = encodeInput(request.form['inputVersion'])
safe_inputDesc = encodeInput(request.form['inputDesc'])
date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
db.execute('INSERT INTO projects (timestamp, projectName, projectVersion, projectDesc, userID, ownerID, groupID) VALUES (?, ?, ?, ?, ?, ?, ?)',
[date, safe_inputName, safe_inputVersion, safe_inputDesc, session['userID'], session['userID'], session['privateGroup']])
db.commit()
return redirect(url_for('project_list'))
@app.route('/assign-group', methods=['POST'])
@security
def assign_group():
"""add a new project to database"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /assign-group", "FAIL", "HIGH")
abort(401)
permissions("edit")
check_token()
db = get_db()
valNum(request.form['projectID'], 12)
valNum(request.form['groupID'], 12)
safe_groupID = encodeInput(request.form['groupID'])
safe_projectID = encodeInput(request.form['projectID'])
"""Check is submitted groupID is owned by user"""
cur = db.execute('SELECT groupID from groups where ownerID=?',
[session['userID']])
owner = cur.fetchall()
for val in owner:
print(val)
if int(safe_groupID) == int(val[0]):
db.execute('UPDATE projects SET groupID=? WHERE projectID=? AND userID=?',
[safe_groupID, safe_projectID, session['userID']])
db.commit()
return redirect(url_for('project_list'))
@app.route('/project-del', methods=['POST'])
@security
def project_del():
"""delete project from database"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /project-del", "FAIL", "HIGH")
abort(401)
permissions("delete")
valNum(request.form['projectID'], 12)
id = request.form['projectID']
check_token()
db = get_db()
db.execute("DELETE FROM projects WHERE projectID=? AND userID=? AND ownerID=?",
[id, session['userID'], session['userID']])
db.commit()
return redirect("/project-list")
@app.route('/project-list', methods=['GET'])
@security
def project_list():
"""show the project list page"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /project-list", "FAIL", "HIGH")
abort(401)
permissions("read")
db = get_db()
#First query is for the users own owned projects
cur = db.execute('SELECT p.projectName, p.projectVersion, p.projectDESC, p.projectID, p.timestamp, p.groupID, g.groupName, g.groupID FROM projects as p JOIN groups as g ON g.groupID = p.groupID where p.userID=? ORDER BY projectID DESC',
[session['userID']])
entries = cur.fetchall()
#select the groups which can be selected by this user
cur3 = db.execute('SELECT * FROM groups WHERE ownerID=?',
[session['userID']])
groups = cur3.fetchall()
return render_template('project-list.html', entries=entries, groups=groups, csrf_token=session['csrf_token'])
@app.route('/project-shared', methods=['GET'])
@security
def project_shared():
"""show the project list page"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /project-list", "FAIL", "HIGH")
abort(401)
permissions("read")
db = get_db()
#Here we see what projects this users was assigned to
cur = db.execute('SELECT p.projectName, p.projectVersion, p.projectDESC, p.projectID, p.timestamp, p.groupID, p.ownerID, m.userID, m.groupID, u.userID, u.userName FROM projects as p JOIN groupMembers as m ON m.groupID = p.groupID JOIN users as u ON u.userID=p.ownerID where m.userID=? AND u.userName !=? ORDER BY p.projectID DESC',
[session['userID'], session['userName']])
entries = cur.fetchall()
return render_template('project-shared.html', entries=entries, csrf_token=session['csrf_token'])
@app.route('/project-options/<project_id>', methods=['GET'])
@security
def projects_options(project_id):
"""show the project options landing page"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /project-options", "FAIL", "HIGH")
abort(401)
permissions("read")
valNum(project_id, 12)
safe_project_id = encodeInput(project_id)
return render_template('project-options.html', project_id=safe_project_id, csrf_token=session['csrf_token'])
@app.route('/project-functions/<project_id>', methods=['GET'])
@security
def project_functions(project_id):
"""show the pproject functions page"""
if not session.get('logged_in'):
log("User with no valid session tries access to page /project-functions", "FAIL", "HIGH")
abort(401)
permissions("read")
techlist = projects_functions_techlist()
valNum(project_id, 12)
safe_project_id = encodeInput(project_id)
db = get_db()
db.commit()
cur = db.execute('SELECT p.paramID, p.functionName, p.functionDesc, p.projectID, p.userID, p.tech, p.techVuln, p.entryDate, t.techName, proj.projectID, proj.groupID, m.userID, m.groupID FROM parameters AS p JOIN techhacks AS t ON p.tech = t.techID JOIN projects as proj ON proj.projectID = p.projectID JOIN groupMembers as m ON m.groupID = proj.groupID WHERE proj.projectID=? AND m.userID=? GROUP BY t.techName',
[safe_project_id, session['userID']])
entries = cur.fetchall()
return render_template('project-functions.html', project_id=project_id, techlist=projects_functions_techlist(), entries=entries, csrf_token=session['csrf_token'])
@app.route('/project-function-del', methods=['POST'])
@security
def function_del():
"""delete a project function"""
if not session.get('logged_in'):
log( "User with no valid session tries access to page /project-function-del", "FAIL", "HIGH")
abort(401)
permissions("delete")
check_token()
valNum(request.form['projectID'], 12)
valNum(request.form['paramID'], 12)
id = request.form['projectID']
id_param = int(request.form['paramID'])
db = get_db()
#First check if the user is allowed to delete this parameter
cur = db.execute('SELECT p.projectID, p.groupID, m.groupID, m.userID from projects as p JOIN groupMembers as m ON m.groupID = p.groupID where m.userID=?',
[session['userID']])
for val in cur:
if int(id) == int(val[0]):
db.execute("DELETE FROM parameters WHERE projectID=? AND paramID=?",
[id, id_param])
db.commit()
redirect_url = "/project-functions/"+str(id)
return redirect(redirect_url)