-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple-guardian-server.py
1844 lines (1602 loc) · 71.8 KB
/
simple-guardian-server.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
from typing import List
try:
import json
import os
import random
import shlex
import time
import logging
import sys
import re
import bcrypt
import eventlet.wsgi
# noinspection PyPackageRequirements
import socketio
from uuid import uuid4
from queue import Queue
from flask import Flask, render_template, session, request, redirect, url_for, make_response, abort, Response
from flask import send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from sqlalchemy.orm import joinedload
from sqlalchemy import desc
from datetime import datetime
from threading import Thread
from http_socket_server import HTTPSocketServer, HSocket
from easycrypt import AESCipher
finally:
from the_runner.requirements_updater import RequirementsUpdater
RequirementsUpdater().auto()
DIR_DATABASES = os.path.abspath('db') # directory with database and config.json
CONFIG = { # dictionary with config. Is overwritten by config.json
'port': 7221, # port of the web server
'forceHTTPS': False, # if set to True, every generated URL if forced to start with https://
'logFile': None, # type: None or str # string is the path to the file in which the logs will be saved
'logger': None, # type: logging.Logger # the Logger object that is used by this application to log.
# Initialized in logging_init()
'newDeviceProfiles': [] # type: List[int] # the list of IDs of profiles which are applied to newly created devices
}
SID_SECRETS = {} # sid: {secret, mail}, stores login data about clients that are trying to log in
SID_LOGGED_IN = {} # sid: mail, stores data logged in clients
# initialize all servers
sio = socketio.Server()
app = Flask(__name__)
CORS(app)
hss = HTTPSocketServer(app)
# set basic config and initialize database
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' # temporary placement, is set to disc file further in code
db = SQLAlchemy(app)
class AppRunning:
"""
This class signalizes or sets if this program's threads should run or should be terminated
"""
app_running = [True]
@staticmethod
def is_running() -> bool:
"""
Tests if the program should be running
:return: True if the program should be running, False if it should terminate itself
"""
return len(AppRunning.app_running) > 0
@staticmethod
def set_running(val: bool):
"""
Sets if the program should be running
:param val: True if the program should be running, False if it should terminate itself
:return: None
"""
if val:
AppRunning.app_running.append(True)
else:
AppRunning.app_running.clear()
@staticmethod
def exit(exit_code): # type: (int) -> None
"""
Signalizes all threads to exit and then exists with specified exit code
:param exit_code:
:return: NOne
"""
AppRunning.set_running(False)
exit(exit_code)
@staticmethod
def sleep_while_running(seconds): # type: (float) -> None
"""
Performs a sleep operation on calling thread. Sleep is interrupted if the program is supposed to terminate
:param seconds: how long should the thread sleep
:return: None
"""
while AppRunning.is_running() and seconds > 0:
sleep = min(1.0, seconds)
time.sleep(sleep)
seconds -= sleep
class AsyncSio:
"""
Asynchronously sending SIO events from other threads
"""
to_send = Queue() # Queue of dictionaries to send to client. Filled by using .emit()
@staticmethod
def init() -> None:
"""
Initializes the server by launching the background task
:return: None
"""
sio.start_background_task(AsyncSio._background_task)
@staticmethod
def _background_task():
"""
While the application is running, fetches new messages from the to_send Queue and emits them to clients
:return: None
"""
while AppRunning.is_running():
eventlet.sleep(1)
while not AsyncSio.to_send.empty():
el = AsyncSio.to_send.get()
sio.emit(el['event'], el['data'], room=el['room'])
@staticmethod
def emit(event, data=None, room=None) -> None:
"""
Allow us to send async sio emits
:param event: name of event to emit
:param data: which data to send
:param room: and to whom to send it
:return: None
"""
AsyncSio.to_send.put({'event': event, 'data': data, 'room': room})
class LoginException(Exception):
pass
"""
Initialize the database schema
"""
# noinspection PyUnresolvedReferences
association_table_user_profile_likes = db.Table('users-profiles_likes', db.Model.metadata,
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('profile_id', db.Integer, db.ForeignKey('profile.id'))
)
# noinspection PyUnresolvedReferences
association_table_device_profile = db.Table('device-profile', db.Model.metadata,
db.Column('device_id', db.Integer, db.ForeignKey('device.id')),
db.Column('profile_id', db.Integer, db.ForeignKey('profile.id'))
)
# noinspection PyUnresolvedReferences
class Profile(db.Model):
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
author = db.relationship('User', backref=db.backref('profiles', lazy=True))
name = db.Column(db.Text, unique=False, nullable=False)
description = db.Column(db.Text, unique=False, nullable=False)
config = db.Column(db.Text, unique=False, nullable=False)
likes = db.relationship("User", secondary=association_table_user_profile_likes)
updated = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
@property
def official(self):
return self.author.admin
def delete(self):
self.__class__.query.filter_by(id=self.id).delete()
# noinspection PyUnresolvedReferences
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
mail = db.Column(db.Text, unique=True, nullable=False)
admin = db.Column(db.Boolean, nullable=False, default=False)
federated_block_list = db.Column(db.Boolean, nullable=False, default=False)
server_block_list = db.Column(db.Boolean, nullable=False, default=False)
password = db.Column(db.Text, unique=False, nullable=False)
def delete(self): # type: () -> None
"""
Deletes this device and all his/her data from the database
:return: None
"""
[[item.delete() for item in items] for items in [self.devices, self.profiles]]
self.__class__.query.filter_by(id=self.id).delete()
@staticmethod
def login(mail, password): # type: (str, str) -> None
"""
Tries to verify the user's mail and password with the database and if verification is successful,
then saves his session
:param mail: user's mail
:param password: user's password
:raise LoginException: when the combination of mail and password is unknown to the database
:return: None if login was successful, if something was wrong then it raises the LoginException
"""
user = User.query.filter_by(mail=mail).first()
if user is None:
raise LoginException('this user does not exist')
if not bcrypt.checkpw(password, user.password):
raise LoginException('this combination of user and password is unknown to me')
session.permanent = True
session['mail'] = mail
@staticmethod
def does_need_login(): # type: () -> False or "Redirect"
"""
Checks if web user has to log in or is already logged in
:return: False if user is logged in or Flask's redirect to the login page if the user is not logged in yet
"""
if 'mail' in session and User.query.filter_by(mail=session['mail']).first() is not None:
return False
return redirect(url_for('login'))
@staticmethod
def list_sids_by_mail(user_mail): # type: (str) -> List[str]
"""
Lists all web user's socket IDs that are logged in and belongs to specific mail
:param user_mail: mail of the user to checks for SIDs of him
:return: list of currently active SIDs assigned to specified user
"""
sids = []
if user_mail in SID_LOGGED_IN.values():
for sid, mail in SID_LOGGED_IN.items():
if mail == user_mail:
sids.append(sid)
return sids
@staticmethod
def is_online_by_mail(user_mail: str) -> bool:
"""
Checks if user is currently online by looking if his mail is assigned to any active web UI's SID
:param user_mail: mail of the user to checks for SIDs of him
:return: True if at least one SID is assigned to this mail, false otherwise
"""
return user_mail in SID_LOGGED_IN.values()
# noinspection PyUnresolvedReferences
class Device(db.Model):
id = db.Column(db.Integer, primary_key=True)
uid = db.Column(db.Text, unique=True, nullable=False)
name = db.Column(db.Text, unique=False, nullable=False)
secret = db.Column(db.Text, unique=False, nullable=True)
version = db.Column(db.Text, unique=False, nullable=True, default="0.0")
profiles = db.relationship("Profile",
secondary=association_table_device_profile, backref=db.backref('devices', lazy=True))
installed = db.Column(db.Boolean, nullable=False, default=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
user = db.relationship('User', backref=db.backref('devices', lazy=True))
@property
def config(self): # type: () -> str
"""
Get JSON file profile for the simple guardian client with online configuration
:return: content of the JSON profile file
"""
data = {}
for profile in self.profiles:
profile_data = json.loads(profile.config)
# add profile ID to identify this profile when using legacy web GUI
profile_data[list(profile_data.keys())[0]]['hubID'] = profile.id
data.update(profile_data)
return json.dumps(data)
@config.setter
def config(self, value): # type: (str) -> None
"""
When legacy web UI is used to set profiles directly, map them based on the hubID property inside them
:param value: JSON profile format
:return: None
"""
value = json.loads(value)
new_profiles = set()
for profile_data in value.values():
if 'hubID' not in profile_data:
continue
profile = Profile.query.filter_by(id=profile_data.get('hubID')).first()
if profile is None:
continue
new_profiles.add(profile)
if profile not in self.profiles:
self.profiles.append(profile)
# remove profiles that were not part of the pushed config
[self.profiles.remove(profile) for profile in
{profile for profile in self.profiles if profile not in new_profiles}]
db.session.commit()
def is_online(self) -> bool:
"""
Check if connection between the device and the server is active
:return: True if connection between the device and the server is active, False otherwise
"""
return self.id in HSSOperator.sid_device_id_link.values()
def get_sid(self) -> str or None:
"""
Gets the SID of this device
:return: SID if device is connected to this server, None if connection with this server is not estabilished
"""
vals = HSSOperator.sid_device_id_link.values()
if self.id not in vals:
return None
return list(HSSOperator.sid_device_id_link.keys())[list(vals).index(self.id)]
def delete(self): # type: () -> None
"""
Deletes this device and all cached attacks and bans linked with this device
:return: None
"""
[[item.delete() for item in items] for items in [self.attacks, self.bans, self.offline_actions]]
if self.is_online():
del HSSOperator.sid_device_id_link[self.get_sid()]
self.__class__.query.filter_by(id=self.id).delete()
@staticmethod
@sio.on('listDevices')
def list_for_user(sid, asynchronous=False): # type: (str, bool) -> None
"""
Lists devices for the user online on web UI
:param sid: SID of the user on the web UI the list of devices will be send to
:param asynchronous: True if you are not calling this function from Flask thread
:return: None
"""
if sid not in SID_LOGGED_IN:
return
# emit dict of device names and uids
f_emit = sio.emit if not asynchronous else AsyncSio.emit
f_emit('deviceList',
{device.uid: {'name': device.name, 'installed': device.installed,
'online': False if not device.installed else device.is_online()} for device in
User.query.filter_by(mail=SID_LOGGED_IN[sid]).options(
joinedload('devices')).first().devices}, room=sid)
@staticmethod
@sio.on('deviceNew')
def create_new(sid, device_name): # type: (str, str) -> None
"""
Creates new device and lists client all his devices
:param sid: SID of the user on the web UI the list of devices will be send to
:param device_name: name of the new device
:return: None
"""
if sid not in SID_LOGGED_IN:
return
while True:
device_uid = uuid4().hex
if Device.query.filter_by(uid=device_uid).first() is None:
break
device = Device(name=device_name, uid=device_uid, user=User.query.filter_by(mail=SID_LOGGED_IN[sid]).first())
db.session.add(device)
db.session.commit()
Device.list_for_user(sid)
@staticmethod
@sio.on('deviceDelete')
def device_delete(sid, device_id): # type: (str, int) -> None
"""
Deletes the device and lists client all his left devices
:param sid: SID of the user on the web UI the list of devices will be send to
:param device_id: id of the device to be deleted
:return: None
"""
if sid not in SID_LOGGED_IN:
return
device = Device.query.filter_by(uid=device_id, user=User.query.filter_by(mail=SID_LOGGED_IN[sid]).first())
device.delete()
db.session.commit()
Device.list_for_user(sid)
class Attack(db.Model):
id = db.Column(db.Integer, primary_key=True)
time = db.Column(db.Integer, unique=False, nullable=True)
profile = db.Column(db.Text, unique=False, nullable=True)
user = db.Column(db.Text, unique=False, nullable=True)
ip = db.Column(db.Text, unique=False, nullable=True)
device_id = db.Column(db.Integer, db.ForeignKey('device.id'), nullable=False)
device = db.relationship('Device', backref=db.backref('attacks', lazy=True))
def delete(self):
self.__class__.query.filter_by(id=self.id).delete()
class Ban(db.Model):
id = db.Column(db.Integer, primary_key=True)
time = db.Column(db.Integer, unique=False, nullable=True)
ip = db.Column(db.Text, unique=False, nullable=True)
attacks_count = db.Column(db.Integer, unique=False, nullable=True)
device_id = db.Column(db.Integer, db.ForeignKey('device.id'), nullable=False)
device = db.relationship('Device', backref=db.backref('bans', lazy=True))
def delete(self):
self.__class__.query.filter_by(id=self.id).delete()
class OfflineAction(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, unique=False, nullable=False)
value = db.Column(db.Text, unique=False, nullable=True)
device_id = db.Column(db.Integer, db.ForeignKey('device.id'), nullable=False)
device = db.relationship('Device', backref=db.backref('offline_actions', lazy=True))
def delete(self):
self.__class__.query.filter_by(id=self.id).delete()
class UserSecret:
def __init__(self, secret_key): # type: (str) -> None
self.__cypher = AESCipher(secret_key)
def make(self, user): # type: (str) -> str
return self.__cypher.encrypt(json.dumps({'user': user}))
def parse_user(self, secret): # type: (str) -> str or None
try:
user_data_string = self.__cypher.decrypt(secret)
except ValueError:
return None
if not len(user_data_string):
return None
return json.loads(user_data_string)['user']
@app.route("/api/serviceName")
def get_service_name(): # type: () -> str
"""
Used by client when pairing to verify that he has connected to right device
:return: name of this service
"""
return "simple-guardian-server"
def init_api():
# noinspection PyTypeChecker
user_secret = UserSecret(CONFIG["app_secret"])
def make_respond(message, status='ok'):
return Response(json.dumps({'status': status, 'message': message}), mimetype='application/json')
def get_user(): # type: () -> User or Response
"""
Parses the user from sg-auth header
:return: If user sent no or invalid header then response for him to login is returned. Otherwise is returned his
mail parsed from the header
"""
need_login_response = make_respond('login required', status='needsLogin')
if 'sg-auth' not in request.headers:
return need_login_response
user_mail = user_secret.parse_user(request.headers['sg-auth'])
user = User.query.filter_by(mail=user_mail).first()
return user if user is not None else need_login_response
@app.route("/api/user/whoami")
def api_user_whoami():
user = get_user()
if type(user) == Response:
return user
return make_respond({'username': user.mail, 'id': user.id})
@app.route("/api/user/isOn/federatedSharing", methods=['GET', 'POST'])
def api_user_user_is_on_federated_sharing():
user = get_user() # type: User
if type(user) == Response:
return user
if request.method == 'POST':
user.federated_block_list = request.json.get('on')
db.session.commit()
return make_respond({'on': user.federated_block_list})
@app.route("/api/device/list")
def api_device_list():
user = get_user()
if type(user) == Response:
return user
return make_respond([{'name': device.name, 'id': device.uid,
'status': 'online' if device.is_online()
else 'offline' if device.installed else 'not-linked'}
for device in
User.query.filter_by(mail=user.mail).options(
joinedload('devices')).first().devices])
@app.route("/api/user/login", methods=["POST"])
def api_user_login():
mail = request.json.get('mail', '')
password = request.json.get('password', '').encode('utf8')
try:
User.login(mail, password)
return make_respond({'login': 'ok', 'key': user_secret.make(mail)})
except LoginException:
CONFIG['logger'].warn("%s tried to log in as user \"%s\", but failed" % (request.remote_addr, mail))
return make_respond({'login': 'failed', 'key': None})
@app.route("/api/user/delete")
def api_user_delete():
user = get_user() # type: User
if type(user) == Response:
return user
user.delete()
db.session.commit()
return make_respond(True)
@app.route("/api/user/password/check", methods=["POST"])
def api_user_password_check():
user = get_user()
if type(user) == Response:
return user
password = request.json.get('password', '').encode('utf8')
return make_respond(bcrypt.checkpw(password, user.password))
@app.route("/api/user/password/change", methods=["POST"])
def api_user_password_change():
user = get_user()
if type(user) == Response:
return user
password = request.json.get('password', '').encode('utf8').strip()
if len(password) == 0:
return make_respond('No new password supplied', status='error')
user.password = bcrypt.hashpw(password, bcrypt.gensalt())
db.session.commit()
return make_respond('ok')
@app.route("/api/user/register", methods=["POST"])
def api_user_register():
mail = request.json.get('mail', '').strip()
password = request.json.get('password', '').encode('utf8').strip()
if len(mail) == 0 or len(password) == 0:
return make_respond({'register': 'error', 'message': 'You must send both mail and password'})
if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", mail):
return make_respond({'register': 'error', 'message': 'This mail is not mail'})
if User.query.filter_by(mail=mail).first() is not None:
return make_respond({'register': 'error', 'message': 'This user already exists'})
db.session.add(User(mail=mail, password=bcrypt.hashpw(password, bcrypt.gensalt())))
db.session.commit()
return make_respond({'register': 'ok', 'message': 'You are registered now', 'key': user_secret.make(mail)})
@app.route("/api/hub/list")
def api_hub_list():
"""
Lists all hub profiles and returns them
:return: data about hub profiles in JSON format
"""
return make_respond(
[{'name': profile.name, 'likes': len(profile.devices), 'id': profile.id, 'official': profile.official}
for profile in Profile.query.all()])
@app.route("/api/hub/profile/-1", methods=['POST'])
def api_hub_profile_new():
return api_hub_profile(-1)
@app.route("/api/hub/profile/<int:profile_id>/send", methods=['POST'])
def api_hub_profile_send(profile_id): # type: (int) -> any
user = get_user()
if type(user) == Response:
return user
profile = Profile.query.filter_by(id=profile_id).first() # type: Profile
devices = [Device.query.filter_by(uid=uid, user=user).first() for uid in request.json.get('devices', [])]
if None in devices:
return make_respond('This devices does not exist', status='error')
if profile is None:
return make_respond('This profile does not exist', status='error')
for device in devices:
if profile in device.profiles:
continue
device.profiles.append(profile)
if device.is_online():
hss.emit(device.get_sid(), 'config', device.config)
db.session.commit()
return make_respond('OK')
@app.route("/api/hub/profile/<int:profile_id>", methods=['GET', 'POST'])
def api_hub_profile(profile_id): # type: (int) -> any
"""
GET: Lists all hub profiles and returns them
POST: take profile as data param and save it into database and return success message
:return: data about hub profiles in JSON format
"""
profile = Profile.query.filter_by(id=profile_id).first() # type: Profile
new_profile = False
if profile is None and profile_id == -1 and request.method == 'POST':
profile = Profile()
new_profile = True
if profile is None:
return make_respond('This profile does not exist', status='error')
if request.method == 'GET':
return make_respond({
'name': profile.name,
'id': profile.id,
'description': profile.description,
'config': list(json.loads(profile.config).values())[0],
'author': profile.author.id
})
user = get_user()
if type(user) == Response:
return user
if not new_profile and profile.author != user:
return make_respond('You are not allowed to do that', status='error')
data = request.json.get('data')
if data is None:
return make_respond('You forgot to send profile data', status='error')
profile.author = user
profile.updated = datetime.now()
profile.description = data['description']
profile.name = data['name']
profile.config = json.dumps({profile.name: data['config']})
if new_profile:
db.session.add(profile)
db.session.commit()
return make_respond({'id': profile.id, 'message': 'Profile saved'})
@app.route("/api/hub/profile/delete", methods=["POST"])
def api_hub_profile_delete():
"""
Deletes profile is user is his author
:return: message about success / fail
"""
user = get_user()
if type(user) == Response:
return user
profile = Profile.query.filter_by(id=request.json.get('id')).first() # type: Profile
if profile is None:
return make_respond('This profile does not exist', status='error')
if user != profile.author:
return make_respond('You do not have permissions to do this', status='error')
profile.delete()
db.session.commit()
return make_respond("Profile deleted")
@app.route("/api/hub/profile/remove", methods=["POST"])
def api_hub_profile_remove():
"""
Removes profile from device
:return: message about success / fail
"""
user = get_user()
if type(user) == Response:
return user
profile = Profile.query.filter_by(id=request.json.get('id')).first() # type: Profile
device = Device.query.filter_by(uid=request.json.get('device')).first() # type: Device
if profile is None:
return make_respond('This profile does not exist', status='error')
if device is None:
return make_respond('This device does not exist', status='error')
if device.user != user:
return make_respond('You do not have permission to to this', status='error')
if profile not in device.profiles:
return make_respond('This profile is not assigned to this device', status='error')
device.profiles.remove(profile)
db.session.commit()
return make_respond("%s removed from %s" % (profile.name, device.name))
@app.route("/api/device/<string:device_uid>/info")
def api_device_info(device_uid): # type: (str) -> any
"""
Fetches info about device
:return:
"""
user = get_user()
if type(user) == Response:
return user
device = Device.query.filter_by(uid=device_uid, user=user).first()
if device is None:
return make_respond({}, status='error')
device_attacks = Attack.query.filter_by(device=device).order_by(desc(Attack.time)).all()
device_bans = Ban.query.filter_by(device=device).order_by(desc(Ban.time)).all()
time_yesterday = time.time() - (24 * 3600)
return make_respond({
'id': device.uid,
'name': device.name,
'status': 'online' if device.is_online() else 'offline' if device.installed else 'not-linked',
'version': device.version,
'attacks': [
{
'id': attack.id,
'ip': attack.ip,
'time': attack.time,
'user': attack.user,
'profile': attack.profile
} for attack in device_attacks[:300]
],
'bans': [
{
'id': ban.id,
'ip': ban.ip,
'time': ban.time,
'attacksCount': ban.attacks_count
} for ban in device_bans[:300]
],
'stats': {
'attacks': {
'total': len(device_attacks),
'today': len([a for a in device_attacks if a.time > time_yesterday])
},
'bans': {
'total': len(device_bans),
'today': len([b for b in device_bans if b.time > time_yesterday])
}
},
'profiles': [profile.id for profile in device.profiles]
})
@app.route("/api/device/create", methods=["POST"])
def api_device_create():
"""
Creates new device for user
:return:
"""
user = get_user()
if type(user) == Response:
return user
device_name = request.json.get('name', '').strip()
if Device.query.filter_by(name=device_name, user=user).first() is not None:
return make_respond({'status': 'error', 'message': 'Device with this name already exists'})
while True:
device_uid = uuid4().hex
if Device.query.filter_by(uid=device_uid).first() is None:
break
new_device_profiles = []
for profile_id in CONFIG['newDeviceProfiles']:
profile = Profile.query.filter_by(id=profile_id).first()
if profile is not None:
new_device_profiles.append(profile)
device = Device(name=device_name, uid=device_uid, user=user, profiles=new_device_profiles)
db.session.add(device)
db.session.commit()
return make_respond({'status': 'ok', 'message': 'Device created', 'id': device_uid})
@app.route("/api/device/update", methods=["POST"])
def api_device_update():
"""
Sends request to the user's device to update it
:return: JSON {success: boolean, message: description}
"""
user = get_user()
if type(user) == Response:
return user
device_uid = request.json.get('id', '').strip()
device = Device.query.filter_by(uid=device_uid, user=user).first()
if device is None:
return make_respond({'success': False, 'message': 'Device does not exist'})
device_sid = device.get_sid()
if device_sid is None:
if OfflineAction.query.filter_by(device=device, name='update').first() is not None:
return make_respond({'success': True, 'message': 'This action is already in queue'})
db.session.add(OfflineAction(device=device, name='update', value=None))
db.session.commit()
return make_respond({'success': True, 'message': 'The action will be performed'
' when the device will become online again'})
hss.emit(device_sid, 'update')
return make_respond({'success': True, 'message': 'Request sent'})
@app.route("/api/device/unban", methods=["POST"])
def api_device_unban():
"""
Sends request to the user's device to unban specific IP
:return: JSON {success: boolean, message: description}
"""
user = get_user()
if type(user) == Response:
return user
device_uid = request.json.get('id', '').strip()
unban_ip = request.json.get('ip', '').strip()
device = Device.query.filter_by(uid=device_uid, user=user).first()
if device is None:
return make_respond({'success': False, 'message': 'Device does not exist'})
device_sid = device.get_sid()
if device_sid is None:
if OfflineAction.query.filter_by(device=device, name='unblock_ip', value=unban_ip).first() is not None:
return make_respond({'success': True, 'message': 'This action is already in queue'})
db.session.add(OfflineAction(device=device, name='unblock_ip', value=unban_ip))
db.session.commit()
return make_respond({'success': True, 'message': 'The action will be performed'
' when the device will become online again'})
hss.emit(device_sid, 'unblock_ip', unban_ip)
ban = Ban.query.filter_by(device=device, ip=unban_ip)
if ban is not None:
ban.delete()
return make_respond({'success': True, 'message': 'Request sent'})
@app.route("/api/device/delete", methods=["POST"])
def api_device_delete():
"""
Deletes user's device. (specified in the "id" POST key)
:return: JSON {success: boolean, message: description}
"""
user = get_user()
if type(user) == Response:
return user
device_uid = request.json.get('id', '').strip()
device = Device.query.filter_by(uid=device_uid, user=user).first() # type: Device
if device is None:
return make_respond({'success': False, 'message': 'Device does not exist'})
device.delete()
db.session.commit()
return make_respond({'success': True, 'message': 'Device deleted'})
@app.route("/api/device/rename", methods=["POST"])
def api_device_rename():
"""
Renames user's device. (specified in the "id" and "name" POST keys)
:return: JSON {success: boolean, message: description}
"""
user = get_user()
if type(user) == Response:
return user
device_uid = request.json.get('id', '').strip()
device_name = request.json.get('name', '').strip()
if len(device_name) == 0:
return make_respond({'success': False, 'message': 'Name can not be empty'})
device = Device.query.filter_by(uid=device_uid, user=user).first()
if device is None:
return make_respond({'success': False, 'message': 'Device does not exist'})
device.name = device_name
db.session.commit()
return make_respond({'success': True, 'message': 'Device renamed'})
@app.route("/api/device/new/<string:user_mail>/<string:device_id>", methods=['GET', 'POST'])
def api_device_new(user_mail, device_id): # type: (str, str) -> str
"""
On GET shows user information that this page is accessible only by using the SG client
When SG client accesses this page, it gives him login keys and pairs the device with the user's mail
:param user_mail: mail of user the calling device will be assigned to
:param device_id: UUID of the device that is pairing
:return: login data as JSON if device gave us correct information, 404 otherwise
"""
if request.method == "GET":
return "this is meant to be run by your simple-guardian-client, not by your web browser. sorry."
user = User.query.filter_by(mail=user_mail).first()
if user is None:
abort(404)
device = Device.query.filter_by(user=user, uid=device_id).first()
if device is None or device.installed: # if device is logged in already, we cannot login anymore
abort(404)
device.secret = uuid4().hex
device.installed = True
db.session.commit()
[Device.list_for_user(sid, asynchronous=True) for sid in User.list_sids_by_mail(device.user.mail)]
return json.dumps({'service': 'simple-guardian',
'device_id': device_id, 'device_secret': device.secret, 'server_url': request.host_url})
@app.route("/api/tutorial/list")
def api_tutorial_list(): # type: () -> "json file"
return send_from_directory('static/tutorials', 'list.json')
@app.route("/api/tutorial/<int:article_id>")
def api_tutorial_get(article_id): # type: (int) -> "md file"
if article_id < 0:
abort(404)
return
with open('static/tutorials/list.json', 'r') as f:
articles = json.load(f)
if article_id >= len(articles):
abort(404)
return
return send_from_directory('static/tutorials', articles[article_id]['text'])
def init_old_web_ui():
@app.route("/api/getSidSecret")
def get_new_sid(): # type: () -> str or "redirect"
"""
Requests a secret for user's SID. User must be logged in in order to access this page
so we are sure to who are we giving the secret to SID
:return: secret for authentication user's socket
"""
needs_login = User.does_need_login()
if needs_login:
return needs_login
if 'sid' not in request.args:
return 'who are you?'
if request.args['sid'] not in SID_SECRETS:
return 'you are not connected'
SID_SECRETS[request.args['sid']]['mail'] = session['mail']
return SID_SECRETS[request.args['sid']]['secret']
@app.route('/control')
def control_panel():
"""
Shows control panel to the user
User must be logged in
:return: control panel template
"""
needs_login = User.does_need_login()
if needs_login:
return needs_login
return render_template('main-panel.html', username=session.get('mail', 'undefined'), logged_in=True)
@app.route('/user', methods=['GET', 'POST'])
def user_data():
"""
Shows panel with user config data and allows them to change them
User must be logged in
:return: user data template
"""
needs_login = User.does_need_login()
if needs_login:
return needs_login
message = ""
if request.method == "POST":
try:
user = User.query.filter_by(mail=session['mail']).first()
if not bcrypt.checkpw(request.form['passCurrent'].encode('utf8'), user.password):
message = "current password does not match"
raise InterruptedError
user.password = bcrypt.hashpw(request.form['passNew'].encode('utf8'), bcrypt.gensalt())
if request.form.get('reallyChangeMail', '') == 'on':
new_mail = request.form['mail']
if User.query.filter_by(mail=new_mail).first() is not None:
message = "user with this mail already exists"