-
-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathgenserv.py
More file actions
6647 lines (6105 loc) · 249 KB
/
genserv.py
File metadata and controls
6647 lines (6105 loc) · 249 KB
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
# -------------------------------------------------------------------------------
# FILE: genserv.py
# PURPOSE: Flask app for generator monitor web app
#
# AUTHOR: Jason G Yates
# DATE: 20-Dec-2016
#
# MODIFICATIONS:
# -------------------------------------------------------------------------------
from __future__ import print_function
import collections
import errno
import hashlib
import json
import os
import os.path
import secrets
import signal
import subprocess
import sys
import threading
import time
import uuid
try:
from flask import (
Flask,
Response,
jsonify,
make_response,
redirect,
render_template,
request,
send_file,
send_from_directory,
session,
url_for,
)
except Exception as e1:
print(
"\n\nThis program requires the Flask library. Please see the project documentation at https://github.com/jgyates/genmon.\n"
)
print("Error: " + str(e1))
sys.exit(2)
try:
import pyotp
except Exception as e1:
print(
"\n\nThis program requires the pyotp library. Please see the project documentation at https://github.com/jgyates/genmon.\n"
)
print("Error: " + str(e1))
sys.exit(2)
try:
from genmonlib.myclient import ClientInterface
from genmonlib.myconfig import MyConfig
from genmonlib.mylog import SetupLogger
from genmonlib.mymail import MyMail
from genmonlib.mysupport import MySupport
from genmonlib.myplatform import MyPlatform
from genmonlib.program_defaults import ProgramDefaults
except Exception as e1:
print(
"\n\nThis program requires the modules located in the genmonlib directory in the original github repository.\n"
)
print(
"Please see the project documentation at https://github.com/jgyates/genmon.\n"
)
print("Error: " + str(e1))
sys.exit(2)
if sys.version_info[0] < 3:
from urlparse import parse_qs, parse_qsl, urlparse
else:
from urllib.parse import urlparse
from urllib.parse import parse_qs
from urllib.parse import parse_qsl
import datetime
import re
# -------------------------------------------------------------------------------
app = Flask(__name__, static_url_path="")
# this allows the flask support to be extended on a per site basis but sill allow for
# updates via the main github repository. If genservex.py exists, load it
if os.path.isfile(
os.path.join(os.path.dirname(os.path.realpath(__file__)), "genservext.py")
):
import genservext
app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 300
HTTPAuthUser = None
HTTPAuthPass = None
HTTPAuthUser_RO = None
HTTPAuthPass_RO = None
LdapServer = None
LdapBase = None
DomainNetbios = None
LdapAdminGroup = None
LdapReadOnlyGroup = None
mail = None
bUseMFA = False
bMfaEnrolled = False
SecretMFAKey = None
MFA_URL = None
RememberMeDays = 0
MfaTrustDays = 90
bMfaTrustExtend = False
LastOTPSendTime = None
bUseSecureHTTP = False
CertMode = "selfsigned" # selfsigned | localca | custom
SSLContext = None
HTTPPort = 8000
OldHTTPPort = None
loglocation = ProgramDefaults.LogPath
clientport = ProgramDefaults.ServerPort
log = None
console = None
debug = False
AppPath = ""
favicon = "favicon.ico"
ConfigFilePath = ProgramDefaults.ConfPath
MAIL_SECTION = "MyMail"
GENMON_SECTION = "GenMon"
RedirectServer = None
WebUILocked = False
LoginAttempts = 0
MaxLoginAttempts = 5
LockOutDuration = 5 * 60
LastLoginTime = datetime.datetime.now()
LastFailedLoginTime = datetime.datetime.now()
securityMessageSent = None
Closing = False
Restarting = False
ControllerType = "generac_evo_nexus"
CriticalLock = threading.Lock()
CachedToolTips = {}
CachedRegisterDescriptions = {}
# -------------------------------------------------------------------------------
def StartHTTPRedirectServer():
"""Start a lightweight HTTP server on OldHTTPPort that 301-redirects
every request to the HTTPS port. Runs in a daemon thread so it dies
with the main process."""
import http.server
import socketserver
redirect_port = OldHTTPPort
target_port = HTTPPort # already set to HTTPSPort at this point
class RedirectHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
host = self.headers.get("Host", "localhost").split(":")[0]
if target_port == 443:
location = "https://" + host + self.path
else:
location = "https://" + host + ":" + str(target_port) + self.path
# Serve an HTML page with JS redirect instead of a raw 302.
# Chrome aggressively caches 301/302 redirects for IP addresses,
# making it impossible to reach the HTTP site after HTTPS is disabled.
# An HTML page is not cached as a redirect by the browser.
self.send_response(200)
self.send_header("Content-Type", "text/html")
self.send_header("Cache-Control", "no-store")
self.end_headers()
page = (
"<!DOCTYPE html><html><head>"
'<meta http-equiv="refresh" content="1;url={loc}">'
"</head><body>"
'<p>Redirecting to <a href="{loc}">{loc}</a>…</p>'
"<script>location.replace('{loc}');</script>"
"</body></html>"
).format(loc=location)
self.wfile.write(page.encode("utf-8"))
do_POST = do_GET
do_PUT = do_GET
do_DELETE = do_GET
do_HEAD = do_GET
def log_message(self, format, *args):
pass # suppress request logs
global RedirectServer
try:
socketserver.TCPServer.allow_reuse_address = True
RedirectServer = socketserver.TCPServer(
(ListenIPAddress, redirect_port), RedirectHandler
)
LogDebug(
"HTTP->HTTPS redirect active on port "
+ str(redirect_port)
+ " -> "
+ str(target_port)
)
RedirectServer.serve_forever()
except Exception as e1:
LogErrorLine(
"Unable to start HTTP redirect server on port "
+ str(redirect_port)
+ ": "
+ str(e1)
)
# -------------------------------------------------------------------------------
def HasWriteAccess():
"""Return True if the current request has write access.
When authentication is disabled everyone gets full access.
When authentication is enabled the session must carry an explicit True."""
if not LoginActive():
return True
return session.get("write_access", False)
# -------------------------------------------------------------------------------
@app.before_request
def csrf_check():
"""Block cross-origin state-changing requests (CSRF protection).
Reverse-proxy aware: trusts X-Forwarded-Host so that the browser's
Origin (the public domain) matches even when Flask sees the backend
address as request.host.
"""
if request.method in ("GET", "HEAD", "OPTIONS"):
return # safe methods — SameSite cookie handles GET-based CSRF
# Login endpoints are protected by credentials, not session — exempt from CSRF
if request.endpoint in ("do_admin_login", "passkey_login_begin", "passkey_login_complete", "mfa_auth"):
return
origin = request.headers.get("Origin")
referer = request.headers.get("Referer")
if not origin and not referer:
LogError("CSRF blocked: missing Origin and Referer")
return jsonify({"error": "CSRF validation failed"}), 403
# Build the set of hosts we trust: the direct host Flask sees plus
# any X-Forwarded-Host a reverse proxy (Caddy, nginx, etc.) provides.
trusted_hosts = {request.host}
fwd_host = request.headers.get("X-Forwarded-Host")
if fwd_host:
# X-Forwarded-Host may be a comma-separated list; trust all entries
for h in fwd_host.split(","):
trusted_hosts.add(h.strip())
if origin:
parsed = urlparse(origin)
if parsed.netloc not in trusted_hosts:
LogError("CSRF blocked: Origin mismatch: " + origin
+ " (trusted: " + ", ".join(sorted(trusted_hosts)) + ")")
return jsonify({"error": "Cross-origin request blocked"}), 403
elif referer:
parsed = urlparse(referer)
if parsed.netloc not in trusted_hosts:
LogError("CSRF blocked: Referer mismatch: " + referer
+ " (trusted: " + ", ".join(sorted(trusted_hosts)) + ")")
return jsonify({"error": "Cross-origin request blocked"}), 403
# -------------------------------------------------------------------------------
@app.route("/logout")
def logout():
try:
# remove the session data
if LoginActive():
session["logged_in"] = False
session["write_access"] = False
session["mfa_ok"] = False
return redirect(url_for("root"))
except Exception as e1:
LogError("Error on logout: " + str(e1))
# -------------------------------------------------------------------------------
@app.after_request
def add_header(r):
"""
Force cache header and add security headers
"""
r.headers[
"Cache-Control"
] = "no-cache, no-store, must-revalidate, public, max-age=0"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
# --- security headers ---
r.headers["X-Content-Type-Options"] = "nosniff"
r.headers["X-Frame-Options"] = "DENY"
r.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
r.headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=()"
r.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline'; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data:; "
"connect-src 'self' https://raw.githubusercontent.com; "
"frame-ancestors 'none'"
)
# When HTTPS is off, tell browsers to stop forcing HTTPS (clears cached HSTS)
if not bUseSecureHTTP:
r.headers["Strict-Transport-Security"] = "max-age=0"
return r
# -------------------------------------------------------------------------------
@app.route("/", methods=["GET"])
def root():
if bUseMFA:
if not "mfa_ok" in session or not session["mfa_ok"] == True:
session["logged_in"] = False
session["write_access"] = False
session["mfa_ok"] = False
return ServePage("index.html")
# -------------------------------------------------------------------------------
@app.route("/locked", methods=["GET"])
def locked():
LogError("Locked Page")
return render_template("locked.html", theme=get_theme_pref())
# -------------------------------------------------------------------------------
@app.route("/upload", methods=["POST"])
def upload():
try:
if not HasWriteAccess():
return jsonify({"status": "error", "message": "Write access required."}), 403
if "file" not in request.files:
return jsonify({"status": "error", "message": "No file provided."}), 400
f = request.files["file"]
if f.filename == "":
return jsonify({"status": "error", "message": "No file selected."}), 400
if not f.filename.lower().endswith(".tar.gz"):
return jsonify({"status": "error", "message": "Invalid file type. Expected a .tar.gz archive."}), 400
# Read into memory and enforce size limit (10 MB)
data = f.read()
MAX_UPLOAD = 10 * 1024 * 1024
if len(data) > MAX_UPLOAD:
return jsonify({"status": "error", "message": "File too large. Maximum size is 10 MB."}), 400
import tarfile, io, tempfile
# Validate it's a real tar.gz archive
try:
buf = io.BytesIO(data)
with tarfile.open(fileobj=buf, mode="r:gz") as tf:
names = tf.getnames()
# Security: reject path traversal
for name in names:
if name.startswith("/") or ".." in name:
return jsonify({"status": "error", "message": "Archive contains unsafe paths."}), 400
# Sanity check: must contain genmon_backup/ with at least one .conf
has_conf = any(
n.startswith("genmon_backup/") and n.endswith(".conf") for n in names
)
if not has_conf:
return jsonify({"status": "error", "message": "Archive does not appear to be a valid genmon backup (no genmon_backup/*.conf found)."}), 400
except tarfile.TarError:
return jsonify({"status": "error", "message": "File is not a valid tar.gz archive."}), 400
# Save to temp file and run restore script
pathtofile = os.path.dirname(os.path.realpath(__file__))
upload_path = os.path.join(pathtofile, "genmon_restore_upload.tar.gz")
try:
with open(upload_path, "wb") as out:
out.write(data)
if not RestoreBackup(upload_path):
return jsonify({"status": "error", "message": "Restore script failed. Check server logs."}), 500
finally:
if os.path.exists(upload_path):
os.remove(upload_path)
threading.Thread(target=Restart, daemon=True).start()
return jsonify({"status": "ok", "message": "Configuration restored. Service is restarting\u2026"})
except Exception as e1:
LogErrorLine("Error in upload: " + str(e1))
return jsonify({"status": "error", "message": "Server error during upload."}), 500
# -------------------------------------------------------------------------------
@app.route("/download/ca.crt")
def download_ca_der():
"""Serve the Local CA certificate in DER format for browser import."""
try:
ca_path = os.path.join(ConfigFilePath, "ca.crt")
if not os.path.isfile(ca_path):
return "CA certificate not found", 404
from OpenSSL import crypto
with open(ca_path, "rb") as f:
ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
der = crypto.dump_certificate(crypto.FILETYPE_ASN1, ca_cert)
return Response(
der,
mimetype="application/x-x509-ca-cert",
headers={"Content-Disposition": "attachment; filename=genmon-ca.crt"},
)
except Exception as e1:
LogErrorLine("Error in download_ca_der: " + str(e1))
return "Error serving certificate", 500
# -------------------------------------------------------------------------------
@app.route("/import/ca.crt")
def import_ca_inline():
"""Serve the CA cert inline (no attachment header) so Firefox opens its
native import dialog and Chrome/Edge download it automatically."""
try:
ca_path = os.path.join(ConfigFilePath, "ca.crt")
if not os.path.isfile(ca_path):
return "CA certificate not found", 404
from OpenSSL import crypto
with open(ca_path, "rb") as f:
ca_cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
der = crypto.dump_certificate(crypto.FILETYPE_ASN1, ca_cert)
return Response(der, mimetype="application/x-x509-ca-cert")
except Exception as e1:
LogErrorLine("Error in import_ca_inline: " + str(e1))
return "Error serving certificate", 500
# -------------------------------------------------------------------------------
@app.route("/download/ca.pem")
def download_ca_pem():
"""Serve the Local CA certificate in PEM format."""
try:
ca_path = os.path.join(ConfigFilePath, "ca.crt")
if not os.path.isfile(ca_path):
return "CA certificate not found", 404
with open(ca_path, "rb") as f:
pem_data = f.read()
return Response(
pem_data,
mimetype="application/x-pem-file",
headers={"Content-Disposition": "attachment; filename=genmon-ca.pem"},
)
except Exception as e1:
LogErrorLine("Error in download_ca_pem: " + str(e1))
return "Error serving certificate", 500
# -------------------------------------------------------------------------------
def get_theme_pref():
try:
raw = ConfigFiles[GENMON_CONFIG].ReadValue(
"ui_prefs", return_type=str, section="GenMon", default="{}"
)
return json.loads(raw).get("theme", "dark")
except Exception:
return "dark"
# -------------------------------------------------------------------------------
def _render_login():
"""Render login page with theme and passkey availability."""
has_pk = bUseMFA and bUseSecureHTTP and bool(_load_passkeys())
return render_template("login.html", theme=get_theme_pref(), has_passkeys=has_pk, remember_me_enabled=RememberMeDays > 0)
# -------------------------------------------------------------------------------
def _get_mfa_trust_serializer():
from itsdangerous import URLSafeTimedSerializer
return URLSafeTimedSerializer(app.secret_key, salt="mfa-trust")
# -------------------------------------------------------------------------------
def _set_mfa_trust_cookie(response, username):
s = _get_mfa_trust_serializer()
token = s.dumps({"u": username})
response.set_cookie(
"mfa_trust", token,
max_age=MfaTrustDays * 86400,
httponly=True, secure=True, samesite="Lax",
)
return response
# -------------------------------------------------------------------------------
def _check_mfa_trust_cookie():
if not bMfaTrustExtend:
return None
token = request.cookies.get("mfa_trust")
if not token:
return None
try:
s = _get_mfa_trust_serializer()
data = s.loads(token, max_age=MfaTrustDays * 86400)
return data.get("u")
except Exception:
return None
# -------------------------------------------------------------------------------
def ServePage(page_file):
if LoginActive():
if not session.get("logged_in"):
return _render_login()
else:
return app.send_static_file(page_file)
else:
return app.send_static_file(page_file)
# -------------------------------------------------------------------------------
@app.route("/mfa", methods=["POST"])
def mfa_auth():
try:
if bUseMFA:
code = request.form.get("code", "")
verified = False
# Check if this is a backup code (8 hex chars) or TOTP (6 digits)
if len(code) == 8 and all(c in "0123456789abcdef" for c in code.lower()):
verified = _validate_backup_code(session.get("username", ""), code)
else:
verified = ValidateOTP(code)
if verified:
session["mfa_ok"] = True
resp = redirect(url_for("root"))
# Set MFA trust cookie if checkbox was checked and trust is enabled
if bMfaTrustExtend and request.form.get("trust_browser"):
username = session.get("username", "")
resp = _set_mfa_trust_cookie(resp, username)
return resp
else:
session["logged_in"] = False
session["write_access"] = False
session["mfa_ok"] = False
CheckFailedLogin() # count toward brute-force lockout
return redirect(url_for("logout"))
else:
return redirect(url_for("root"))
except Exception as e1:
LogErrorLine("Error in mfa_auth: " + str(e1))
return _render_login()
# -------------------------------------------------------------------------------
def admin_login_helper():
global LoginAttempts
LoginAttempts = 0
try:
# remember-me: make session persistent if checkbox was checked and days > 0
if request.form.get("remember_me") and RememberMeDays > 0:
session.permanent = True
if bUseMFA:
# Check MFA trust cookie before showing MFA screen
trust_user = _check_mfa_trust_cookie()
if trust_user and trust_user == session.get("username", ""):
session["mfa_ok"] = True
resp = redirect(url_for("root"))
resp = _set_mfa_trust_cookie(resp, trust_user)
return resp
# GetOTP()
email_ok = mail is not None and not getattr(mail, 'DisableEmail', True) and not getattr(mail, 'DisableSMTP', True)
uname = session.get("username", "").lower()
bc_data = _load_backup_codes()
has_bc = len(bc_data.get(uname, [])) > 0
response = make_response(render_template("mfa.html", theme=get_theme_pref(), trust_enabled=bMfaTrustExtend, trust_days=MfaTrustDays, email_available=email_ok, has_backup_codes=has_bc))
return response
else:
return redirect(url_for("root"))
except Exception as e1:
LogErrorLine("Error in admin_login_helper: " + str(e1))
return False
# -------------------------------------------------------------------------------
@app.route("/", methods=["POST"])
def do_admin_login():
CheckLockOutDuration()
if WebUILocked:
next_time = (datetime.datetime.now() - LastFailedLoginTime).total_seconds()
str_seconds = str(int(LockOutDuration - next_time))
response = make_response(render_template("locked.html", time=str_seconds, theme=get_theme_pref()))
response.headers["Content-type"] = "text/html; charset=utf-8"
response.mimetype = "text/html; charset=utf-8"
return response
submitted_user = request.form["username"].lower()
submitted_pass = request.form["password"]
# Timing-safe comparisons to prevent user/password enumeration
admin_user_ok = secrets.compare_digest(submitted_user, (HTTPAuthUser or "").lower())
admin_pass_ok = secrets.compare_digest(submitted_pass, HTTPAuthPass or "")
ro_user_ok = secrets.compare_digest(submitted_user, (HTTPAuthUser_RO or "").lower())
ro_pass_ok = secrets.compare_digest(submitted_pass, HTTPAuthPass_RO or "")
if admin_user_ok and admin_pass_ok:
session["logged_in"] = True
session["write_access"] = True
session["username"] = submitted_user
LogError("Admin Login")
return admin_login_helper()
elif ro_user_ok and ro_pass_ok:
session["logged_in"] = True
session["write_access"] = False
session["username"] = submitted_user
LogError("Limited Rights Login")
return admin_login_helper()
elif doLdapLogin(request.form["username"], request.form["password"]):
session["username"] = request.form["username"].lower()
return admin_login_helper()
elif request.form["username"] != "":
LogError("Invalid login: " + request.form["username"])
CheckFailedLogin()
return _render_login()
else:
return _render_login()
# -------------------------------------------------------------------------------
def CheckLockOutDuration():
global WebUILocked
global LoginAttempts
global securityMessageSent
if MaxLoginAttempts == 0:
return
if LoginAttempts >= MaxLoginAttempts:
if (
datetime.datetime.now() - LastFailedLoginTime
).total_seconds() > LockOutDuration:
WebUILocked = False
LoginAttempts = 0
else:
WebUILocked = True
# send message to user only once every 4 hours
if securityMessageSent == None or (
(datetime.datetime.now() - securityMessageSent).total_seconds()
> (4 * 60)
):
message = {
"title": "Security Warning",
"body": "Genmon login is locked due to exceeding the maximum login attempts.",
"type": "error",
"oncedaily": False,
"onlyonce": False,
}
command = "generator: notify_message=" + json.dumps(message)
data = MyClientInterface.ProcessMonitorCommand(command)
securityMessageSent = datetime.datetime.now()
# -------------------------------------------------------------------------------
def CheckFailedLogin():
global LoginAttempts
global WebUILocked
global LastFailedLoginTime
LoginAttempts += 1
LastFailedLoginTime = datetime.datetime.now()
CheckLockOutDuration()
# -------------------------------------------------------------------------------
def doLdapLogin(username, password):
if LdapServer == None or LdapServer == "":
return False
try:
from ldap3 import ALL, NTLM, Connection, Server
from ldap3.utils.dn import escape_rdn
from ldap3.utils.conv import escape_filter_chars
except ImportError as importException:
LogError(
"LDAP3 import not found, run 'sudo pip install ldap3 && sudo pip3 install ldap3'"
)
LogError(importException)
return False
HasAdmin = False
HasReadOnly = False
try:
SplitName = username.split("\\")
DomainName = SplitName[0]
DomainName = DomainName.strip()
AccountName = SplitName[1]
AccountName = AccountName.strip()
except IndexError:
LogError("Using domain name in config file")
DomainName = DomainNetbios
AccountName = username.strip()
try:
server = Server(LdapServer, get_info=ALL)
conn = Connection(
server,
user="{}\\{}".format(DomainName, AccountName),
password=password,
authentication=NTLM,
auto_bind=True,
)
loginbasestr = escape_filter_chars("(&(objectclass=user)(sAMAccountName=" + AccountName + "))")
conn.search(
LdapBase,
loginbasestr,
attributes=["memberOf"],
)
for user in sorted(conn.entries):
for group in user.memberOf:
if group.upper().find("CN=" + LdapAdminGroup.upper() + ",") >= 0:
HasAdmin = True
elif group.upper().find("CN=" + LdapReadOnlyGroup.upper() + ",") >= 0:
HasReadOnly = True
conn.unbind()
except Exception:
LogError("Error in LDAP login. Check credentials and config parameters")
session["logged_in"] = HasAdmin or HasReadOnly
session["write_access"] = HasAdmin
if HasAdmin:
LogError("Admin Login via LDAP")
elif HasReadOnly:
LogError("Limited Rights Login via LDAP")
else:
LogError("No rights for login via LDAP")
return HasAdmin or HasReadOnly
# -------------------------------------------------------------------------------
@app.route("/cmd/<command>")
def command(command):
if Closing or Restarting:
return jsonify("Closing")
if HTTPAuthUser == None or HTTPAuthPass == None:
# Not everything sent to this function is a json string
# so try to jsonify it and if that fails just return the
# original string
commandResponse = ProcessCommand(command)
try:
# Set Content-Type to application/json
return jsonify(json.loads(commandResponse))
except Exception as e1:
return commandResponse
if not session.get("logged_in"):
return _render_login()
else:
commandResponse = ProcessCommand(command)
try:
return jsonify(json.loads(commandResponse))
except Exception as e1:
return commandResponse
# -------------------------------------------------------------------------------
def ProcessCommand(command):
try:
command_list = [
"status",
"status_json",
"outage",
"outage_json",
"maint",
"maint_json",
"logs",
"logs_json",
"monitor",
"monitor_json",
"registers_json",
"allregs_json",
"start_info_json",
"gui_status_json",
"power_log_json",
"power_log_clear",
"getbase",
"getsitename",
"setexercise",
"setquiet",
"setremote",
"settime",
"sendregisters",
"sendlogfiles",
"getdebug",
"status_num_json",
"maint_num_json",
"monitor_num_json",
"outage_num_json",
"get_maint_log_json",
"add_maint_log",
"clear_maint_log",
"delete_row_maint_log",
"edit_row_maint_log",
"support_data_json",
"fuel_log_clear",
"notify_message",
"set_button_command",
]
# LogError(request.url)
if command in command_list:
finalcommand = "generator: " + command
try:
if command in [
"setexercise",
"setquiet",
"setremote",
"add_maint_log",
"delete_row_maint_log",
"edit_row_maint_log",
] and not HasWriteAccess():
return jsonify("Read Only Mode")
if command == "setexercise":
settimestr = request.args.get("setexercise", 0, type=str)
if settimestr:
finalcommand += "=" + settimestr
elif command == "setquiet":
# /cmd/setquiet?setquiet=off
setquietstr = request.args.get("setquiet", 0, type=str)
if setquietstr:
finalcommand += "=" + setquietstr
elif command == "setremote":
setremotestr = request.args.get("setremote", 0, type=str)
if setremotestr:
finalcommand += "=" + setremotestr
if command == "power_log_json":
# example: /cmd/power_log_json?power_log_json=1440
setlogstr = request.args.get("power_log_json", 0, type=str)
if setlogstr:
finalcommand += "=" + setlogstr
# Sanitize command parameters: strip null bytes and newlines
# to prevent header/log injection, cap length to limit abuse.
if command == "add_maint_log":
# use direct method instead of request.args.get due to unicode
# input for add_maint_log for international users
input = request.args["add_maint_log"]
input = input.replace("\x00", "").replace("\n", " ").replace("\r", " ")[:2048]
finalcommand += "=" + input
if command == "delete_row_maint_log":
input = request.args["delete_row_maint_log"]
input = input.replace("\x00", "").replace("\n", " ").replace("\r", " ")[:512]
finalcommand += "=" + input
if command == "edit_row_maint_log":
input = request.args["edit_row_maint_log"]
input = input.replace("\x00", "").replace("\n", " ").replace("\r", " ")[:2048]
finalcommand += "=" + input
if command == "set_button_command":
input = request.args["set_button_command"]
input = input.replace("\x00", "").replace("\n", " ").replace("\r", " ")[:512]
finalcommand += "=" + input
data = MyClientInterface.ProcessMonitorCommand(finalcommand)
except Exception as e1:
data = "Retry"
LogErrorLine("Error on command function: " + str(e1))
if command in [
"status_json",
"outage_json",
"maint_json",
"monitor_json",
"logs_json",
"registers_json",
"allregs_json",
"start_info_json",
"gui_status_json",
"power_log_json",
"status_num_json",
"maint_num_json",
"monitor_num_json",
"outage_num_json",
"get_maint_log_json",
"support_data_json",
]:
if command in ["start_info_json"]:
try:
StartInfo = json.loads(data)
StartInfo["write_access"] = HasWriteAccess()
if not StartInfo["write_access"]:
StartInfo["pages"]["settings"] = False
StartInfo["pages"]["notifications"] = False
StartInfo["LoginActive"] = LoginActive()
data = json.dumps(StartInfo, sort_keys=False)
except Exception as e1:
LogErrorLine("Error in JSON parse / decode: " + str(e1))
return data
return jsonify(data)
elif command in ["updatesoftware"]:
if HasWriteAccess():
Update()
return "OK"
else:
return "Access denied"
elif command in ["getfavicon"]:
return jsonify(favicon)
elif command in ["settings"]:
if HasWriteAccess():
data = ReadSettingsFromFile()
return json.dumps(data, sort_keys=False)
else:
return "Access denied"
elif command in ["notifications"]:
data = ReadNotificationsFromFile()
return jsonify(data)
elif command in ["setnotifications"]:
if HasWriteAccess():
SaveNotifications(request.args.get("setnotifications", 0, type=str))
return "OK"
# Add on items
elif command in ["get_add_on_settings", "set_add_on_settings"]:
if HasWriteAccess():
if command == "get_add_on_settings":
data = GetAddOnSettings()
return json.dumps(data, sort_keys=False)
elif command == "set_add_on_settings":
SaveAddOnSettings(
request.args.get("set_add_on_settings", default=None, type=str)
)
else:
return "OK"
return "OK"
elif command in ["get_advanced_settings", "set_advanced_settings"]:
if HasWriteAccess():
if command == "get_advanced_settings":
data = ReadAdvancedSettingsFromFile()
return json.dumps(data, sort_keys=False)
elif command == "set_advanced_settings":
SaveAdvancedSettings(
request.args.get(
"set_advanced_settings", default=None, type=str
)
)
else:
return "OK"
return "OK"
elif command in ["setsettings"]:
if HasWriteAccess():
SaveSettings(request.args.get("setsettings", 0, type=str))
return "OK"
# ---- UI preferences (persisted to genmon.conf, no restart) ----
elif command in ["get_ui_prefs", "set_ui_prefs"]:
if command == "get_ui_prefs":
try:
return ConfigFiles[GENMON_CONFIG].ReadValue(
"ui_prefs", return_type=str, section="GenMon", default="{}"
)
except Exception:
return "{}"
elif command == "set_ui_prefs":
if HasWriteAccess():
raw = request.args.get("set_ui_prefs", "{}", type=str)
if len(raw) > 16384: # 16 KB cap to prevent memory/storage abuse
return "Error: payload too large"
try:
json.loads(raw) # validate JSON
except Exception:
return "Error: invalid JSON"
ConfigFiles[GENMON_CONFIG].WriteValue(
"ui_prefs", raw, section="GenMon"
)
return "OK"
elif command in ["getreglabels"]:
return jsonify(CachedRegisterDescriptions)
elif command in ["restart"]: