/
netpop.py
857 lines (630 loc) · 24.5 KB
/
netpop.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
import configparser
from flask import Flask, render_template, flash, request, url_for, redirect, session, jsonify
from flask_mail import Mail, Message
import time
from dbconnect import connection
from checks import NP_DBStatus
from wtforms import Form, validators, PasswordField, StringField, SelectField
from passlib.hash import sha256_crypt
from pymysql import escape_string as thwart
import gc
from functools import wraps
from flask_executor import Executor
from os import urandom
import secrets
from secrets import token_urlsafe
# Random Variables
time_now = time.strftime("%H:%M %m-%d-%Y")
############
# Settings #
############
config = configparser.ConfigParser()
config.read('conf/config.ini')
netpop_hostname = config['SKIMMER']['HOSTNAME']
netpop_logging_to_console = config['SKIMMER']['LOG_TO_CONSOLE']
# Logging Settings
if netpop_logging_to_console:
import logging
logging.basicConfig(level=logging.DEBUG,
filename="netpop.log",
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
# Flask Settings
app = Flask(__name__)
executor = Executor(app)
app.secret_key = urandom(24)
app.config.update(
# Disabled for dev
# SESSION_COOKIE_SECURE = True,
# REMEMBER_COOKIE_SECURE = True,
DEBUG=True,
# EMAIL SETTINGS
MAIL_SERVER=config['EMAIL']['EMAIL_SERVER'],
MAIL_PORT=config['EMAIL']['EMAIL_PORT'],
MAIL_USE_SSL=config['EMAIL']['EMAIL_USE_SSL'],
MAIL_USERNAME=config['EMAIL']['EMAIL_USERNAME'],
MAIL_PASSWORD=config['EMAIL']['EMAIL_PASSWORD'])
mail = Mail(app)
# Executor Settings
app.config['EXECUTOR_MAX_WORKERS'] = 4
# Admin Status Check
def admin_check(c_name):
c, conn = connection()
u_name = thwart(c_name)
admin_status = False
try:
data = c.execute("SELECT * FROM users WHERE username = %s", u_name, )
user_rank = c.fetchone()[8]
if user_rank >= 3:
session['user_rank'] = '3'
session['admin_status'] = True
session.modified = True
admin_status = True
except Exception:
admin_status = False
c.close()
conn.close()
gc.collect()
return admin_status
# Verify user has a valid token before allowing access to the update password page for their account.
def token_check(c_token):
c, conn = connection()
token_status = False
try:
x = c.execute("SELECT * FROM users WHERE reset_token = %s", c_token, )
if int(x) == 0:
token_status = False
else:
token_status = True
except Exception:
token_status = False
c.close()
conn.close()
gc.collect()
return token_status
# Send Email
def send_mail(rec, u_name, msg_type):
email_cont = []
# Logs alerts and emails to cont_log table
def contact_log(recip, message_type):
try:
c, conn = connection()
c.execute("INSERT INTO cont_log (recipient, date_sent, message_type) VALUES (%s, %s, %s)",
(thwart(recip),
time.strftime("%H:%M:%S %m-%d-%Y"),
message_type),)
conn.commit()
print(f"Message sent to {recip} as {message_type} and logged to db")
except Exception as e:
if netpop_logging_to_console:
app.logger.error(e)
c.close()
conn.close()
gc.collect()
def message_type():
if msg_type.lower() == "new_user":
msg_subject = "Welcome to Netpops!"
msg_html = f'<p>Hey {u_name.capitalize()}!\
<br>\
Welcome to NetPops {u_name.capitalize()}!\
<br>\
Thanks!\
<br>\
NetPop</p>'
msg_body = f"Welcome to Netpops and Thanks for registering {u_name.capitalize()}!"
msg = [msg_subject, msg_body, msg_html]
print("Welcome Email Sent.")
return msg
elif msg_type.lower() == "reset_password":
c, conn = connection()
data = c.execute("SELECT * FROM users WHERE username = %s", u_name, )
result = c.fetchone()
token = result[11]
full_url = f"{netpop_hostname}/reset_password/{token}"
msg_subject = "NetPops Password Reset"
msg_html = f'<p>Hey {u_name.capitalize()}!\
<br>\
We got a request to reset your password.\
<br>\
<p>Click <a href="{full_url}">HERE</a> to it.\
<br>\
<p>Or open this <strong>{full_url}</strong> in your browser.\
<br>\
<p>If you did not request this password reset, then just ignore this email.\
<br>\
Thanks!\
<br>\
NetPops</p>'
msg_body = f"Looks like you're trying to reset your password for {u_name}. \
Go to {full_url} to reset you password. If you did not request \
this password change you can ignore this message."
msg = [msg_subject, msg_body, msg_html]
return msg
elif msg_type.lower() == "password_update_confirm":
c, conn = connection()
data = c.execute("SELECT * FROM users WHERE username = %s", u_name, )
msg_subject = "NetPops Password Changed"
msg_html = f'<p>Hey {u_name.capitalize()}!\
<br>\
Your password was successfully changed!\
<br>\
Thanks!\
<br>\
NetPop</p>'
msg_body = "Your password was successfully changed! Thanks!"
msg = [msg_subject, msg_body, msg_html]
return msg
else:
if netpop_logging_to_console:
app.logger.error(e)
email_cont = message_type()
try:
msg = Message(email_cont[0], sender="netpops@digidogsolutions.com", recipients=[rec,])
msg.body = email_cont[1]
msg.html = email_cont[2]
mail.send(msg)
print("calling contact_log function")
contact_log(rec, message_type)
print("contact_log function has completed.")
except Exception as e:
if netpop_logging_to_console:
app.logger.error(e)
################
### Wrappers ###
################
# Login Required - Wrapper
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash("You need to login first")
return redirect(url_for('login_page'))
return wrap
# Admin Required - Wrapper
def admin_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if admin_check(session['username']) == True:
return f(*args, **kwargs)
else:
return redirect(url_for('access_denied'))
return wrap
# Token Required - Wrapper
def token_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if token_check(session['token']) == True:
return f(*args, **kwargs)
else:
return redirect(url_for('access_denied'))
return wrap
##############
### Routes ###
##############
# Home Page
@app.route('/')
def homepage():
return render_template("main.html")
# Logout Page
@app.route("/logout/")
@login_required
def logout():
session.clear()
flash("You've been logged out")
return redirect(url_for('homepage'))
# Login Page
@app.route('/login/', methods=["GET", "POST"])
def login_page():
try:
c, conn = connection()
if request.method == "POST":
secure_un = thwart(request.form['username'], )
def list_return():
data = c.execute("SELECT * FROM users WHERE username = %s", secure_un)
data = c.fetchone()[5]
return data
if sha256_crypt.verify(request.form['password'], list_return()):
session['logged_in'] = True
session['username'] = request.form['username']
if admin_check(session['username']):
session['admin_status'] = True
else:
session['admin_status'] = False
c.execute("UPDATE users SET lastlogin=%s WHERE username=%s",
(time.strftime("%H:%M:%S %m-%d-%Y"), secure_un))
conn.commit()
flash(f"Welcome, {session['username'].capitalize()}! You are now logged in!")
return redirect(url_for('monitor'))
gc.collect()
if netpop_logging_to_console:
app.logger.info(f"No user found for {request.form['username']}")
flash("Invalid Login. Try Again.")
return render_template("login.html")
return render_template("login.html")
except Exception as e:
return render_template("error.html", error=e)
# Registration Page
class RegistrationForm(Form):
username = StringField('Username', [validators.Length(min=4, max=20)])
email = StringField('Email Address', [validators.Length(min=6, max=50)])
password = PasswordField('Password', [validators.DataRequired(),
validators.EqualTo('confirm', message='Passwords do not match.')])
confirm = PasswordField('Confirm Password')
@app.route('/register/', methods=['GET', 'POST'])
def register_page():
rank = '2' # (Sets all users as Standard Users on registration)
try:
form = RegistrationForm(request.form)
c, conn = connection()
if request.method == "POST" and form.validate():
username = form.username.data
email = form.email.data
password = sha256_crypt.hash((str(form.password.data)))
x = c.execute("SELECT * FROM users WHERE username = %s", (username,))
if int(x) > 0:
flash("That username is taken. Try another!")
return render_template("register.html", form=form)
else:
c.execute(
"INSERT INTO users (username, password, email, rank, lastlogin, account_creation) VALUES (%s, %s, %s, %s, %s, %s)",
(thwart(username),
thwart(password),
thwart(email),
rank,
time.strftime("%H:%M:%S %m-%d-%Y"),
time.strftime("%H:%M:%S %m-%d-%Y")))
conn.commit()
flash(f"Thanks for registering {username.capitalize()}!")
c.close()
conn.close()
gc.collect()
print("Sending Welcome Email.")
executor.submit(send_mail(email, username, "new_user"))
session['logged_in'] = True
session['username'] = username
session['rank'] = '2'
return redirect(url_for('monitor'))
return render_template("register.html", form=form)
except Exception as e:
if netpop_logging_to_console:
app.logger.error(e)
# return render_template("error.html", error=e)
return e
# Forgot Password
@app.route('/reset_password/', methods=["GET", "POST"])
def reset_password():
try:
c, conn = connection()
if request.method == "POST":
x = c.execute("SELECT * FROM users WHERE username = %s", thwart(request.form['username'], ))
if int(x) == 0:
app.logger.info(f"No account found for for {request.form['username']}")
return render_template("reset_password.html")
else:
data = c.execute("SELECT * FROM users WHERE username = %s", thwart(request.form['username'], ))
email = c.fetchone()[6]
username = request.form['username']
secure_un = thwart(username.lower())
token = secrets.token_urlsafe(32)
secure_token = thwart(token)
c.execute("UPDATE users SET reset_token=%s WHERE username=%s", (secure_token, secure_un))
c.execute("UPDATE users SET reset_password=%s WHERE username=%s", (1, secure_un))
conn.commit()
executor.submit(send_mail(email, username, "reset_password"))
flash(f"Please check your inbox for reset password instructions for {username}.")
return redirect(url_for('homepage'))
return render_template("reset_password.html")
c.close()
conn.close()
gc.collect()
except Exception as e:
return render_template("error.html", error=e)
# Reset Password Token reply
@app.route('/reset_password/<token>')
def reset_password_token(token):
try:
c, conn = connection()
x = c.execute("SELECT * FROM users WHERE reset_token = %s", token)
if int(x) == 0:
app.logger.info(f"No token found for for {token}")
return 404
else:
session['token'] = token
return redirect(url_for('update_password'))
except Exception as e:
return render_template("error.html", error=e)
# Change/Update Password Page
@app.route('/update_password/', methods=["GET", "POST"])
@token_required
def update_password():
try:
c, conn = connection()
if request.method == "POST":
c, conn = connection()
token = session['token']
data = c.execute("SELECT * FROM users WHERE reset_token = %s", (thwart(token),))
result = c.fetchone()
username = result[3]
email = result[6]
password = request.form['password']
c_password = request.form['c_password']
hashed_password = sha256_crypt.hash(password)
if password == c_password:
c.execute("UPDATE users SET password=%s WHERE username=%s", (thwart(hashed_password), username))
c.execute("UPDATE users SET reset_token=NULL WHERE username=%s", (username))
c.execute("UPDATE users SET reset_password=0 WHERE username=%s", (username))
conn.commit()
session.pop('token')
executor.submit(send_mail(email, username, "password_update_confirm"))
flash("Your password has been changed! Try your login now.")
return redirect(url_for('login_page'))
else:
flash("Uh-Oh... Your passwords didn't match. Let's try that again.")
return redirect(url_for('update_password'))
return render_template("update_password.html")
c.close()
conn.close()
gc.collect()
except Exception as e:
# return e
return render_template("error.html", error=e)
# Monitor Page
@app.route('/monitor/')
@login_required
def monitor():
def total_endpoints():
try:
c, conn = connection()
c.execute("SELECT count(*) FROM endpoints;")
results = c.fetchone()
results = results[0]
c.close()
conn.close()
gc.collect()
except Exception:
results = 'e'
return results
def down_endpoints():
try:
c, conn = connection()
c.execute("SELECT count(*) FROM endpoints WHERE endpoint_status = 0;")
results = c.fetchone()
results = results[0]
c.close()
conn.close()
except Exception:
results = 'e'
return results
def warning_endpoints():
try:
c, conn = connection()
c.execute("SELECT count(*) FROM endpoints WHERE endpoint_status = 2;")
results = c.fetchone()
results = results[0]
c.close()
conn.close()
except Exception:
results = 'e'
return results
def host_list():
try:
c, conn = connection()
c.execute("SELECT last_check, endpoint_status, endpoint_name FROM netpop.endpoints;")
results = c.fetchall()
c.close()
conn.close()
except Exception:
results = 'e'
return results
try:
return render_template("monitor.html", host_l=host_list(), time_now=time_now, t_endpoints=total_endpoints(),
down_endpoints=down_endpoints(), warn_endpoints=warning_endpoints())
except Exception as e:
if netpop_logging_to_console:
app.logger.error(e)
# return render_template("error.html", error=e)
return e
# Settings page (Admin only)
@app.route('/settings/')
@login_required
@admin_required
def settings():
def total_endpoints():
try:
c, conn = connection()
c.execute("SELECT count(*) FROM endpoints;")
results = c.fetchone()
results = results[0]
c.close()
conn.close()
gc.collect()
except Exception:
results = 'e'
return results
try:
return render_template("settings.html", db_status=NP_DBStatus(), t_endpoints=total_endpoints())
except Exception as e:
return render_template("error.html", error=e)
# Add Endpoint (Admin Only)
class AddEndpointForm(Form):
endpoint_name = StringField('Endpoint Name')
hostname = StringField('Hostname')
ip_addr = StringField('IP Address')
zip_code = StringField('Zip Code')
check_type = SelectField('Check Type', choices = [('ping', 'Ping this endpoint'),
('http', 'Check the status code of this Website'),
('content', 'Check if content missing or changed from a website.'),
('port','Check if a port is open or not on this endpoint.')])
check_interval = SelectField('Check Interval', choices = [('60', 'Every 1 Minute'),
('300', 'Every 5 Minute'),
('900', 'Every 15 Minute'),
('1800', 'Every 30 Minute'),
('3600','Every 1 hour'),
('86400','Every Day')])
@app.route('/add_endpoint/', methods=["GET", "POST"])
@login_required
@admin_required
def add_endpoint():
try:
form = AddEndpointForm(request.form)
if request.method == "POST":
c, conn = connection()
endpoint_name = form.endpoint_name.data
hostname = form.hostname.data
ip_addr = form.ip_addr.data
zip_code = form.zip_code.data
check_type = form.check_type.data
check_interval = form.check_interval.data
c_enabled = 1
cc_time = time.strftime("%H:%M:%S %m-%d-%Y")
x = c.execute("SELECT * FROM endpoints WHERE hostname = %s", (hostname,))
print(f"Hostname used is :'{hostname}'")
if int(x) > 0:
print(x)
flash(f"{endpoint_name.capitalize()} is already in the system.")
return render_template("add_endpoint.html", form=form)
else:
c.execute(
"INSERT INTO endpoints (endpoint_name, \
hostname, \
ip, \
zip, \
check_type, \
enabled, \
check_interval, \
last_check, \
next_check, \
enabled_date, \
creation_date) \
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",
(thwart(endpoint_name),
thwart(hostname),
thwart(ip_addr),
thwart(zip_code),
thwart(check_type),
c_enabled,
check_interval,
cc_time,
cc_time,
cc_time,
cc_time))
conn.commit()
flash(f"{endpoint_name.capitalize()} has been added!")
return redirect(url_for('monitor'))
return render_template("add_endpoint.html", form=form)
except Exception as e:
if netpop_logging_to_console:
app.logger.error(e)
return render_template("error.html", error=e)
@app.route('/multi_endpoint_import/')
@login_required
@admin_required
def multi_endpoint_import():
return render_template("multi_endpoint_import.html")
# My Profile/Account Settings
@app.route('/my_account/')
@login_required
def my_account():
try:
c, conn = connection()
data = c.execute("SELECT firstname, lastname, email, lastlogin, last_invalid_login, account_creation, user_timezone FROM users WHERE username LIKE %s", session['username'])
results = c.fetchone()
return render_template("my_account.html", user_results=results, c_user=session['username'])
except Exception as e:
return render_template("error.html", error=e)
# User Management Page (admin only)
@app.route('/user_management/')
@login_required
@admin_required
def user_management():
try:
c, conn = connection()
data = c.execute("SELECT * FROM users")
results = c.fetchall()
return render_template("user_management.html", results=results)
except Exception as e:
return render_template("error.html", error=e)
# Edit Accounts (admin only)
@app.route('/edit_account/')
@login_required
@admin_required
def edit_account():
return render_template("edit_account.html")
# Contact Pages Settings
@app.route('/contacts/')
@login_required
def contacts():
try:
return render_template("contacts.html")
except Exception as e:
return render_template("error.html", error=e)
@app.route('/contact_groups/')
@login_required
def contact_groups():
try:
return render_template("contact_groups.html")
except Exception as e:
return render_template("error.html", error=e)
# Endpoint Management Page (admin only)
@app.route('/endpoint/<endpoint_name>')
@login_required
@admin_required
def endpoint(endpoint_name):
try:
c, conn = connection()
c.execute("SELECT * FROM netpop.endpoints WHERE endpoint_name LIKE %s", endpoint_name)
results = c.fetchone()
c.close()
conn.close()
return render_template("endpoint.html", endpoint_info=results)
except Exception as e:
return render_template("error.html", error=e)
##### Playground ######
# jQuery Test Page
@app.route('/interactive/')
def interactive():
return render_template('interactive.html')
# Background Process for jQuery page
@app.route('/background_process')
def background_process():
try:
lang = request.args.get('proglang', 0, type=str)
if lang.lower() == 'python':
return jsonify(result=time.strftime("%H:%M %m-%d-%Y"))
else:
return jsonify(result='Try again.')
except Exception as e:
return str(e)
###### End of Playground ########
# Edit Endpoint Selection List
@app.route('/edit_endpoint/')
@login_required
@admin_required
def edit_endpoint():
try:
c, conn = connection()
c.execute("SELECT endpoint_name, endpoint_status FROM netpop.endpoints;")
results = c.fetchall()
c.close()
conn.close()
return render_template("edit_endpoint.html", ehost_l=results)
except Exception as e:
return render_template("error.html", error=e)
# Error Handling Pages
@app.route('/access_denied/')
def access_denied():
return render_template("access_denied.html")
@app.errorhandler(404)
def page_not_found(e):
return render_template("404.html")
@app.errorhandler(405)
def page_not_found(e):
return render_template("405.html")
@app.errorhandler(500)
def server_issue(e):
return render_template("500.html", error=e)
# Main App
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')