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
from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging
import json
from django.shortcuts import HttpResponse, render
import re
from django.shortcuts import HttpResponse, render
from loginSystem.models import Administrator
class secMiddleware:
@@ -23,7 +22,7 @@ class secMiddleware:
try:
uID = request.session['userID']
admin = Administrator.objects.get(pk=uID)
ipAddr = get_client_ip(request)
ipAddr = self.get_client_ip(request)
if ipAddr.find('.') > -1:
if request.session['ipAddr'] == ipAddr or admin.securityLevel == secMiddleware.LOW:
@@ -31,19 +30,17 @@ class secMiddleware:
else:
del request.session['userID']
del request.session['ipAddr']
logging.writeToFile(get_client_ip(request))
final_dic = {'error_message': "Session reuse detected, IPAddress logged.",
"errorMessage": "Session reuse detected, IPAddress logged."}
final_json = json.dumps(final_dic)
return HttpResponse(final_json)
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:
pass
else:
del request.session['userID']
del request.session['ipAddr']
logging.writeToFile(get_client_ip(request))
final_dic = {'error_message': "Session reuse detected, IPAddress logged.",
"errorMessage": "Session reuse detected, IPAddress logged."}
final_json = json.dumps(final_dic)
@@ -53,7 +50,6 @@ class secMiddleware:
if request.method == 'POST':
try:
#logging.writeToFile(request.body)
data = json.loads(request.body)
for key, value in data.items():
if request.path.find('gitNotify') > -1:
@@ -62,17 +58,10 @@ class secMiddleware:
pass
elif type(value) == list:
for items in value:
if items.find('- -') > -1 or items.find('\n') > -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 or items.find("<") > -1 or items.find(">") > -1:
logging.writeToFile(request.body)
if any(char in items for char in ['$','&','(',')','[',']','{','}',';','','<','>']):
final_dic = {
'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 ` $ & ( ) [ ] { } ; : < >."}
'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 `$ & ( ) [ ] { } ; : < >."}
final_json = json.dumps(final_dic)
return HttpResponse(final_json)
else:
@@ -80,7 +69,6 @@ class secMiddleware:
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':
logging.writeToFile(request.body)
final_dic = {'error_message': "Data supplied is not accepted.",
"errorMessage": "Data supplied is not accepted."}
final_json = json.dumps(final_dic)
@@ -88,7 +76,7 @@ class secMiddleware:
if 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(
'saveSpamAssassinConfigurations') > -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(
"{") > -1 or value.find("}") > -1 \
or value.find(":") > -1 or value.find("<") > -1 or value.find(">") > -1:
logging.writeToFile(request.body)
final_dic = {
'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 ` $ & ( ) [ ] { } ; : < >."}
'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 `$ & ( ) [ ] { } ; : < >."}
final_json = json.dumps(final_dic)
return HttpResponse(final_json)
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(
"{") > -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.",
"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)
return HttpResponse(final_json)
@@ -129,14 +115,6 @@ class secMiddleware:
logging.writeToFile(str(msg))
response = self.get_response(request)
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)

View File

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