secMiddleware.py

secMiddleware.py This needs testing, if this change will mess up anything else.
@usmannasir Can you try this?
This commit is contained in:
Master3395
2024-01-04 22:32:13 +01:00
parent 382ec6e8a6
commit 658807611f
2 changed files with 77 additions and 99 deletions

View File

@@ -1,8 +1,7 @@
# coding=utf-8 # coding=utf-8
from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging
import json import json
from django.shortcuts import HttpResponse, render
import re import re
from django.shortcuts import HttpResponse, render
from loginSystem.models import Administrator from loginSystem.models import Administrator
class secMiddleware: class secMiddleware:
@@ -23,7 +22,7 @@ class secMiddleware:
try: try:
uID = request.session['userID'] uID = request.session['userID']
admin = Administrator.objects.get(pk=uID) admin = Administrator.objects.get(pk=uID)
ipAddr = get_client_ip(request) ipAddr = self.get_client_ip(request)
if ipAddr.find('.') > -1: if ipAddr.find('.') > -1:
if request.session['ipAddr'] == ipAddr or admin.securityLevel == secMiddleware.LOW: if request.session['ipAddr'] == ipAddr or admin.securityLevel == secMiddleware.LOW:
@@ -31,19 +30,17 @@ class secMiddleware:
else: else:
del request.session['userID'] del request.session['userID']
del request.session['ipAddr'] del request.session['ipAddr']
logging.writeToFile(get_client_ip(request))
final_dic = {'error_message': "Session reuse detected, IPAddress logged.", final_dic = {'error_message': "Session reuse detected, IPAddress logged.",
"errorMessage": "Session reuse detected, IPAddress logged."} "errorMessage": "Session reuse detected, IPAddress logged."}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
return HttpResponse(final_json) return HttpResponse(final_json)
else: else:
ipAddr = get_client_ip(request).split(':')[:3] ipAddr = self.get_client_ip(request).split(':')[:3]
if request.session['ipAddr'] == ipAddr or admin.securityLevel == secMiddleware.LOW: if request.session['ipAddr'] == ipAddr or admin.securityLevel == secMiddleware.LOW:
pass pass
else: else:
del request.session['userID'] del request.session['userID']
del request.session['ipAddr'] del request.session['ipAddr']
logging.writeToFile(get_client_ip(request))
final_dic = {'error_message': "Session reuse detected, IPAddress logged.", final_dic = {'error_message': "Session reuse detected, IPAddress logged.",
"errorMessage": "Session reuse detected, IPAddress logged."} "errorMessage": "Session reuse detected, IPAddress logged."}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
@@ -53,7 +50,6 @@ class secMiddleware:
if request.method == 'POST': if request.method == 'POST':
try: try:
#logging.writeToFile(request.body)
data = json.loads(request.body) data = json.loads(request.body)
for key, value in data.items(): for key, value in data.items():
if request.path.find('gitNotify') > -1: if request.path.find('gitNotify') > -1:
@@ -62,17 +58,10 @@ class secMiddleware:
pass pass
elif type(value) == list: elif type(value) == list:
for items in value: for items in value:
if items.find('- -') > -1 or items.find('\n') > -1 or items.find(';') > -1 or items.find( if any(char in items for char in ['$','&','(',')','[',']','{','}',';','','<','>']):
'&&') > -1 or items.find('|') > -1 or items.find('...') > -1 \
or items.find("`") > -1 or items.find("$") > -1 or items.find(
"(") > -1 or items.find(")") > -1 \
or items.find("'") > -1 or items.find("[") > -1 or items.find(
"]") > -1 or items.find("{") > -1 or items.find("}") > -1 \
or items.find(":") > -1 or items.find("<") > -1 or items.find(">") > -1:
logging.writeToFile(request.body)
final_dic = { final_dic = {
'error_message': "Data supplied is not accepted, following characters are not allowed in the input ` $ & ( ) [ ] { } ; : < >.", 'error_message': "Data supplied is not accepted, following characters are not allowed in the input `$ & ( ) [ ] { } ; : < >.",
"errorMessage": "Data supplied is not accepted, following characters are not allowed in the input ` $ & ( ) [ ] { } ; : < >."} "errorMessage": "Data supplied is not accepted, following characters are not allowed in the input `$ & ( ) [ ] { } ; : < >."}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
return HttpResponse(final_json) return HttpResponse(final_json)
else: else:
@@ -80,7 +69,6 @@ class secMiddleware:
if key == 'backupDestinations': if key == 'backupDestinations':
if re.match('^[a-z|0-9]+:[a-z|0-9|\.]+\/?[A-Z|a-z|0-9|\.]*$', value) == None and value != 'local': if re.match('^[a-z|0-9]+:[a-z|0-9|\.]+\/?[A-Z|a-z|0-9|\.]*$', value) == None and value != 'local':
logging.writeToFile(request.body)
final_dic = {'error_message': "Data supplied is not accepted.", final_dic = {'error_message': "Data supplied is not accepted.",
"errorMessage": "Data supplied is not accepted."} "errorMessage": "Data supplied is not accepted."}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
@@ -88,7 +76,7 @@ class secMiddleware:
if request.build_absolute_uri().find( if request.build_absolute_uri().find(
'api/remoteTransfer') > -1 or request.build_absolute_uri().find( 'api/remoteTransfer') > -1 or request.build_absolute_uri().find(
'api/verifyConn') > -1 or request.build_absolute_uri().find( 'api/verifyConn') >-1 or request.build_absolute_uri().find(
'webhook') > -1 or request.build_absolute_uri().find( 'webhook') > -1 or request.build_absolute_uri().find(
'saveSpamAssassinConfigurations') > -1 or request.build_absolute_uri().find( 'saveSpamAssassinConfigurations') > -1 or request.build_absolute_uri().find(
'docker') > -1 or request.build_absolute_uri().find( 'docker') > -1 or request.build_absolute_uri().find(
@@ -108,10 +96,9 @@ class secMiddleware:
or value.find("'") > -1 or value.find("[") > -1 or value.find("]") > -1 or value.find( or value.find("'") > -1 or value.find("[") > -1 or value.find("]") > -1 or value.find(
"{") > -1 or value.find("}") > -1 \ "{") > -1 or value.find("}") > -1 \
or value.find(":") > -1 or value.find("<") > -1 or value.find(">") > -1: or value.find(":") > -1 or value.find("<") > -1 or value.find(">") > -1:
logging.writeToFile(request.body)
final_dic = { final_dic = {
'error_message': "Data supplied is not accepted, following characters are not allowed in the input ` $ & ( ) [ ] { } ; : < >.", 'error_message': "Data supplied is not accepted, following characters are not allowed in the input `$ & ( ) [ ] { } ; : < >.",
"errorMessage": "Data supplied is not accepted, following characters are not allowed in the input ` $ & ( ) [ ] { } ; : < >."} "errorMessage": "Data supplied is not accepted, following characters are not allowed in the input `$ & ( ) [ ] { } ; : < >."}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
return HttpResponse(final_json) return HttpResponse(final_json)
if key.find(';') > -1 or key.find('&&') > -1 or key.find('|') > -1 or key.find('...') > -1 \ if key.find(';') > -1 or key.find('&&') > -1 or key.find('|') > -1 or key.find('...') > -1 \
@@ -119,9 +106,8 @@ class secMiddleware:
or key.find("'") > -1 or key.find("[") > -1 or key.find("]") > -1 or key.find( or key.find("'") > -1 or key.find("[") > -1 or key.find("]") > -1 or key.find(
"{") > -1 or key.find("}") > -1 \ "{") > -1 or key.find("}") > -1 \
or key.find(":") > -1 or key.find("<") > -1 or key.find(">") > -1: or key.find(":") > -1 or key.find("<") > -1 or key.find(">") > -1:
logging.writeToFile(request.body)
final_dic = {'error_message': "Data supplied is not accepted.", final_dic = {'error_message': "Data supplied is not accepted.",
"errorMessage": "Data supplied is not accepted following characters are not allowed in the input ` $ & ( ) [ ] { } ; : < >."} "errorMessage": "Data supplied is not accepted following characters are not allowed in the input `$ & ( ) [ ] { } ; : < >."}
final_json = json.dumps(final_dic) final_json = json.dumps(final_dic)
return HttpResponse(final_json) return HttpResponse(final_json)
@@ -129,14 +115,6 @@ class secMiddleware:
logging.writeToFile(str(msg)) logging.writeToFile(str(msg))
response = self.get_response(request) response = self.get_response(request)
return response return response
# else:
# try:
# if request.path.find('cloudAPI/') > -1 or request.path.find('api/') > -1:
# pass
# else:
# uID = request.session['userID']
# except:
# return render(request, 'loginSystem/login.html', {})
response = self.get_response(request) response = self.get_response(request)

View File

@@ -1,6 +1,6 @@
{% extends "baseTemplate/index.html" %} {% extends "baseTemplate/index.html" %}
{% load i18n %} {% load i18n %}
{% block title %}{% trans "Version Management - CyberPanel" %}"{% endblock %} {% block title %}{% trans "Version Management - CyberPanel" %}{% endblock %}
{% block content %} {% block content %}
@@ -131,80 +131,80 @@
getBranches('https://api.github.com/repos/usmannasir/cyberpanel/branches', [], 1); getBranches('https://api.github.com/repos/usmannasir/cyberpanel/branches', [], 1);
function upgradeCyberPanel() { function upgradeCyberPanel() {
try { try {
var selectedBranch = document.getElementById("branchSelect").value; var selectedBranch = document.getElementById("branchSelect").value;
// Use the shell script URL based on the selected branch // Use the shell script URL based on the selected branch
var shellScriptUrl = `https://raw.githubusercontent.com/usmannasir/cyberpanel/${selectedBranch}/cyberpanel_upgrade.sh`; var shellScriptUrl = `https://raw.githubusercontent.com/usmannasir/cyberpanel/${selectedBranch}/cyberpanel_upgrade.sh`;
if (confirm("Are you sure you want to upgrade to the selected branch from the remote script?")) { if (confirm("Are you sure you want to upgrade to the selected branch from the remote script?")) {
// Use fetch to trigger a server-side action (execute shell script) // Use fetch to trigger a server-side action (execute shell script)
fetch('/upgrade', { fetch('/upgrade', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}, },
body: JSON.stringify({ body: JSON.stringify({
scriptUrl: shellScriptUrl, scriptUrl: shellScriptUrl,
}), }),
})
.then(response => {
if (!response.ok) {
throw new Error(`Failed to start upgrade. HTTP status ${response.status}`);
}
return response.json();
}) })
.then(response => { .then(data => {
if (!response.ok) { // Log the response from the server
throw new Error(`Failed to start upgrade. HTTP status ${response.status}`); console.log('Upgrade response:', data);
}
return response.json();
})
.then(data => {
// Log the response from the server
console.log('Upgrade response:', data);
// Check if the progress value is a finite number before setting it on the progress bar // Check if the progress value is defined and a finite number before setting it on the progress bar
if (isFinite(data.progress)) { if (typeof data.progress !== 'undefined' && isFinite(data.progress)) {
var upgradeProgressLog = document.getElementById("upgradeProgressLog"); var upgradeProgressLog = document.getElementById("upgradeProgressLog");
upgradeProgressLog.innerText = 'Upgrade Progress: ' + data.progress + '%'; upgradeProgressLog.innerText = 'Upgrade Progress: ' + data.progress + '%';
// You may also update other UI elements based on the response data // You may also update other UI elements based on the response data
} else { } else {
console.error('Invalid progress value received from the server:', data.progress); console.error('Invalid progress value received from the server:', data.progress);
var upgradeProgressLog = document.getElementById("upgradeProgressLog"); var upgradeProgressLog = document.getElementById("upgradeProgressLog");
upgradeProgressLog.innerText = 'Upgrade failed. Invalid progress value received from the server.'; upgradeProgressLog.innerText = 'Upgrade failed. Invalid progress value received from the server.';
} }
}) })
.catch(error => { .catch(error => {
console.error('Upgrade failed. Error starting upgrade:', error); console.error('Upgrade failed. Error starting upgrade:', error);
alert('Upgrade failed. Error starting upgrade. Check the console for details.'); alert('Upgrade failed. Error starting upgrade. Check the console for details.');
}); });
// Download and execute the upgrade script using wget // Download and execute the upgrade script using wget
fetch(shellScriptUrl) fetch(shellScriptUrl)
.then(response => response.text()) .then(response => response.text())
.then(scriptContent => { .then(scriptContent => {
// Create a Blob from the script content // Create a Blob from the script content
var blob = new Blob([scriptContent], { type: 'text/plain' }); var blob = new Blob([scriptContent], { type: 'text/plain' });
// Create a temporary URL for the Blob // Create a temporary URL for the Blob
var scriptUrl = URL.createObjectURL(blob); var scriptUrl = URL.createObjectURL(blob);
// Create an invisible iframe to trigger the download // Create an invisible iframe to trigger the download
var iframe = document.createElement('iframe'); var iframe = document.createElement('iframe');
iframe.style.display = 'none'; iframe.style.display = 'none';
iframe.src = scriptUrl; iframe.src = scriptUrl;
document.body.appendChild(iframe); document.body.appendChild(iframe);
}) })
.catch(error => { .catch(error => {
console.error('Failed to download upgrade script:', error); console.error('Failed to download upgrade script:', error);
alert('Failed to download upgrade script. Check the console for details.'); alert('Failed to download upgrade script. Check the console for details.');
}); });
}
} catch (error) {
console.error('An unexpected error occurred:', error);
// Additional error handling
alert('An unexpected error occurred during the upgrade. Check the console for details.');
// Log detailed error information
console.error('Detailed error information:', error);
} }
} catch (error) {
console.error('An unexpected error occurred:', error);
// Additional error handling
alert('An unexpected error occurred during the upgrade. Check the console for details.');
// Log detailed error information
console.error('Detailed error information:', error);
} }
}
function refreshPage() { function refreshPage() {
location.reload(); location.reload();
@@ -212,4 +212,4 @@
</script> </script>
{% endblock %} {% endblock %}