diff --git a/cli/cyberPanel.py b/cli/cyberPanel.py index 69ff0bdb0..ed876eb23 100755 --- a/cli/cyberPanel.py +++ b/cli/cyberPanel.py @@ -71,9 +71,7 @@ class cyberPanel: def deleteWebsite(self, domainName): try: - - numberOfWebsites = Websites.objects.count() + ChildDomains.objects.count() - vhost.deleteVirtualHostConfigurations(domainName, numberOfWebsites) + vhost.deleteVirtualHostConfigurations(domainName) self.printStatus(1, 'None') except BaseException, msg: diff --git a/firewall/views.py b/firewall/views.py index 12b7c73d4..e2f9056d2 100644 --- a/firewall/views.py +++ b/firewall/views.py @@ -4,1352 +4,229 @@ import json import shlex import subprocess from loginSystem.views import loadLoginPage -from plogical.firewallUtilities import FirewallUtilities -from .models import FirewallRules -import os -from loginSystem.models import Administrator -import plogical.CyberCPLogFileWriter as logging from plogical.virtualHostUtilities import virtualHostUtilities -import thread -from plogical.modSec import modSec -from plogical.installUtilities import installUtilities -from random import randint from plogical.csf import CSF import time from plogical.acl import ACLManager +from plogical.firewallManager import FirewallManager # Create your views here. def securityHome(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - - return render(request,'firewall/index.html') + fm = FirewallManager() + return fm.securityHome(request, userID) except KeyError: return redirect(loadLoginPage) def firewallHome(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request,'firewall/firewall.html') + fm = FirewallManager() + return fm.firewallHome(request, userID) except KeyError: return redirect(loadLoginPage) def getCurrentRules(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('fetchStatus', 0) - - - try: - if request.method == 'POST': - - rules = FirewallRules.objects.all() - - json_data = "[" - checker = 0 - - for items in rules: - dic = {'id': items.id, - 'name': items.name, - 'proto': items.proto, - 'port': items.port, - 'ipAddress':items.ipAddress, - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - - json_data = json_data + ']' - final_json = json.dumps({'fetchStatus': 1, 'error_message': "None","data":json_data}) - return HttpResponse(final_json) - - except BaseException,msg: - final_dic = {'fetchStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - - return HttpResponse(final_json) + fm = FirewallManager() + return fm.getCurrentRules(userID) except KeyError: - final_dic = {'fetchStatus': 0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + return redirect(loadLoginPage) def addRule(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('add_status', 0) - - try: - if request.method == 'POST': - - data = json.loads(request.body) - ruleName = data['ruleName'] - ruleProtocol = data['ruleProtocol'] - rulePort = data['rulePort'] - ruleIP = data['ruleIP'] - - FirewallUtilities.addRule(ruleProtocol,rulePort,ruleIP) - - newFWRule = FirewallRules(name=ruleName,proto=ruleProtocol,port=rulePort,ipAddress=ruleIP) - newFWRule.save() - - final_dic = {'add_status': 1, 'error_message': "None"} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - - - except BaseException,msg: - final_dic = {'add_status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except KeyError,msg: - final_dic = {'add_status': 0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.addRule(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def deleteRule(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('delete_status', 0) - try: - if request.method == 'POST': - - data = json.loads(request.body) - ruleID = data['id'] - ruleProtocol = data['proto'] - rulePort = data['port'] - ruleIP = data['ruleIP'] - - FirewallUtilities.deleteRule(ruleProtocol, rulePort,ruleIP) - - delRule = FirewallRules.objects.get(id=ruleID) - delRule.delete() - - final_dic = {'delete_status': 1, 'error_message': "None"} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException,msg: - final_dic = {'delete_status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except KeyError,msg: - final_dic = {'delete_status': 0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.deleteRule(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def reloadFirewall(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('reload_status', 0) - - try: - if request.method == 'POST': - - command = 'sudo firewall-cmd --reload' - cmd = shlex.split(command) - res = subprocess.call(cmd) - - if res == 0: - final_dic = {'reload_status': 1, 'error_message': "None"} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - final_dic = {'reload_status': 0, 'error_message': "Can not reload firewall, see CyberCP main log file."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException,msg: - final_dic = {'reload_status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except KeyError,msg: - final_dic = {'reload_status': 0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.reloadFirewall(userID) + except KeyError: + return redirect(loadLoginPage) def startFirewall(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('start_status', 0) - try: - if request.method == 'POST': - - command = 'sudo systemctl start firewalld' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - if res == 0: - final_dic = {'start_status': 1, 'error_message': "None"} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - final_dic = {'start_status': 0, 'error_message': "Can not start firewall, see CyberCP main log file."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException,msg: - final_dic = {'start_status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except KeyError,msg: - final_dic = {'reload_status': 0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.startFirewall(userID) + except KeyError: + return redirect(loadLoginPage) def stopFirewall(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('stop_status', 0) - try: - if request.method == 'POST': - - command = 'sudo systemctl stop firewalld' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - if res == 0: - final_dic = {'stop_status': 1, 'error_message': "None"} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - final_dic = {'stop_status': 0, 'error_message': "Can not stop firewall, see CyberCP main log file."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException,msg: - final_dic = {'stop_status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except KeyError,msg: - final_dic = {'stop_status': 0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.stopFirewall(userID) + except KeyError: + return redirect(loadLoginPage) def firewallStatus(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson() - try: - if request.method == 'POST': - - status = subprocess.check_output(["systemctl", "status","firewalld"]) - - if status.find("active") >-1: - final_dic = {'status': 1, 'error_message': "none",'firewallStatus':1} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - final_dic = {'status': 1, 'error_message': "none", 'firewallStatus': 0} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException,msg: - final_dic = {'status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except KeyError,msg: - final_dic = {'v': 0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.firewallStatus(userID) + except KeyError: + return redirect(loadLoginPage) def secureSSH(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - return render(request,'firewall/secureSSH.html') + fm = FirewallManager() + return fm.secureSSH(request, userID) except KeyError: return redirect(loadLoginPage) def getSSHConfigs(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson() - - try: - if request.method == 'POST': - data = json.loads(request.body) - type = data['type'] - - if type=="1": - - ## temporarily changing permission for sshd files - - command = 'sudo chown -R cyberpanel:cyberpanel /etc/ssh/sshd_config' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - - pathToSSH = "/etc/ssh/sshd_config" - - data = open(pathToSSH, 'r').readlines() - - permitRootLogin = 0 - sshPort = "22" - - for items in data: - if items.find("PermitRootLogin") > -1: - if items.find("Yes") > -1 or items.find("yes")>-1: - permitRootLogin = 1 - continue - if items.find("Port") > -1 and not items.find("GatewayPorts") > -1: - sshPort = items.split(" ")[1].strip("\n") - - ## changing permission back - - command = 'sudo chown -R root:root /etc/ssh/sshd_config' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - final_dic = {'permitRootLogin': permitRootLogin, 'sshPort': sshPort} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - - ## temporarily changing permission for sshd files - - command = 'sudo chown -R cyberpanel:cyberpanel /root' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - pathToKeyFile = "/root/.ssh/authorized_keys" - - json_data = "[" - checker = 0 - - data = open(pathToKeyFile, 'r').readlines() - - for items in data: - if items.find("ssh-rsa") > -1: - keydata = items.split(" ") - - key = "ssh-rsa " +keydata[1][:50] + " ... " + keydata[2] - - try: - userName = keydata[2][:keydata[2].index("@")] - except: - userName = keydata[2] - - dic = {'userName': userName, - 'key': key, - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - - ## changing permission back - - command = 'sudo chown -R root:root /root' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - except BaseException,msg: - final_dic = {'status': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except KeyError,msg: - final_dic = {'status': 0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.getSSHConfigs(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def saveSSHConfigs(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('saveStatus', 0) - try: - if request.method == 'POST': - data = json.loads(request.body) - type = data['type'] - - if type=="1": - - sshPort = data['sshPort'] - rootLogin = data['rootLogin'] - - command = 'sudo semanage port -a -t ssh_port_t -p tcp ' +sshPort - cmd = shlex.split(command) - res = subprocess.call(cmd) - - - FirewallUtilities.addRule('tcp',sshPort,"0.0.0.0/0") - - try: - updateFW = FirewallRules.objects.get(name="SSHCustom") - FirewallUtilities.deleteRule("tcp",updateFW.port) - updateFW.port = sshPort - updateFW.save() - except: - try: - newFireWallRule = FirewallRules(name="SSHCustom",port=sshPort,proto="tcp") - newFireWallRule.save() - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - - - ## temporarily changing permission for sshd files - - command = 'sudo chown -R cyberpanel:cyberpanel /etc/ssh/sshd_config' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - ## - - - if rootLogin == True: - rootLogin = "PermitRootLogin yes\n" - else: - rootLogin = "PermitRootLogin no\n" - - sshPort = "Port "+sshPort+"\n" - - - pathToSSH = "/etc/ssh/sshd_config" - - data = open(pathToSSH, 'r').readlines() - - writeToFile = open(pathToSSH,"w") - - - for items in data: - if items.find("PermitRootLogin") > -1: - if items.find("Yes") > -1 or items.find("yes"): - writeToFile.writelines(rootLogin) - continue - elif items.find("Port") > -1: - writeToFile.writelines(sshPort) - else: - writeToFile.writelines(items) - writeToFile.close() - - command = 'sudo systemctl restart sshd' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - ## changin back permissions - - command = 'sudo chown -R root:root /etc/ssh/sshd_config' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - ## - - - final_dic = {'saveStatus': 1} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException,msg: - final_dic = {'saveStatus': 0,'error_message':str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except KeyError,msg: - final_dic = {'saveStatus': 0,'error_message':str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.saveSSHConfigs(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def deleteSSHKey(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('delete_status', 0) - try: - if request.method == 'POST': - data = json.loads(request.body) - key = data['key'] - - # temp change of permissions - - command = 'sudo chown -R cyberpanel:cyberpanel /root' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - ## - - keyPart = key.split(" ")[1] - - pathToSSH = "/root/.ssh/authorized_keys" - - data = open(pathToSSH, 'r').readlines() - - writeToFile = open(pathToSSH,"w") - - for items in data: - if items.find("ssh-rsa") > -1 and items.find(keyPart)>-1: - continue - else: - writeToFile.writelines(items) - writeToFile.close() - - # change back permissions - - command = 'sudo chown -R root:root /root' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - ## - - - final_dic = {'delete_status': 1} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException,msg: - final_dic = {'delete_status': 0} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except KeyError,msg: - final_dic = {'delete_status': 0} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.deleteSSHKey(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def addSSHKey(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('add_status', 0) - - try: - if request.method == 'POST': - data = json.loads(request.body) - key = data['key'] - - # temp change of permissions - - command = 'sudo chown -R cyberpanel:cyberpanel /root' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - ## - - sshDir = "/root/.ssh" - - pathToSSH = "/root/.ssh/authorized_keys" - - if os.path.exists(sshDir): - pass - else: - os.mkdir(sshDir) - - if os.path.exists(pathToSSH): - pass - else: - sshFile = open(pathToSSH,'w') - sshFile.writelines("#Created by CyberPanel\n") - sshFile.close() - - - - writeToFile = open(pathToSSH, 'a') - writeToFile.writelines("\n") - writeToFile.writelines(key) - writeToFile.writelines("\n") - writeToFile.close() - - # change back permissions - - command = 'sudo chown -R root:root /root' - - cmd = shlex.split(command) - - res = subprocess.call(cmd) - - ## - - - final_dic = {'add_status': 1} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - except BaseException,msg: - final_dic = {'add_status': 0} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - except KeyError,msg: - final_dic = {'add_status': 0} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.addSSHKey(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def loadModSecurityHome(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - confPath = os.path.join(virtualHostUtilities.Server_root,"conf/httpd_config.conf") - - command = "sudo cat " + confPath - httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() - - modSecInstalled = 0 - - for items in httpdConfig: - if items.find('module mod_security') > -1: - modSecInstalled = 1 - break - - return render(request,'firewall/modSecurity.html', {'modSecInstalled': modSecInstalled}) + fm = FirewallManager() + return fm.loadModSecurityHome(request, userID) except KeyError: return redirect(loadLoginPage) def installModSec(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('installModSec', 0) - - try: - thread.start_new_thread(modSec.installModSec, ('Install','modSec')) - final_json = json.dumps({'installModSec': 1, 'error_message': "None"}) - return HttpResponse(final_json) - - except BaseException,msg: - final_dic = {'installModSec': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.installModSec(userID, json.loads(request.body)) except KeyError: - final_dic = {'installModSec': 0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + return redirect(loadLoginPage) def installStatusModSec(request): try: - val = request.session['userID'] - admin = Administrator.objects.get(pk=val) - try: - if request.method == 'POST': - - - installStatus = unicode(open(modSec.installLogPath, "r").read()) - - if installStatus.find("[200]")>-1: - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" - - execPath = execPath + " installModSecConfigs" - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - pass - else: - final_json = json.dumps({ - 'error_message': "Failed to install ModSecurity configurations.", - 'requestStatus': installStatus, - 'abort': 1, - 'installed': 0, - }) - return HttpResponse(final_json) - - installUtilities.reStartLiteSpeed() - - final_json = json.dumps({ - 'error_message': "None", - 'requestStatus': installStatus, - 'abort':1, - 'installed': 1, - }) - return HttpResponse(final_json) - elif installStatus.find("[404]") > -1: - - final_json = json.dumps({ - 'abort':1, - 'installed':0, - 'error_message': "None", - 'requestStatus': installStatus, - }) - return HttpResponse(final_json) - - else: - final_json = json.dumps({ - 'abort':0, - 'error_message': "None", - 'requestStatus': installStatus, - }) - return HttpResponse(final_json) - - - except BaseException,msg: - final_dic = {'abort':1,'installed':0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + userID = request.session['userID'] + fm = FirewallManager() + return fm.installStatusModSec(userID) except KeyError: - final_dic = {'abort':1,'installed':0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + return redirect(loadLoginPage) def fetchModSecSettings(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('fetchStatus', 0) - - try: - if request.method == 'POST': - - - modsecurity = 0 - SecAuditEngine = 0 - SecRuleEngine = 0 - SecDebugLogLevel = "9" - SecAuditLogRelevantStatus = '^(?:5|4(?!04))' - SecAuditLogParts = 'ABIJDEFHZ' - SecAuditLogType = 'Serial' - - confPath = os.path.join(virtualHostUtilities.Server_root, 'conf/httpd_config.conf') - modSecPath = os.path.join(virtualHostUtilities.Server_root, 'modules', 'mod_security.so') - - if os.path.exists(modSecPath): - - command = "sudo cat " + confPath - - data = subprocess.check_output(shlex.split(command)).splitlines() - - for items in data: - - if items.find('modsecurity ') > -1: - if items.find('on') > -1 or items.find('On') > -1: - modsecurity = 1 - continue - if items.find('SecAuditEngine ') > -1: - if items.find('on') > -1 or items.find('On') > -1: - SecAuditEngine = 1 - continue - - if items.find('SecRuleEngine ') > -1: - if items.find('on') > -1 or items.find('On') > -1: - SecRuleEngine = 1 - continue - - if items.find('SecDebugLogLevel') > -1: - result = items.split(' ') - if result[0] == 'SecDebugLogLevel': - SecDebugLogLevel = result[1] - continue - if items.find('SecAuditLogRelevantStatus') > -1: - result = items.split(' ') - if result[0] == 'SecAuditLogRelevantStatus': - SecAuditLogRelevantStatus = result[1] - continue - if items.find('SecAuditLogParts') > -1: - result = items.split(' ') - if result[0] == 'SecAuditLogParts': - SecAuditLogParts = result[1] - continue - if items.find('SecAuditLogType') > -1: - result = items.split(' ') - if result[0] == 'SecAuditLogType': - SecAuditLogType = result[1] - continue - - - final_dic = {'fetchStatus': 1, - 'installed': 1, - 'SecRuleEngine': SecRuleEngine, - 'modsecurity': modsecurity, - 'SecAuditEngine': SecAuditEngine, - 'SecDebugLogLevel': SecDebugLogLevel, - 'SecAuditLogParts': SecAuditLogParts, - 'SecAuditLogRelevantStatus': SecAuditLogRelevantStatus, - 'SecAuditLogType': SecAuditLogType, - } - - else: - final_dic = {'fetchStatus': 1, - 'installed': 0} - - - - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - - - except BaseException,msg: - final_dic = {'fetchStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - - return HttpResponse(final_json) - - - return render(request,'managePHP/editPHPConfig.html') + fm = FirewallManager() + return fm.fetchModSecSettings(userID, json.loads(request.body)) except KeyError: return redirect(loadLoginPage) def saveModSecConfigurations(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('saveStatus', 0) - try: - if request.method == 'POST': - - data = json.loads(request.body) - - modsecurity = data['modsecurity_status'] - SecAuditEngine = data['SecAuditEngine'] - SecRuleEngine = data['SecRuleEngine'] - SecDebugLogLevel = data['SecDebugLogLevel'] - SecAuditLogParts = data['SecAuditLogParts'] - SecAuditLogRelevantStatus = data['SecAuditLogRelevantStatus'] - SecAuditLogType = data['SecAuditLogType'] - - if modsecurity == True: - modsecurity = "modsecurity on" - else: - modsecurity = "modsecurity off" - - if SecAuditEngine == True: - SecAuditEngine = "SecAuditEngine on" - else: - SecAuditEngine = "SecAuditEngine off" - - if SecRuleEngine == True: - SecRuleEngine = "SecRuleEngine On" - else: - SecRuleEngine = "SecRuleEngine off" - - SecDebugLogLevel = "SecDebugLogLevel " + str(SecDebugLogLevel) - SecAuditLogParts = "SecAuditLogParts " + str(SecAuditLogParts) - SecAuditLogRelevantStatus = "SecAuditLogRelevantStatus " + SecAuditLogRelevantStatus - SecAuditLogType = "SecAuditLogType " + SecAuditLogType - - - ## writing data temporary to file - - - tempConfigPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - confPath = open(tempConfigPath, "w") - - confPath.writelines(modsecurity + "\n") - confPath.writelines(SecAuditEngine + "\n") - confPath.writelines(SecRuleEngine + "\n") - confPath.writelines(SecDebugLogLevel + "\n") - confPath.writelines(SecAuditLogParts + "\n") - confPath.writelines(SecAuditLogRelevantStatus + "\n") - confPath.writelines(SecAuditLogType + "\n") - - confPath.close() - - ## save configuration data - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" - - execPath = execPath + " saveModSecConfigs --tempConfigPath " + tempConfigPath - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - installUtilities.reStartLiteSpeed() - data_ret = {'saveStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'saveStatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException,msg: - data_ret = {'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except KeyError,msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - data_ret = {'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + fm = FirewallManager() + return fm.saveModSecConfigurations(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def modSecRules(request): try: - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") - - command = "sudo cat " + confPath - httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() - - modSecInstalled = 0 - - for items in httpdConfig: - if items.find('module mod_security') > -1: - modSecInstalled = 1 - break - - return render(request, 'firewall/modSecurityRules.html',{'modSecInstalled': modSecInstalled}) - + fm = FirewallManager() + return fm.modSecRules(request, userID) except KeyError: return redirect(loadLoginPage) def fetchModSecRules(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('modSecInstalled', 0) - - confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") - - command = "sudo cat " + confPath - httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() - - modSecInstalled = 0 - - for items in httpdConfig: - if items.find('module mod_security') > -1: - modSecInstalled = 1 - break - - - rulesPath = os.path.join(virtualHostUtilities.Server_root + "/conf/modsec/rules.conf") - - if modSecInstalled: - command = "sudo cat " + rulesPath - currentModSecRules = subprocess.check_output(shlex.split(command)) - - final_dic = {'modSecInstalled': 1, - 'currentModSecRules': currentModSecRules} - - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - final_dic = {'modSecInstalled': 0} - - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.fetchModSecRules(userID, json.loads(request.body)) except KeyError: return redirect(loadLoginPage) def saveModSecRules(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('saveStatus', 0) - try: - if request.method == 'POST': - - data = json.loads(request.body) - - newModSecRules = data['modSecRules'] - - ## writing data temporary to file - - rulesPath = open(modSec.tempRulesFile, "w") - - rulesPath.write(newModSecRules) - - rulesPath.close() - - ## save configuration data - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" - - execPath = execPath + " saveModSecRules" - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - installUtilities.reStartLiteSpeed() - data_ret = {'saveStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'saveStatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException,msg: - data_ret = {'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except KeyError,msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - data_ret = {'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + fm = FirewallManager() + return fm.saveModSecRules(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def modSecRulesPacks(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadError() - - confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") - - command = "sudo cat " + confPath - httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() - - modSecInstalled = 0 - - for items in httpdConfig: - if items.find('module mod_security') > -1: - modSecInstalled = 1 - break - - return render(request, 'firewall/modSecurityRulesPacks.html',{'modSecInstalled': modSecInstalled}) - + fm = FirewallManager() + return fm.modSecRulesPacks(request, userID) except KeyError: return redirect(loadLoginPage) def getOWASPAndComodoStatus(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('modSecInstalled', 0) - - confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") - - command = "sudo cat " + confPath - httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() - - modSecInstalled = 0 - - for items in httpdConfig: - if items.find('module mod_security') > -1: - modSecInstalled = 1 - break - - comodoInstalled = 0 - owaspInstalled = 0 - - if modSecInstalled: - command = "sudo cat " + confPath - httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() - - for items in httpdConfig: - - if items.find('modsec/comodo') > -1: - comodoInstalled = 1 - elif items.find('modsec/owasp') > -1: - owaspInstalled = 1 - - if owaspInstalled == 1 and comodoInstalled == 1: - break - - final_dic = { - 'modSecInstalled': 1, - 'owaspInstalled': owaspInstalled, - 'comodoInstalled': comodoInstalled - } - - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - else: - final_dic = {'modSecInstalled': 0} - - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + fm = FirewallManager() + return fm.getOWASPAndComodoStatus(userID, json.loads(request.body)) except KeyError: return redirect(loadLoginPage) def installModSecRulesPack(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('installStatus', 0) - try: - if request.method == 'POST': - - data = json.loads(request.body) - - packName = data['packName'] - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" - - execPath = execPath + " " + packName - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - installUtilities.reStartLiteSpeed() - data_ret = {'installStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'installStatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException, msg: - data_ret = {'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except KeyError, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - data_ret = {'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + fm = FirewallManager() + return fm.installModSecRulesPack(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def getRulesFiles(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('fetchStatus', 0) - - try: - if request.method == 'POST': - - data = json.loads(request.body) - packName = data['packName'] - - confPath = os.path.join(virtualHostUtilities.Server_root, 'conf/httpd_config.conf') - - command = "sudo cat " + confPath - httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() - - json_data = "[" - checker = 0 - counter = 0 - - for items in httpdConfig: - - if items.find('modsec/'+packName) > -1: - counter = counter + 1 - if items[0] == '#': - status = False - else: - status = True - - fileName = items.lstrip('#') - fileName = fileName.split('/')[-1] - - dic = { - 'id': counter, - 'fileName': fileName, - 'packName':packName, - 'status': status, - - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - - json_data = json_data + ']' - final_json = json.dumps({'fetchStatus': 1, 'error_message': "None","data":json_data}) - return HttpResponse(final_json) - - except BaseException,msg: - final_dic = {'fetchStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - - return HttpResponse(final_json) + fm = FirewallManager() + return fm.getRulesFiles(userID, json.loads(request.body)) except KeyError: - final_dic = {'fetchStatus': 0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) + return redirect(loadLoginPage) def enableDisableRuleFile(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - else: - return ACLManager.loadErrorJson('saveStatus', 0) - try: - if request.method == 'POST': - - data = json.loads(request.body) - - packName = data['packName'] - fileName = data['fileName'] - currentStatus = data['status'] - - if currentStatus == True: - functionName = 'disableRuleFile' - else: - functionName = 'enableRuleFile' - - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" - - execPath = execPath + " " + functionName + ' --packName ' + packName + ' --fileName ' + fileName - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - installUtilities.reStartLiteSpeed() - data_ret = {'saveStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'saveStatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException,msg: - data_ret = {'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except BaseException, msg: - data_ret = {'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + fm = FirewallManager() + return fm.enableDisableRuleFile(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def csf(request): try: diff --git a/plogical/acl.py b/plogical/acl.py index a74cd34c2..e6a7cd2ff 100644 --- a/plogical/acl.py +++ b/plogical/acl.py @@ -7,7 +7,7 @@ django.setup() from loginSystem.models import Administrator, ACL from django.shortcuts import HttpResponse from packages.models import Package -from websiteFunctions.models import Websites +from websiteFunctions.models import Websites, ChildDomains from dns.models import Domains import json @@ -104,6 +104,18 @@ class ACLManager: return finalResponse + @staticmethod + def currentContextPermission(currentACL, context): + try: + if currentACL['admin'] == 1: + return 1 + elif currentACL[context] == 1: + return 1 + else: + return 0 + except: + pass + @staticmethod def createDefaultACLs(): try: @@ -372,17 +384,29 @@ class ACLManager: @staticmethod def checkOwnership(domain, admin, currentACL): - domainName = Websites.objects.get(domain=domain) + try: + childDomain = ChildDomains.objects.get(domain=domain) - if currentACL['admin'] == 1: - return 1 - elif domainName.admin == admin: - return 1 - else: - if domainName.admin.owner == admin.pk: + if currentACL['admin'] == 1: + return 1 + elif childDomain.master.admin == admin: return 1 else: - return 0 + if childDomain.master.admin.owner == admin.pk: + return 1 + + except: + domainName = Websites.objects.get(domain=domain) + + if currentACL['admin'] == 1: + return 1 + elif domainName.admin == admin: + return 1 + else: + if domainName.admin.owner == admin.pk: + return 1 + else: + return 0 diff --git a/plogical/applicationInstaller.py b/plogical/applicationInstaller.py index 3574f6546..f0e2db753 100644 --- a/plogical/applicationInstaller.py +++ b/plogical/applicationInstaller.py @@ -590,8 +590,7 @@ class ApplicationInstaller(multi.Thread): command = 'sudo GIT_SSH_COMMAND="ssh -i /root/.ssh/cyberpanel -o StrictHostKeyChecking=no" git clone ' \ '--depth 1 --no-single-branch git@' + defaultProvider +'.com:' + username + '/' + reponame + '.git -b ' + branch + ' ' + finalPath - result = subprocess.check_output(shlex.split(command)) - + subprocess.check_output(shlex.split(command)) except subprocess.CalledProcessError, msg: statusFile = open(tempStatusPath, 'w') statusFile.writelines('Failed to clone repository, make sure you deployed your key to repository. [404]') diff --git a/plogical/childDomain.py b/plogical/childDomain.py index e69de29bb..250fc8044 100644 --- a/plogical/childDomain.py +++ b/plogical/childDomain.py @@ -0,0 +1,40 @@ +#!/usr/local/CyberCP/bin/python2 +import os +import os.path +import sys +import django +sys.path.append('/usr/local/CyberCP') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") +django.setup() +from websiteFunctions.models import Websites +import json + + +class ChildDomainManager: + def __init__(self, masterDomain = None, childDomain = None): + self.masterDomain = masterDomain + self.childDomain = childDomain + + def findChildDomainsJson(self): + master = Websites.objects.get(domain=self.masterDomain) + childDomains = master.childdomains_set.all() + + json_data = "[" + checker = 0 + + for items in childDomains: + dic = { + 'childDomain': items.domain, + 'path': items.path, + 'childLunch': '/websites/' + self.masterDomain + '/' + items.domain + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + return json_data \ No newline at end of file diff --git a/plogical/firewallManager.py b/plogical/firewallManager.py new file mode 100644 index 000000000..b295422cb --- /dev/null +++ b/plogical/firewallManager.py @@ -0,0 +1,1176 @@ +#!/usr/local/CyberCP/bin/python2 +import os +import os.path +import sys +import django +sys.path.append('/usr/local/CyberCP') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") +django.setup() +import json +from acl import ACLManager +import CyberCPLogFileWriter as logging +from virtualHostUtilities import virtualHostUtilities +import subprocess +import shlex +from installUtilities import installUtilities +from django.shortcuts import HttpResponse, render, redirect +from loginSystem.models import Administrator +from random import randint +import time +from loginSystem.views import loadLoginPage +from plogical.firewallUtilities import FirewallUtilities +from firewall.models import FirewallRules +import thread +from plogical.modSec import modSec + +class FirewallManager: + + def securityHome(self, request = None, userID = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + return render(request, 'firewall/index.html') + except BaseException, msg: + return HttpResponse(str(msg)) + + def firewallHome(self, request = None, userID = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + return render(request, 'firewall/firewall.html') + except BaseException, msg: + return HttpResponse(str(msg)) + + def getCurrentRules(self, userID = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('fetchStatus', 0) + + rules = FirewallRules.objects.all() + + json_data = "[" + checker = 0 + + for items in rules: + dic = {'id': items.id, + 'name': items.name, + 'proto': items.proto, + 'port': items.port, + 'ipAddress': items.ipAddress, + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + final_json = json.dumps({'fetchStatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'fetchStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def addRule(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('add_status', 0) + + + ruleName = data['ruleName'] + ruleProtocol = data['ruleProtocol'] + rulePort = data['rulePort'] + ruleIP = data['ruleIP'] + + FirewallUtilities.addRule(ruleProtocol, rulePort, ruleIP) + + newFWRule = FirewallRules(name=ruleName, proto=ruleProtocol, port=rulePort, ipAddress=ruleIP) + newFWRule.save() + + final_dic = {'add_status': 1, 'error_message': "None"} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'add_status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def deleteRule(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('delete_status', 0) + + + ruleID = data['id'] + ruleProtocol = data['proto'] + rulePort = data['port'] + ruleIP = data['ruleIP'] + + FirewallUtilities.deleteRule(ruleProtocol, rulePort, ruleIP) + + delRule = FirewallRules.objects.get(id=ruleID) + delRule.delete() + + final_dic = {'delete_status': 1, 'error_message': "None"} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'delete_status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def reloadFirewall(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('reload_status', 0) + + command = 'sudo firewall-cmd --reload' + cmd = shlex.split(command) + res = subprocess.call(cmd) + + if res == 0: + final_dic = {'reload_status': 1, 'error_message': "None"} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + else: + final_dic = {'reload_status': 0, + 'error_message': "Can not reload firewall, see CyberCP main log file."} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'reload_status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def startFirewall(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('start_status', 0) + + command = 'sudo systemctl start firewalld' + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + if res == 0: + final_dic = {'start_status': 1, 'error_message': "None"} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + else: + final_dic = {'start_status': 0, + 'error_message': "Can not start firewall, see CyberCP main log file."} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'start_status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def stopFirewall(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('stop_status', 0) + + command = 'sudo systemctl stop firewalld' + cmd = shlex.split(command) + res = subprocess.call(cmd) + + if res == 0: + final_dic = {'stop_status': 1, 'error_message': "None"} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + else: + final_dic = {'stop_status': 0, + 'error_message': "Can not stop firewall, see CyberCP main log file."} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'stop_status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def firewallStatus(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + command = 'sudo systemctl status firewalld' + + status = subprocess.check_output(shlex.split(command)) + + if status.find("active") > -1: + final_dic = {'status': 1, 'error_message': "none", 'firewallStatus': 1} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + else: + final_dic = {'status': 1, 'error_message': "none", 'firewallStatus': 0} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def secureSSH(self, request = None, userID = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + return render(request, 'firewall/secureSSH.html') + except BaseException, msg: + return HttpResponse(str(msg)) + + def getSSHConfigs(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson() + + type = data['type'] + + if type == "1": + + ## temporarily changing permission for sshd files + + command = 'sudo chown -R cyberpanel:cyberpanel /etc/ssh/sshd_config' + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + pathToSSH = "/etc/ssh/sshd_config" + + data = open(pathToSSH, 'r').readlines() + + permitRootLogin = 0 + sshPort = "22" + + for items in data: + if items.find("PermitRootLogin") > -1: + if items.find("Yes") > -1 or items.find("yes") > -1: + permitRootLogin = 1 + continue + if items.find("Port") > -1 and not items.find("GatewayPorts") > -1: + sshPort = items.split(" ")[1].strip("\n") + + ## changing permission back + + command = 'sudo chown -R root:root /etc/ssh/sshd_config' + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + final_dic = {'permitRootLogin': permitRootLogin, 'sshPort': sshPort} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + else: + + ## temporarily changing permission for sshd files + + command = 'sudo chown -R cyberpanel:cyberpanel /root' + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + pathToKeyFile = "/root/.ssh/authorized_keys" + + json_data = "[" + checker = 0 + + data = open(pathToKeyFile, 'r').readlines() + + for items in data: + if items.find("ssh-rsa") > -1: + keydata = items.split(" ") + + key = "ssh-rsa " + keydata[1][:50] + " ... " + keydata[2] + + try: + userName = keydata[2][:keydata[2].index("@")] + except: + userName = keydata[2] + + dic = {'userName': userName, + 'key': key, + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + ## changing permission back + + command = 'sudo chown -R root:root /root' + cmd = shlex.split(command) + res = subprocess.call(cmd) + + final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'status': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def saveSSHConfigs(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('saveStatus', 0) + + type = data['type'] + + if type == "1": + + sshPort = data['sshPort'] + rootLogin = data['rootLogin'] + + command = 'sudo semanage port -a -t ssh_port_t -p tcp ' + sshPort + cmd = shlex.split(command) + res = subprocess.call(cmd) + + FirewallUtilities.addRule('tcp', sshPort, "0.0.0.0/0") + + try: + updateFW = FirewallRules.objects.get(name="SSHCustom") + FirewallUtilities.deleteRule("tcp", updateFW.port) + updateFW.port = sshPort + updateFW.save() + except: + try: + newFireWallRule = FirewallRules(name="SSHCustom", port=sshPort, proto="tcp") + newFireWallRule.save() + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + + ## temporarily changing permission for sshd files + + command = 'sudo chown -R cyberpanel:cyberpanel /etc/ssh/sshd_config' + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + ## + + + if rootLogin == True: + rootLogin = "PermitRootLogin yes\n" + else: + rootLogin = "PermitRootLogin no\n" + + sshPort = "Port " + sshPort + "\n" + + pathToSSH = "/etc/ssh/sshd_config" + + data = open(pathToSSH, 'r').readlines() + + writeToFile = open(pathToSSH, "w") + + for items in data: + if items.find("PermitRootLogin") > -1: + if items.find("Yes") > -1 or items.find("yes"): + writeToFile.writelines(rootLogin) + continue + elif items.find("Port") > -1: + writeToFile.writelines(sshPort) + else: + writeToFile.writelines(items) + writeToFile.close() + + command = 'sudo systemctl restart sshd' + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + ## changin back permissions + + command = 'sudo chown -R root:root /etc/ssh/sshd_config' + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + ## + + final_dic = {'saveStatus': 1} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'saveStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def deleteSSHKey(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('delete_status', 0) + + key = data['key'] + + # temp change of permissions + + command = 'sudo chown -R cyberpanel:cyberpanel /root' + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + ## + + keyPart = key.split(" ")[1] + + pathToSSH = "/root/.ssh/authorized_keys" + + data = open(pathToSSH, 'r').readlines() + + writeToFile = open(pathToSSH, "w") + + for items in data: + if items.find("ssh-rsa") > -1 and items.find(keyPart) > -1: + continue + else: + writeToFile.writelines(items) + writeToFile.close() + + # change back permissions + + command = 'sudo chown -R root:root /root' + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + ## + + final_dic = {'delete_status': 1} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'delete_status': 0, 'error_mssage': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def addSSHKey(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('add_status', 0) + + key = data['key'] + + # temp change of permissions + + command = 'sudo chown -R cyberpanel:cyberpanel /root' + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + ## + + sshDir = "/root/.ssh" + + pathToSSH = "/root/.ssh/authorized_keys" + + if os.path.exists(sshDir): + pass + else: + os.mkdir(sshDir) + + if os.path.exists(pathToSSH): + pass + else: + sshFile = open(pathToSSH, 'w') + sshFile.writelines("#Created by CyberPanel\n") + sshFile.close() + + writeToFile = open(pathToSSH, 'a') + writeToFile.writelines("\n") + writeToFile.writelines(key) + writeToFile.writelines("\n") + writeToFile.close() + + # change back permissions + + command = 'sudo chown -R root:root /root' + + cmd = shlex.split(command) + + res = subprocess.call(cmd) + + ## + + + final_dic = {'add_status': 1} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'add_status': 0, 'error_mssage': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def loadModSecurityHome(self, request = None, userID = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + + command = "sudo cat " + confPath + httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() + + modSecInstalled = 0 + + for items in httpdConfig: + if items.find('module mod_security') > -1: + modSecInstalled = 1 + break + return render(request, 'firewall/modSecurity.html', {'modSecInstalled': modSecInstalled}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def installModSec(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('installModSec', 0) + + thread.start_new_thread(modSec.installModSec, ('Install', 'modSec')) + final_json = json.dumps({'installModSec': 1, 'error_message': "None"}) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'installModSec': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def installStatusModSec(self, userID = None, data = None): + try: + + installStatus = unicode(open(modSec.installLogPath, "r").read()) + + if installStatus.find("[200]") > -1: + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" + + execPath = execPath + " installModSecConfigs" + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + pass + else: + final_json = json.dumps({ + 'error_message': "Failed to install ModSecurity configurations.", + 'requestStatus': installStatus, + 'abort': 1, + 'installed': 0, + }) + return HttpResponse(final_json) + + installUtilities.reStartLiteSpeed() + + final_json = json.dumps({ + 'error_message': "None", + 'requestStatus': installStatus, + 'abort': 1, + 'installed': 1, + }) + return HttpResponse(final_json) + elif installStatus.find("[404]") > -1: + + final_json = json.dumps({ + 'abort': 1, + 'installed': 0, + 'error_message': "None", + 'requestStatus': installStatus, + }) + return HttpResponse(final_json) + + else: + final_json = json.dumps({ + 'abort': 0, + 'error_message': "None", + 'requestStatus': installStatus, + }) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'abort': 1, 'installed': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def fetchModSecSettings(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('fetchStatus', 0) + + modsecurity = 0 + SecAuditEngine = 0 + SecRuleEngine = 0 + SecDebugLogLevel = "9" + SecAuditLogRelevantStatus = '^(?:5|4(?!04))' + SecAuditLogParts = 'ABIJDEFHZ' + SecAuditLogType = 'Serial' + + confPath = os.path.join(virtualHostUtilities.Server_root, 'conf/httpd_config.conf') + modSecPath = os.path.join(virtualHostUtilities.Server_root, 'modules', 'mod_security.so') + + if os.path.exists(modSecPath): + + command = "sudo cat " + confPath + + data = subprocess.check_output(shlex.split(command)).splitlines() + + for items in data: + + if items.find('modsecurity ') > -1: + if items.find('on') > -1 or items.find('On') > -1: + modsecurity = 1 + continue + if items.find('SecAuditEngine ') > -1: + if items.find('on') > -1 or items.find('On') > -1: + SecAuditEngine = 1 + continue + + if items.find('SecRuleEngine ') > -1: + if items.find('on') > -1 or items.find('On') > -1: + SecRuleEngine = 1 + continue + + if items.find('SecDebugLogLevel') > -1: + result = items.split(' ') + if result[0] == 'SecDebugLogLevel': + SecDebugLogLevel = result[1] + continue + if items.find('SecAuditLogRelevantStatus') > -1: + result = items.split(' ') + if result[0] == 'SecAuditLogRelevantStatus': + SecAuditLogRelevantStatus = result[1] + continue + if items.find('SecAuditLogParts') > -1: + result = items.split(' ') + if result[0] == 'SecAuditLogParts': + SecAuditLogParts = result[1] + continue + if items.find('SecAuditLogType') > -1: + result = items.split(' ') + if result[0] == 'SecAuditLogType': + SecAuditLogType = result[1] + continue + + final_dic = {'fetchStatus': 1, + 'installed': 1, + 'SecRuleEngine': SecRuleEngine, + 'modsecurity': modsecurity, + 'SecAuditEngine': SecAuditEngine, + 'SecDebugLogLevel': SecDebugLogLevel, + 'SecAuditLogParts': SecAuditLogParts, + 'SecAuditLogRelevantStatus': SecAuditLogRelevantStatus, + 'SecAuditLogType': SecAuditLogType, + } + + else: + final_dic = {'fetchStatus': 1, + 'installed': 0} + + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'fetchStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def saveModSecConfigurations(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('saveStatus', 0) + + modsecurity = data['modsecurity_status'] + SecAuditEngine = data['SecAuditEngine'] + SecRuleEngine = data['SecRuleEngine'] + SecDebugLogLevel = data['SecDebugLogLevel'] + SecAuditLogParts = data['SecAuditLogParts'] + SecAuditLogRelevantStatus = data['SecAuditLogRelevantStatus'] + SecAuditLogType = data['SecAuditLogType'] + + if modsecurity == True: + modsecurity = "modsecurity on" + else: + modsecurity = "modsecurity off" + + if SecAuditEngine == True: + SecAuditEngine = "SecAuditEngine on" + else: + SecAuditEngine = "SecAuditEngine off" + + if SecRuleEngine == True: + SecRuleEngine = "SecRuleEngine On" + else: + SecRuleEngine = "SecRuleEngine off" + + SecDebugLogLevel = "SecDebugLogLevel " + str(SecDebugLogLevel) + SecAuditLogParts = "SecAuditLogParts " + str(SecAuditLogParts) + SecAuditLogRelevantStatus = "SecAuditLogRelevantStatus " + SecAuditLogRelevantStatus + SecAuditLogType = "SecAuditLogType " + SecAuditLogType + + ## writing data temporary to file + + + tempConfigPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + confPath = open(tempConfigPath, "w") + + confPath.writelines(modsecurity + "\n") + confPath.writelines(SecAuditEngine + "\n") + confPath.writelines(SecRuleEngine + "\n") + confPath.writelines(SecDebugLogLevel + "\n") + confPath.writelines(SecAuditLogParts + "\n") + confPath.writelines(SecAuditLogRelevantStatus + "\n") + confPath.writelines(SecAuditLogType + "\n") + + confPath.close() + + ## save configuration data + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" + + execPath = execPath + " saveModSecConfigs --tempConfigPath " + tempConfigPath + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + installUtilities.reStartLiteSpeed() + data_ret = {'saveStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'saveStatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'saveStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def modSecRules(self, request = None, userID = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + + command = "sudo cat " + confPath + httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() + + modSecInstalled = 0 + + for items in httpdConfig: + if items.find('module mod_security') > -1: + modSecInstalled = 1 + break + + return render(request, 'firewall/modSecurityRules.html', {'modSecInstalled': modSecInstalled}) + + except BaseException, msg: + return HttpResponse(str(msg)) + + def fetchModSecRules(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('modSecInstalled', 0) + + confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + + command = "sudo cat " + confPath + httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() + + modSecInstalled = 0 + + for items in httpdConfig: + if items.find('module mod_security') > -1: + modSecInstalled = 1 + break + + rulesPath = os.path.join(virtualHostUtilities.Server_root + "/conf/modsec/rules.conf") + + if modSecInstalled: + command = "sudo cat " + rulesPath + currentModSecRules = subprocess.check_output(shlex.split(command)) + + final_dic = {'modSecInstalled': 1, + 'currentModSecRules': currentModSecRules} + + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + else: + final_dic = {'modSecInstalled': 0} + + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'modSecInstalled': 0, + 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def saveModSecRules(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('saveStatus', 0) + + newModSecRules = data['modSecRules'] + + ## writing data temporary to file + + rulesPath = open(modSec.tempRulesFile, "w") + + rulesPath.write(newModSecRules) + + rulesPath.close() + + ## save configuration data + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" + + execPath = execPath + " saveModSecRules" + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + installUtilities.reStartLiteSpeed() + data_ret = {'saveStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'saveStatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'saveStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def modSecRulesPacks(self, request = None, userID = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadError() + + confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + + command = "sudo cat " + confPath + httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() + + modSecInstalled = 0 + + for items in httpdConfig: + if items.find('module mod_security') > -1: + modSecInstalled = 1 + break + + return render(request, 'firewall/modSecurityRulesPacks.html', {'modSecInstalled': modSecInstalled}) + + except BaseException, msg: + return HttpResponse(msg) + + def getOWASPAndComodoStatus(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('modSecInstalled', 0) + + confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf") + + command = "sudo cat " + confPath + httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() + + modSecInstalled = 0 + + for items in httpdConfig: + if items.find('module mod_security') > -1: + modSecInstalled = 1 + break + + comodoInstalled = 0 + owaspInstalled = 0 + + if modSecInstalled: + command = "sudo cat " + confPath + httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() + + for items in httpdConfig: + + if items.find('modsec/comodo') > -1: + comodoInstalled = 1 + elif items.find('modsec/owasp') > -1: + owaspInstalled = 1 + + if owaspInstalled == 1 and comodoInstalled == 1: + break + + final_dic = { + 'modSecInstalled': 1, + 'owaspInstalled': owaspInstalled, + 'comodoInstalled': comodoInstalled + } + + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + else: + final_dic = {'modSecInstalled': 0} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException, msg: + final_dic = {'modSecInstalled': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def installModSecRulesPack(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + packName = data['packName'] + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" + + execPath = execPath + " " + packName + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + installUtilities.reStartLiteSpeed() + data_ret = {'installStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'installStatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def getRulesFiles(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('fetchStatus', 0) + + packName = data['packName'] + + confPath = os.path.join(virtualHostUtilities.Server_root, 'conf/httpd_config.conf') + + command = "sudo cat " + confPath + httpdConfig = subprocess.check_output(shlex.split(command)).splitlines() + + json_data = "[" + checker = 0 + counter = 0 + + for items in httpdConfig: + + if items.find('modsec/' + packName) > -1: + counter = counter + 1 + if items[0] == '#': + status = False + else: + status = True + + fileName = items.lstrip('#') + fileName = fileName.split('/')[-1] + + dic = { + 'id': counter, + 'fileName': fileName, + 'packName': packName, + 'status': status, + + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + final_json = json.dumps({'fetchStatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'fetchStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def enableDisableRuleFile(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] == 1: + pass + else: + return ACLManager.loadErrorJson('saveStatus', 0) + + packName = data['packName'] + fileName = data['fileName'] + currentStatus = data['status'] + + if currentStatus == True: + functionName = 'disableRuleFile' + else: + functionName = 'enableRuleFile' + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py" + + execPath = execPath + " " + functionName + ' --packName ' + packName + ' --fileName ' + fileName + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + installUtilities.reStartLiteSpeed() + data_ret = {'saveStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'saveStatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'saveStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) \ No newline at end of file diff --git a/plogical/upgrade.py b/plogical/upgrade.py index 1b6c5a474..3af417b02 100644 --- a/plogical/upgrade.py +++ b/plogical/upgrade.py @@ -336,7 +336,7 @@ WantedBy=multi-user.target""" cmd = shlex.split(command) subprocess.call(cmd) - passwordCMD = "use " + dbName + ";insert into loginSystem_acl (id, name) values (3,'user');" + passwordCMD = "use " + dbName + ";insert into loginSystem_acl (id, name, createDatabase, deleteDatabase, listDatabases, createDNSZone, deleteZone, addDeleteRecords, createEmail, deleteEmail, emailForwarding, changeEmailPassword, dkimManager, createFTPAccount, deleteFTPAccount, listFTPAccounts, createBackup, manageSSL) values (3,'user', 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1);" command = 'sudo mysql --host=' + host + ' --port=' + port + ' -u ' + dbUser + ' -p' + password + ' -e "' + passwordCMD + '"' cmd = shlex.split(command) subprocess.call(cmd) @@ -351,6 +351,11 @@ WantedBy=multi-user.target""" cmd = shlex.split(command) subprocess.call(cmd) + passwordCMD = "use " + dbName + ";alter table loginSystem_administrator drop initUserAccountsLimit;" + command = 'sudo mysql --host=' + host + ' --port=' + port + ' -u ' + dbUser + ' -p' + password + ' -e "' + passwordCMD + '"' + cmd = shlex.split(command) + subprocess.call(cmd) + os.chdir(cwd) except OSError, msg: diff --git a/plogical/vhost.py b/plogical/vhost.py index 2e1e91468..feeaf574c 100644 --- a/plogical/vhost.py +++ b/plogical/vhost.py @@ -452,11 +452,12 @@ RewriteFile .htaccess return [0,"223 [IO Error with main config file [createConfigInMainVirtualHostFile]]"] @staticmethod - def deleteVirtualHostConfigurations(virtualHostName, numberOfSites): + def deleteVirtualHostConfigurations(virtualHostName): try: ## Deleting master conf + numberOfSites = str(Websites.objects.count() + ChildDomains.objects.count()) vhost.deleteCoreConf(virtualHostName, numberOfSites) delWebsite = Websites.objects.get(domain=virtualHostName) @@ -999,4 +1000,5 @@ RewriteFile .htaccess except BaseException, msg: logging.CyberCPLogFileWriter.writeToFile( str(msg) + "223 [IO Error with main config file [createConfigInMainDomainHostFile]]") - return [0, "223 [IO Error with main config file [createConfigInMainDomainHostFile]]"] \ No newline at end of file + return [0, "223 [IO Error with main config file [createConfigInMainDomainHostFile]]"] + diff --git a/plogical/virtualHostUtilities.py b/plogical/virtualHostUtilities.py index cd99cf0b8..cd48b583a 100644 --- a/plogical/virtualHostUtilities.py +++ b/plogical/virtualHostUtilities.py @@ -14,7 +14,7 @@ from os.path import join from os import listdir, rmdir from shutil import move from multiprocessing import Process -from websiteFunctions.models import Websites, ChildDomains +from websiteFunctions.models import Websites, ChildDomains, aliasDomains from loginSystem.models import Administrator from packages.models import Package import subprocess @@ -137,8 +137,7 @@ class virtualHostUtilities: return 1, 'None' except BaseException, msg: - numberOfWebsites = str(Websites.objects.count() + ChildDomains.objects.count()) - vhost.deleteVirtualHostConfigurations(virtualHostName, numberOfWebsites) + vhost.deleteVirtualHostConfigurations(virtualHostName) logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createVirtualHost]") logging.CyberCPLogFileWriter.statusWriter(tempStatusPath, str(msg) + " [404]") return 0, str(msg) @@ -597,10 +596,14 @@ class virtualHostUtilities: else: vhost.createAliasSSLMap(confPath, masterDomain, aliasDomain) + website = Websites.objects.get(domain=masterDomain) + + newAlias = aliasDomains(master=website, aliasDomain = aliasDomain) + newAlias.save() + print "1,None" except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [createAlias]") print "0," + str(msg) @@ -664,6 +667,9 @@ class virtualHostUtilities: writeToFile.close() installUtilities.installUtilities.reStartLiteSpeed() + delAlias = aliasDomains.objects.get(aliasDomain=aliasDomain) + delAlias.delete() + print "1,None" @@ -1018,7 +1024,7 @@ def main(): virtualHostUtilities.createVirtualHost(args.virtualHostName, args.administratorEmail, args.phpVersion, args.virtualHostUser, int(args.ssl), dkimCheck, openBasedir, args.websiteOwner, args.package, tempStatusPath) elif args.function == "deleteVirtualHostConfigurations": - vhost.deleteVirtualHostConfigurations(args.virtualHostName,int(args.numberOfSites)) + vhost.deleteVirtualHostConfigurations(args.virtualHostName) elif args.function == "createDomain": try: dkimCheck = int(args.dkimCheck) diff --git a/plogical/website.py b/plogical/website.py new file mode 100644 index 000000000..1104b8d3c --- /dev/null +++ b/plogical/website.py @@ -0,0 +1,1942 @@ +#!/usr/local/CyberCP/bin/python2 +import os +import os.path +import sys +import django +sys.path.append('/usr/local/CyberCP') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings") +django.setup() +import json +from acl import ACLManager +import CyberCPLogFileWriter as logging +from websiteFunctions.models import Websites, ChildDomains +from virtualHostUtilities import virtualHostUtilities +import subprocess +import shlex +from installUtilities import installUtilities +from django.shortcuts import HttpResponse, render +from loginSystem.models import Administrator +from packages.models import Package +from mailUtilities import mailUtilities +from random import randint +import time +import re +from childDomain import ChildDomainManager +from math import ceil +from plogical.alias import AliasManager +from plogical.applicationInstaller import ApplicationInstaller +from databases.models import Databases +import randomPassword as randomPassword +import hashlib +from mysqlUtilities import mysqlUtilities + +class WebsiteManager: + def __init__(self, domain = None, childDomain = None): + self.domain = domain + self.childDomain = childDomain + + def createWebsite(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: + return ACLManager.loadError() + + adminNames = ACLManager.loadAllUsers(userID) + packagesName = ACLManager.loadPackages(userID, currentACL) + + Data = {'packageList': packagesName, "owernList": adminNames} + return render(request, 'websiteFunctions/createWebsite.html', Data) + + except BaseException, msg: + return HttpResponse(str(msg)) + + def modifyWebsite(self, request = None, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: + return ACLManager.loadError() + + websitesName = ACLManager.findAllSites(currentACL, userID) + + return render(request, 'websiteFunctions/modifyWebsite.html', {'websiteList': websitesName}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def deleteWebsite(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'deleteWebsite') == 0: + return ACLManager.loadError() + + websitesName = ACLManager.findAllSites(currentACL, userID) + + return render(request, 'websiteFunctions/deleteWebsite.html', {'websiteList': websitesName}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def siteState(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + + if ACLManager.currentContextPermission(currentACL, 'suspendWebsite') == 0: + return ACLManager.loadError() + + websitesName = ACLManager.findAllSites(currentACL, userID) + + return render(request, 'websiteFunctions/suspendWebsite.html', {'websiteList': websitesName}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def listWebsites(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + websites = ACLManager.findAllSites(currentACL, userID) + + pages = float(len(websites)) / float(10) + pagination = [] + + if pages <= 1.0: + pages = 1 + pagination.append('
  • ') + else: + pages = ceil(pages) + finalPages = int(pages) + 1 + + for i in range(1, finalPages): + pagination.append('
  • ' + str(i) + '
  • ') + + return render(request, 'websiteFunctions/listWebsites.html', {"pagination": pagination}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def listCron(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + websitesName = ACLManager.findAllSites(currentACL, userID) + return render(request, 'websiteFunctions/listCron.html', {'websiteList': websitesName}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def domainAlias(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + aliasManager = AliasManager(self.domain) + noAlias, finalAlisList = aliasManager.fetchAlisForDomains() + + path = "/home/" + self.domain + "/public_html" + + return render(request, 'websiteFunctions/domainAlias.html', { + 'masterDomain': self.domain, + 'aliases': finalAlisList, + 'path': path, + 'noAlias': noAlias + }) + except BaseException, msg: + return HttpResponse(str(msg)) + + def submitWebsiteCreation(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'createWebsite') == 0: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + domain = data['domainName'] + adminEmail = data['adminEmail'] + phpSelection = data['phpSelection'] + packageName = data['package'] + websiteOwner = data['websiteOwner'] + externalApp = "".join(re.findall("[a-zA-Z]+", domain))[:7] + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + ## Create Configurations + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " createVirtualHost --virtualHostName " + domain + \ + " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \ + "' --virtualHostUser " + externalApp + " --ssl " + str(data['ssl']) + " --dkimCheck " \ + + str(data['dkimCheck']) + " --openBasedir " + str(data['openBasedir']) + \ + ' --websiteOwner ' + websiteOwner + ' --package ' + packageName + ' --tempStatusPath ' + tempStatusPath + + subprocess.Popen(shlex.split(execPath)) + time.sleep(2) + + data_ret = {'createWebSiteStatus': 1, 'error_message': "None", 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException, msg: + data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitDomainCreation(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + masterDomain = data['masterDomain'] + domain = data['domainName'] + phpSelection = data['phpSelection'] + path = data['path'] + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('createWebSiteStatus', 0) + + if currentACL['admin'] != 1: + data['openBasedir'] = 1 + + + if len(path) > 0: + path = path.lstrip("/") + path = "/home/" + masterDomain + "/public_html/" + path + else: + path = "/home/" + masterDomain + "/public_html/" + domain + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ + " --phpVersion '" + phpSelection + "' --ssl " + str(data['ssl']) + " --dkimCheck " + str( + data['dkimCheck']) \ + + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path + ' --websiteOwner ' \ + + admin.userName + ' --tempStatusPath ' + tempStatusPath + + subprocess.Popen(shlex.split(execPath)) + time.sleep(2) + + data_ret = {'createWebSiteStatus': 1, 'error_message': "None", 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def fetchDomains(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + masterDomain = data['masterDomain'] + + if ACLManager.checkOwnership(masterDomain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('fetchStatus', 0) + + cdManager = ChildDomainManager(masterDomain) + json_data = cdManager.findChildDomainsJson() + + final_json = json.dumps({'fetchStatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + except BaseException, msg: + final_dic = {'fetchStatus': 0, 'error_message': str(msg)} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + + def getFurtherAccounts(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + pageNumber = int(data['page']) + json_data = self.findWebsitesJson(currentACL, userID, pageNumber) + final_dic = {'listWebSiteStatus': 1, 'error_message': "None", "data": json_data} + final_json = json.dumps(final_dic) + return HttpResponse(final_json) + except BaseException, msg: + dic = {'listWebSiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def submitWebsiteDeletion(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'deleteWebsite') == 0: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + websiteName = data['websiteName'] + + ## Deleting master domain + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName + subprocess.check_output(shlex.split(execPath)) + + data_ret = {'websiteDeleteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'websiteDeleteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitDomainDeletion(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + websiteName = data['websiteName'] + + if ACLManager.checkOwnership(websiteName, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('websiteDeleteStatus', 0) + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " deleteDomain --virtualHostName " + websiteName + subprocess.check_output(shlex.split(execPath)) + + data_ret = {'websiteDeleteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'websiteDeleteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitWebsiteStatus(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'suspendWebsite') == 0: + return ACLManager.loadErrorJson('websiteStatus', 0) + + websiteName = data['websiteName'] + state = data['state'] + + website = Websites.objects.get(domain=websiteName) + + if state == "Suspend": + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName + command = "sudo mv " + confPath + " " + confPath + "-suspended" + subprocess.call(shlex.split(command)) + installUtilities.reStartLiteSpeed() + website.state = 0 + else: + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName + + command = "sudo mv " + confPath + "-suspended" + " " + confPath + subprocess.call(shlex.split(command)) + + command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath + cmd = shlex.split(command) + subprocess.call(cmd) + + installUtilities.reStartLiteSpeed() + website.state = 1 + + website.save() + + data_ret = {'websiteStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + + data_ret = {'websiteStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def submitWebsiteModify(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: + return ACLManager.loadErrorJson('modifyStatus', 0) + + packs = ACLManager.loadPackages(userID, currentACL) + admins = ACLManager.loadAllUsers(userID) + + ## Get packs name + + json_data = "[" + checker = 0 + + for items in packs: + dic = {"pack": items} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + ### Get admin names + + admin_data = "[" + checker = 0 + + for items in admins: + dic = {"adminNames": items} + + if checker == 0: + admin_data = admin_data + json.dumps(dic) + checker = 1 + else: + admin_data = admin_data + ',' + json.dumps(dic) + + admin_data = admin_data + ']' + + websiteToBeModified = data['websiteToBeModified'] + + modifyWeb = Websites.objects.get(domain=websiteToBeModified) + + email = modifyWeb.adminEmail + currentPack = modifyWeb.package.packageName + owner = modifyWeb.admin.userName + + data_ret = {'modifyStatus': 1, 'error_message': "None", "adminEmail": email, + "packages": json_data, "current_pack": currentPack, "adminNames": admin_data, + 'currentAdmin': owner} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + except BaseException, msg: + dic = {'modifyStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def saveWebsiteChanges(self, userID = None, data = None): + try: + domain = data['domain'] + package = data['packForWeb'] + email = data['email'] + phpVersion = data['phpVersion'] + newUser = data['admin'] + + currentACL = ACLManager.loadedACL(userID) + if ACLManager.currentContextPermission(currentACL, 'modifyWebsite') == 0: + return ACLManager.loadErrorJson('saveStatus', 0) + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domain + completePathToConfigFile = confPath + "/vhost.conf" + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + pass + else: + data_ret = {'saveStatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## php changes ends + + newOwner = Administrator.objects.get(userName=newUser) + + modifyWeb = Websites.objects.get(domain=domain) + webpack = Package.objects.get(packageName=package) + + modifyWeb.package = webpack + modifyWeb.adminEmail = email + modifyWeb.phpSelection = phpVersion + modifyWeb.admin = newOwner + + modifyWeb.save() + + data_ret = {'saveStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'saveStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def loadDomainHome(self, request = None, userID = None, data = None): + + if Websites.objects.filter(domain=self.domain).exists(): + + currentACL = ACLManager.loadedACL(userID) + website = Websites.objects.get(domain=self.domain) + admin = Administrator.objects.get(pk=userID) + + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + Data = {} + + Data['ftpTotal'] = website.package.ftpAccounts + Data['ftpUsed'] = website.users_set.all().count() + + Data['databasesUsed'] = website.databases_set.all().count() + Data['databasesTotal'] = website.package.dataBases + + Data['domain'] = self.domain + + diskUsageDetails = virtualHostUtilities.getDiskUsage("/home/" + self.domain, website.package.diskSpace) + + ## bw usage calculation + + try: + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str( + website.package.bandwidth) + + output = subprocess.check_output(shlex.split(execPath)) + bwData = output.split(",") + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + bwData = [0, 0] + + ## bw usage calculations + + Data['bwInMBTotal'] = website.package.bandwidth + Data['bwInMB'] = bwData[0] + Data['bwUsage'] = bwData[1] + + if diskUsageDetails != None: + if diskUsageDetails[1] > 100: + diskUsageDetails[1] = 100 + + Data['diskUsage'] = diskUsageDetails[1] + Data['diskInMB'] = diskUsageDetails[0] + Data['diskInMBTotal'] = website.package.diskSpace + else: + Data['diskUsage'] = 0 + Data['diskInMB'] = 0 + Data['diskInMBTotal'] = website.package.diskSpace + + return render(request, 'websiteFunctions/website.html', Data) + + else: + return render(request, 'websiteFunctions/website.html', + {"error": 1, "domain": "This domain does not exists."}) + + def launchChild(self, request = None, userID = None, data = None): + + if ChildDomains.objects.filter(domain=self.childDomain).exists(): + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + website = Websites.objects.get(domain=self.domain) + + Data = {} + + Data['ftpTotal'] = website.package.ftpAccounts + Data['ftpUsed'] = website.users_set.all().count() + + Data['databasesUsed'] = website.databases_set.all().count() + Data['databasesTotal'] = website.package.dataBases + + Data['domain'] = self.domain + Data['childDomain'] = self.childDomain + + diskUsageDetails = virtualHostUtilities.getDiskUsage("/home/" + self.domain, website.package.diskSpace) + + ## bw usage calculation + + try: + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + execPath = execPath + " findDomainBW --virtualHostName " + self.domain + " --bandwidth " + str( + website.package.bandwidth) + + output = subprocess.check_output(shlex.split(execPath)) + bwData = output.split(",") + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile(str(msg)) + bwData = [0, 0] + + ## bw usage calculations + + Data['bwInMBTotal'] = website.package.bandwidth + Data['bwInMB'] = bwData[0] + Data['bwUsage'] = bwData[1] + + if diskUsageDetails != None: + if diskUsageDetails[1] > 100: + diskUsageDetails[1] = 100 + + Data['diskUsage'] = diskUsageDetails[1] + Data['diskInMB'] = diskUsageDetails[0] + Data['diskInMBTotal'] = website.package.diskSpace + else: + Data['diskUsage'] = 0 + Data['diskInMB'] = 0 + Data['diskInMBTotal'] = website.package.diskSpace + + return render(request, 'websiteFunctions/launchChild.html', Data) + else: + return render(request, 'websiteFunctions/launchChild.html', {"error":1,"domain": "This child domain does not exists"}) + + def getDataFromLogFile(self, userID = None, data = None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + logType = data['logType'] + self.domain = data['virtualHost'] + page = data['page'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('logstatus', 0) + + + if logType == 1: + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".access_log" + else: + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" + + ## get Logs + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " getAccessLogs --path " + fileName + " --page " + str(page) + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + final_json = json.dumps( + {'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) + return HttpResponse(final_json) + + ## get log ends here. + + + data = output.split("\n") + + json_data = "[" + checker = 0 + + for items in reversed(data): + if len(items) > 10: + logData = items.split(" ") + domain = logData[0].strip('"') + ipAddress = logData[1] + time = (logData[4]).strip("[").strip("]") + resource = logData[7].strip('"') + size = logData[10].replace('"', '') + + dic = {'domain': domain, + 'ipAddress': ipAddress, + 'time': time, + 'resource': resource, + 'size': size, + } + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + final_json = json.dumps({'logstatus': 1, 'error_message': "None", "data": json_data}) + return HttpResponse(final_json) + + def fetchErrorLogs(self, userID = None, data = None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['virtualHost'] + page = data['page'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('logstatus', 0) + + fileName = "/home/" + self.domain + "/logs/" + self.domain + ".error_log" + + ## get Logs + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " getErrorLogs --path " + fileName + " --page " + str(page) + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + final_json = json.dumps( + {'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) + return HttpResponse(final_json) + + ## get log ends here. + + final_json = json.dumps({'logstatus': 1, 'error_message': "None", "data": output}) + return HttpResponse(final_json) + + def getDataFromConfigFile(self, userID = None, data = None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('configstatus', 0) + + filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" + + command = 'sudo cat ' + filePath + configData = subprocess.check_output(shlex.split(command)) + + if len(configData) == 0: + status = {"configstatus": 0, "error_message": "Configuration file is currently empty!"} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + status = {"configstatus": 1, "configData": configData} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveConfigsToFile(self, userID = None, data = None): + + currentACL = ACLManager.loadedACL(userID) + + if currentACL['admin'] != 1: + return ACLManager.loadErrorJson('configstatus', 0) + + configData = data['configData'] + self.domain = data['virtualHost'] + + mailUtilities.checkHome() + + tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + vhost = open(tempPath, "w") + + vhost.write(configData) + + vhost.close() + + ## writing data temporary to file + + filePath = installUtilities.Server_root_path + "/conf/vhosts/" + self.domain + "/vhost.conf" + + ## save configuration data + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " saveVHostConfigs --path " + filePath + " --tempPath " + tempPath + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + status = {"configstatus": 1} + + final_json = json.dumps(status) + return HttpResponse(final_json) + else: + data_ret = {'configstatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## save configuration data ends + + def getRewriteRules(self, userID = None, data = None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('rewriteStatus', 0) + + try: + childDom = ChildDomains.objects.get(domain=self.domain) + filePath = childDom.path + '/.htaccess' + except: + filePath = "/home/" + self.domain + "/public_html/.htaccess" + + try: + rewriteRules = open(filePath, "r").read() + + if len(rewriteRules) == 0: + status = {"rewriteStatus": 1, "error_message": "Rules file is currently empty"} + final_json = json.dumps(status) + return HttpResponse(final_json) + + status = {"rewriteStatus": 1, "rewriteRules": rewriteRules} + + final_json = json.dumps(status) + return HttpResponse(final_json) + + except IOError: + status = {"rewriteStatus": 1, "error_message": "none", "rewriteRules": ""} + final_json = json.dumps(status) + return HttpResponse(final_json) + + def saveRewriteRules(self, userID = None, data = None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + rewriteRules = data['rewriteRules'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('rewriteStatus', 0) + + ## writing data temporary to file + + mailUtilities.checkHome() + tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + vhost = open(tempPath, "w") + vhost.write(rewriteRules) + vhost.close() + + ## writing data temporary to file + + try: + childDomain = ChildDomains.objects.get(domain=self.domain) + filePath = childDomain.path + '/.htaccess' + except: + filePath = "/home/" + self.domain + "/public_html/.htaccess" + + ## save configuration data + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " saveRewriteRules --virtualHostName " + self.domain + " --path " + filePath + " --tempPath " + tempPath + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + status = {"rewriteStatus": 1, 'error_message': output} + final_json = json.dumps(status) + return HttpResponse(final_json) + else: + data_ret = {'rewriteStatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def saveSSL(self, userID = None, data = None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['virtualHost'] + key = data['key'] + cert = data['cert'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('sslStatus', 0) + + mailUtilities.checkHome() + + ## writing data temporary to file + + + tempKeyPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + vhost = open(tempKeyPath, "w") + vhost.write(key) + vhost.close() + + tempCertPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + vhost = open(tempCertPath, "w") + vhost.write(cert) + vhost.close() + + ## writing data temporary to file + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " saveSSL --virtualHostName " + self.domain + " --tempKeyPath " + tempKeyPath + " --tempCertPath " + tempCertPath + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + data_ret = {'sslStatus': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + logging.CyberCPLogFileWriter.writeToFile( + output) + data_ret = {'sslStatus': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changePHP(self, userID = None, data = None): + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['childDomain'] + phpVersion = data['phpSelection'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('changePHP', 0) + + + confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + self.domain + completePathToConfigFile = confPath + "/vhost.conf" + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + pass + else: + data_ret = {'changePHP': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + data_ret = {'changePHP': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def getWebsiteCron(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getWebsiteCron', 0) + + + website = Websites.objects.get(domain=self.domain) + + if Websites.objects.filter(domain=self.domain).exists(): + pass + else: + dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + cronPath = "/var/spool/cron/" + website.externalApp + cmd = 'sudo test -e ' + cronPath + ' && echo Exists' + output = os.popen(cmd).read() + + if "Exists" not in output: + data_ret = {'getWebsiteCron': 1, "user": website.externalApp, "crons": {}} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + cronPath = "/var/spool/cron/" + website.externalApp + crons = [] + + try: + f = subprocess.check_output(["sudo", "cat", cronPath]) + print f + except subprocess.CalledProcessError as error: + dic = {'getWebsiteCron': 0, 'error_message': 'Unable to access Cron file'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + counter = 0 + for line in f.split("\n"): + if line: + split = line.split(" ", 5) + print line + print split + if len(split) == 6: + counter += 1 + crons.append({"line": counter, + "minute": split[0], + "hour": split[1], + "monthday": split[2], + "month": split[3], + "weekday": split[4], + "command": split[5]}) + + print json.dumps(crons) + + data_ret = {'getWebsiteCron': 1, "user": website.externalApp, "crons": crons} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + except BaseException, msg: + print msg + dic = {'getWebsiteCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def getCronbyLine(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + line = data['line'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getWebsiteCron', 0) + + + if Websites.objects.filter(domain=self.domain).exists(): + pass + else: + dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + line -= 1 + website = Websites.objects.get(domain=self.domain) + + cronPath = "/var/spool/cron/" + website.externalApp + crons = [] + + try: + f = subprocess.check_output(["sudo", "cat", cronPath]) + print f + except subprocess.CalledProcessError as error: + dic = {'getWebsiteCron': 0, 'error_message': 'Unable to access Cron file'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + f = f.split("\n") + cron = f[line] + + if not cron: + dic = {'getWebsiteCron': 0, 'error_message': 'Cron line empty'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + cron = cron.split(" ", 5) + if len(cron) != 6: + dic = {'getWebsiteCron': 0, 'error_message': 'Cron line incorrect'} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + data_ret = {"getWebsiteCron": 1, + "user": website.externalApp, + "cron": { + "minute": cron[0], + "hour": cron[1], + "monthday": cron[2], + "month": cron[3], + "weekday": cron[4], + "command": cron[5], + }, + "line": line} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + except BaseException, msg: + print msg + dic = {'getWebsiteCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def saveCronChanges(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + line = data['line'] + + minute = data['minute'] + hour = data['hour'] + monthday = data['monthday'] + month = data['month'] + weekday = data['weekday'] + command = data['command'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('getWebsiteCron', 0) + + website = Websites.objects.get(domain=self.domain) + + cronPath = "/var/spool/cron/" + website.externalApp + tempPath = "/home/cyberpanel/" + website.externalApp + str(randint(10000, 99999)) + ".cron.tmp" + + finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) + + o = subprocess.call(['sudo', 'cp', cronPath, tempPath]) + if o is not 0: + data_ret = {'addNewCron': 0, 'error_message': 'Unable to copy to temporary files'} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + # Confirming that directory is read/writable + o = subprocess.call(['sudo', 'chown', 'cyberpanel:cyberpanel', tempPath]) + if o is not 0: + data_ret = {'addNewCron': 0, 'error_message': 'Error Changing Permissions'} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + with open(tempPath, 'r') as file: + data = file.readlines() + + data[line] = finalCron + '\n' + + with open(tempPath, 'w') as file: + file.writelines(data) + + output = subprocess.call(["sudo", "/usr/bin/crontab", "-u", website.externalApp, tempPath]) + + os.remove(tempPath) + if output != 0: + data_ret = {'addNewCron': 0, 'error_message': 'Incorrect Syntax cannot be accepted.'} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + data_ret = {"getWebsiteCron": 1, + "user": website.externalApp, + "cron": finalCron, + "line": line} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + except BaseException, msg: + print msg + dic = {'getWebsiteCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def remCronbyLine(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + line = data['line'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('addNewCron', 0) + + line -= 1 + website = Websites.objects.get(domain=self.domain) + + cronPath = "/var/spool/cron/" + website.externalApp + cmd = 'sudo test -e ' + cronPath + ' && echo Exists' + output = os.popen(cmd).read() + + if "Exists" not in output: + data_ret = {'remCronbyLine': 0, 'error_message': 'No Cron exists for this user'} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + cronPath = "/var/spool/cron/" + website.externalApp + tempPath = "/home/cyberpanel/" + website.externalApp + str(randint(10000, 99999)) + ".cron.tmp" + + o = subprocess.call(['sudo', 'cp', cronPath, tempPath]) + if o is not 0: + data_ret = {'addNewCron': 0, 'error_message': 'Unable to copy to temporary files'} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + # Confirming that directory is read/writable + o = subprocess.call(['sudo', 'chown', 'cyberpanel:cyberpanel', tempPath]) + if o is not 0: + data_ret = {'addNewCron': 0, 'error_message': 'Error Changing Permissions'} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + with open(tempPath, 'r') as file: + data = file.readlines() + + removedLine = data.pop(line) + + with open(tempPath, 'w') as file: + file.writelines(data) + + output = subprocess.call(["sudo", "/usr/bin/crontab", "-u", website.externalApp, tempPath]) + + os.remove(tempPath) + if output != 0: + data_ret = {'addNewCron': 0, 'error_message': 'Incorrect Syntax cannot be accepted'} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + data_ret = {"remCronbyLine": 1, + "user": website.externalApp, + "removeLine": removedLine, + "line": line} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + except BaseException, msg: + print msg + dic = {'remCronbyLine': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def addNewCron(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + minute = data['minute'] + hour = data['hour'] + monthday = data['monthday'] + month = data['month'] + weekday = data['weekday'] + command = data['command'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('addNewCron', 0) + + website = Websites.objects.get(domain=self.domain) + + cronPath = "/var/spool/cron/" + website.externalApp + cmd = 'sudo test -e ' + cronPath + ' && echo Exists' + output = os.popen(cmd).read() + + if "Exists" not in output: + echo = subprocess.Popen(('echo'), stdout=subprocess.PIPE) + output = subprocess.call(('sudo', 'crontab', '-u', website.externalApp, '-'), stdin=echo.stdout) + echo.wait() + echo.stdout.close() + # Confirmation + o = subprocess.call(["sudo", "cp", "/dev/null", cronPath]) + + cronPath = "/var/spool/cron/" + website.externalApp + tempPath = "/home/cyberpanel/" + website.externalApp + str(randint(10000, 99999)) + ".cron.tmp" + + finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) + + o = subprocess.call(['sudo', 'cp', cronPath, tempPath]) + if o is not 0: + data_ret = {'addNewCron': 0, 'error_message': 'Unable to copy to temporary files'} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + # Confirming that directory is read/writable + o = subprocess.call(['sudo', 'chown', 'cyberpanel:cyberpanel', tempPath]) + if o is not 0: + data_ret = {'addNewCron': 0, 'error_message': 'Error Changing Permissions'} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + with open(tempPath, "a") as file: + file.write(finalCron + "\n") + + output = subprocess.call(["sudo", "/usr/bin/crontab", "-u", website.externalApp, tempPath]) + + os.remove(tempPath) + if output != 0: + data_ret = {'addNewCron': 0, 'error_message': 'Incorrect Syntax cannot be accepted'} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + + data_ret = {"addNewCron": 1, + "user": website.externalApp, + "cron": finalCron} + final_json = json.dumps(data_ret) + return HttpResponse(final_json) + except BaseException, msg: + print msg + dic = {'addNewCron': 0, 'error_message': str(msg)} + json_data = json.dumps(dic) + return HttpResponse(json_data) + + def submitAliasCreation(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + aliasDomain = data['aliasDomain'] + ssl = data['ssl'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('createAliasStatus', 0) + + sslpath = "/home/" + self.domain + "/public_html" + + ## Create Configurations + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " createAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --ssl " + str( + ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ' --websiteOwner ' + admin.userName + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + pass + else: + data_ret = {'createAliasStatus': 0, 'error_message': output, "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Create Configurations ends here + + data_ret = {'createAliasStatus': 1, 'error_message': "None", "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + + except BaseException, msg: + data_ret = {'createAliasStatus': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def issueAliasSSL(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + aliasDomain = data['aliasDomain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('sslStatus', 0) + + + sslpath = "/home/" + self.domain + "/public_html" + + ## Create Configurations + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " issueAliasSSL --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + " --sslPath " + sslpath + " --administratorEmail " + admin.email + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + data_ret = {'sslStatus': 1, 'error_message': "None", "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'sslStatus': 0, 'error_message': output, "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'sslStatus': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def delateAlias(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['masterDomain'] + aliasDomain = data['aliasDomain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('deleteAlias', 0) + + ## Create Configurations + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " deleteAlias --masterDomain " + self.domain + " --aliasDomain " + aliasDomain + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + data_ret = {'deleteAlias': 1, 'error_message': "None", "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + data_ret = {'deleteAlias': 0, 'error_message': output, "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException, msg: + data_ret = {'deleteAlias': 0, 'error_message': str(msg), "existsStatus": 0} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changeOpenBasedir(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domainName'] + openBasedirValue = data['openBasedirValue'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('changeOpenBasedir', 0) + + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " changeOpenBasedir --virtualHostName '" + self.domain + "' --openBasedirValue " + openBasedirValue + + output = subprocess.check_output(shlex.split(execPath)) + + if output.find("1,None") > -1: + pass + else: + data_ret = {'changeOpenBasedir': 0, 'error_message': output} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + data_ret = {'changeOpenBasedir': 1, 'error_message': "None"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'changeOpenBasedir': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def wordpressInstall(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + return render(request, 'websiteFunctions/installWordPress.html', {'domainName': self.domain}) + + except BaseException, msg: + return HttpResponse(str(msg)) + + def installWordpress(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['blogTitle'] = data['blogTitle'] + extraArgs['adminUser'] = data['adminUser'] + extraArgs['adminPassword'] = data['adminPassword'] + extraArgs['adminEmail'] = data['adminEmail'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + background = ApplicationInstaller('wordpress', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException, msg: + data_ret = {'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installWordpressStatus(self, userID = None, data = None): + try: + statusFile = data['statusFile'] + + statusData = open(statusFile, 'r').readlines() + + lastLine = statusData[-1] + + if lastLine.find('[200]') > -1: + data_ret = {'abort': 1, 'installStatus': 1, 'installationProgress': "100", + 'currentStatus': 'Successfully Installed.'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + elif lastLine.find('[404]') > -1: + data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", + 'error_message': lastLine} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + else: + progress = lastLine.split(',') + currentStatus = progress[0] + installationProgress = progress[1] + data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': installationProgress, + 'currentStatus': currentStatus} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def joomlaInstall(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + return render(request, 'websiteFunctions/installJoomla.html', {'domainName': self.domain}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def installJoomla(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + domainName = data['domain'] + home = data['home'] + + sitename = data['sitename'] + username = data['username'] + password = data['password'] + prefix = data['prefix'] + + mailUtilities.checkHome() + + tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Setting up paths,0') + statusFile.close() + + finalPath = "" + + admin = Administrator.objects.get(pk=userID) + + ## DB Creation + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Creating database..,10') + statusFile.close() + + dbName = randomPassword.generate_pass() + dbUser = dbName + dbPassword = randomPassword.generate_pass() + + if Databases.objects.filter(dbName=dbName).exists() or Databases.objects.filter( + dbUser=dbUser).exists(): + data_ret = {'installStatus': 0, + 'error_message': "0,This database or user is already taken."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + result = mysqlUtilities.createDatabase(dbName, dbUser, dbPassword) + + if result == 1: + pass + else: + data_ret = {'installStatus': 0, + 'error_message': "0,Not able to create database."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## + + + + try: + website = ChildDomains.objects.get(domain=domainName) + externalApp = website.master.externalApp + + if website.master.package.dataBases > website.master.databases_set.all().count(): + pass + else: + data_ret = {'installStatus': 0, + 'error_message': "0,Maximum database limit reached for this website."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if home == '0': + path = data['path'] + finalPath = website.path.rstrip('/') + "/" + path + "/" + else: + finalPath = website.path + "/" + + db = Databases(website=website.master, dbName=dbName, dbUser=dbUser) + db.save() + + except: + website = Websites.objects.get(domain=domainName) + externalApp = website.externalApp + + if website.package.dataBases > website.databases_set.all().count(): + pass + else: + data_ret = {'installStatus': 0, + 'error_message': "0,Maximum database limit reached for this website."} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + if home == '0': + path = data['path'] + finalPath = "/home/" + domainName + "/public_html/" + path + "/" + else: + finalPath = "/home/" + domainName + "/public_html/" + + db = Databases(website=website, dbName=dbName, dbUser=dbUser) + db.save() + + if finalPath.find("..") > -1: + data_ret = {'installStatus': 0, + 'error_message': "Specified path must be inside virtual host home!"} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Installation + salt = randomPassword.generate_pass(32) + # return salt + password_hash = hashlib.md5(password + salt).hexdigest() + password = password_hash + ":" + salt + + statusFile = open(tempStatusPath, 'w') + statusFile.writelines('Downloading Joomla Core..,20') + statusFile.close() + + execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" + + execPath = execPath + " installJoomla --virtualHostName " + domainName + \ + " --virtualHostUser " + externalApp + " --path " + finalPath + " --dbName " + dbName + \ + " --dbUser " + dbUser + " --dbPassword " + dbPassword + " --username " + username + \ + " --password " + password + " --prefix " + prefix + " --sitename '" + sitename + "'" \ + + " --tempStatusPath " + tempStatusPath + + # return execPath + + + output = subprocess.Popen(shlex.split(execPath)) + + data_ret = {"installStatus": 1, 'tempStatusPath': tempStatusPath} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + + ## Installation ends + + except BaseException, msg: + data_ret = {'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def setupGit(self, request = None, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + path = '/home/cyberpanel/' + self.domain + '.git' + + if os.path.exists(path): + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + + webhookURL = 'https://' + ipAddress + ':8090/websites/' + self.domain + '/gitNotify' + + return render(request, 'websiteFunctions/setupGit.html', + {'domainName': self.domain, 'installed': 1, 'webhookURL': webhookURL}) + else: + command = 'sudo cat /root/.ssh/cyberpanel.pub' + deploymentKey = subprocess.check_output(shlex.split(command)).strip('\n') + + return render(request, 'websiteFunctions/setupGit.html', + {'domainName': self.domain, 'deploymentKey': deploymentKey, 'installed': 0}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def setupGitRepo(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['username'] = data['username'] + extraArgs['reponame'] = data['reponame'] + extraArgs['branch'] = data['branch'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + extraArgs['defaultProvider'] = data['defaultProvider'] + + background = ApplicationInstaller('git', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException, msg: + data_ret = {'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def gitNotify(self, userID = None, data = None): + try: + + extraArgs = {} + extraArgs['domain'] = self.domain + + background = ApplicationInstaller('pull', extraArgs) + background.start() + + data_ret = {'pulled': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + except BaseException, msg: + data_ret = {'pulled': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def detachRepo(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['domainName'] = data['domain'] + extraArgs['admin'] = admin + + background = ApplicationInstaller('detach', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException, msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def changeBranch(self, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson() + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['domainName'] = data['domain'] + extraArgs['githubBranch'] = data['githubBranch'] + extraArgs['admin'] = admin + + background = ApplicationInstaller('changeBranch', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'status': 1, 'error_message': 'None'} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + + except BaseException, msg: + data_ret = {'status': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def installPrestaShop(self, request = None, userID = None, data = None): + try: + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadError() + + return render(request, 'websiteFunctions/installPrestaShop.html', {'domainName': self.domain}) + except BaseException, msg: + return HttpResponse(str(msg)) + + def prestaShopInstall(self, userID = None, data = None): + try: + + currentACL = ACLManager.loadedACL(userID) + admin = Administrator.objects.get(pk=userID) + + self.domain = data['domain'] + + if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1: + pass + else: + return ACLManager.loadErrorJson('installStatus', 0) + + mailUtilities.checkHome() + + extraArgs = {} + extraArgs['admin'] = admin + extraArgs['domainName'] = data['domain'] + extraArgs['home'] = data['home'] + extraArgs['shopName'] = data['shopName'] + extraArgs['firstName'] = data['firstName'] + extraArgs['lastName'] = data['lastName'] + extraArgs['databasePrefix'] = data['databasePrefix'] + extraArgs['email'] = data['email'] + extraArgs['password'] = data['password'] + extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) + + if data['home'] == '0': + extraArgs['path'] = data['path'] + + background = ApplicationInstaller('prestashop', extraArgs) + background.start() + + time.sleep(2) + + data_ret = {'installStatus': 1, 'error_message': 'None', + 'tempStatusPath': extraArgs['tempStatusPath']} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + ## Installation ends + + except BaseException, msg: + data_ret = {'installStatus': 0, 'error_message': str(msg)} + json_data = json.dumps(data_ret) + return HttpResponse(json_data) + + def findWebsitesJson(self, currentACL, userID, pageNumber): + finalPageNumber = ((pageNumber * 10)) - 10 + endPageNumber = finalPageNumber + 10 + websites = ACLManager.findWebsiteObjects(currentACL, userID)[finalPageNumber:endPageNumber] + + json_data = "[" + checker = 0 + + try: + ipFile = "/etc/cyberpanel/machineIP" + f = open(ipFile) + ipData = f.read() + ipAddress = ipData.split('\n', 1)[0] + except BaseException, msg: + logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) + ipAddress = "192.168.100.1" + + for items in websites: + if items.state == 0: + state = "Suspended" + else: + state = "Active" + dic = {'domain': items.domain, 'adminEmail': items.adminEmail, 'ipAddress': ipAddress, + 'admin': items.admin.userName, 'package': items.package.packageName, 'state': state} + + if checker == 0: + json_data = json_data + json.dumps(dic) + checker = 1 + else: + json_data = json_data + ',' + json.dumps(dic) + + json_data = json_data + ']' + + return json_data + + + + + + + + diff --git a/tuning/views.py b/tuning/views.py index b5339ed74..382eba79a 100644 --- a/tuning/views.py +++ b/tuning/views.py @@ -6,9 +6,7 @@ from django.http import HttpResponse import json import plogical.CyberCPLogFileWriter as logging from plogical.tuning import tuning -from loginSystem.models import Administrator from loginSystem.views import loadLoginPage -from websiteFunctions.models import Websites,ChildDomains from plogical.virtualHostUtilities import virtualHostUtilities import subprocess import shlex diff --git a/websiteFunctions/views.py b/websiteFunctions/views.py index e81e2b946..b0e71156c 100644 --- a/websiteFunctions/views.py +++ b/websiteFunctions/views.py @@ -4,29 +4,10 @@ from __future__ import unicode_literals from django.shortcuts import render,redirect from django.http import HttpResponse from loginSystem.models import Administrator -from packages.models import Package from loginSystem.views import loadLoginPage import plogical.CyberCPLogFileWriter as logging -from .models import Websites,ChildDomains import json -from math import ceil -from plogical.mysqlUtilities import mysqlUtilities -import os -from plogical.virtualHostUtilities import virtualHostUtilities -from plogical.installUtilities import installUtilities -import plogical.randomPassword as randomPassword -import subprocess -import shlex -from databases.models import Databases -import re -from random import randint -import hashlib -from plogical.mailUtilities import mailUtilities -from plogical.applicationInstaller import ApplicationInstaller -import time -from plogical.acl import ACLManager -from plogical.alias import AliasManager -# Create your views here. +from plogical.website import WebsiteManager def loadWebsitesHome(request): try: @@ -39,48 +20,18 @@ def loadWebsitesHome(request): def createWebsite(request): try: userID = request.session['userID'] - try: - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - elif currentACL['createWebsite'] == 1: - pass - else: - return ACLManager.loadError() - - adminNames = ACLManager.loadAllUsers(userID) - packagesName = ACLManager.loadPackages(userID, currentACL) - - Data = {'packageList': packagesName, "owernList":adminNames} - return render(request, 'websiteFunctions/createWebsite.html', Data) - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse(str(msg)) - + wm = WebsiteManager() + return wm.createWebsite(request, userID) except KeyError: return redirect(loadLoginPage) def modifyWebsite(request): try: userID = request.session['userID'] - try: - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - elif currentACL['modifyWebsite'] == 1: - pass - else: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(request, 'websiteFunctions/modifyWebsite.html', {'websiteList':websitesName}) - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse(str(msg)) + wm = WebsiteManager() + return wm.modifyWebsite(request, userID) + except BaseException, msg: + return HttpResponse(str(msg)) except KeyError: return redirect(loadLoginPage) @@ -88,1652 +39,278 @@ def modifyWebsite(request): def deleteWebsite(request): try: userID = request.session['userID'] - try: - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - elif currentACL['deleteWebsite'] == 1: - pass - else: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(request, 'websiteFunctions/deleteWebsite.html', {'websiteList' : websitesName}) - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse(str(msg)) - + wm = WebsiteManager() + return wm.deleteWebsite(request, userID) except KeyError: return redirect(loadLoginPage) def siteState(request): try: userID = request.session['userID'] - try: - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - elif currentACL['suspendWebsite'] == 1: - pass - else: - return ACLManager.loadError() - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(request, 'websiteFunctions/suspendWebsite.html', {'websiteList':websitesName}) - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse(str(msg)) + wm = WebsiteManager() + return wm.suspendWebsite(request, userID) + except KeyError: + return redirect(loadLoginPage) +def listWebsites(request): + try: + userID = request.session['userID'] + wm = WebsiteManager() + return wm.listWebsites(request, userID) except KeyError: return redirect(loadLoginPage) def submitWebsiteCreation(request): try: userID = request.session['userID'] - - currentACL = ACLManager.loadedACL(userID) - if currentACL['admin'] == 1: - pass - elif currentACL['createWebsite'] == 1: - pass - else: - return ACLManager.loadErrorJson('createWebSiteStatus', 0) - - if request.method == 'POST': - - data = json.loads(request.body) - - domain = data['domainName'] - adminEmail = data['adminEmail'] - phpSelection = data['phpSelection'] - packageName = data['package'] - websiteOwner = data['websiteOwner'] - externalApp = "".join(re.findall("[a-zA-Z]+", domain))[:7] - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - - ## Create Configurations - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " createVirtualHost --virtualHostName " + domain + \ - " --administratorEmail " + adminEmail + " --phpVersion '" + phpSelection + \ - "' --virtualHostUser " + externalApp + " --ssl " + str(data['ssl']) + " --dkimCheck " \ - + str(data['dkimCheck']) + " --openBasedir " + str(data['openBasedir']) + \ - ' --websiteOwner ' + websiteOwner + ' --package ' + packageName + ' --tempStatusPath ' + tempStatusPath - - subprocess.Popen(shlex.split(execPath)) - time.sleep(2) - - data_ret = {'createWebSiteStatus': 1, 'error_message': "None", 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException, msg: - data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + wm = WebsiteManager() + return wm.submitWebsiteCreation(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def submitDomainCreation(request): try: - if request.method == 'POST': - - data = json.loads(request.body) - masterDomain = data['masterDomain'] - domain = data['domainName'] - phpSelection = data['phpSelection'] - path = data['path'] - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if currentACL['admin'] != 1: - data['openBasedir'] = 1 - - if len(path) > 0: - path = path.lstrip("/") - path = "/home/" + masterDomain + "/public_html/" + path - else: - path = "/home/" + masterDomain + "/public_html/" + domain - - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " createDomain --masterDomain " + masterDomain + " --virtualHostName " + domain + \ - " --phpVersion '" + phpSelection + "' --ssl " + str(data['ssl']) + " --dkimCheck " + str(data['dkimCheck']) \ - + " --openBasedir " + str(data['openBasedir']) + ' --path ' + path + ' --websiteOwner ' \ - + admin.userName + ' --tempStatusPath ' + tempStatusPath - - subprocess.Popen(shlex.split(execPath)) - time.sleep(2) - - data_ret = {'createWebSiteStatus': 1, 'error_message': "None", 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'createWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + userID = request.session['userID'] + wm = WebsiteManager() + return wm.submitDomainCreation(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def fetchDomains(request): try: userID = request.session['userID'] - try: - if request.method == 'POST': - data = json.loads(request.body) - masterDomain = data['masterDomain'] - - master = Websites.objects.get(domain=masterDomain) - - childDomains = master.childdomains_set.all() - - json_data = "[" - checker = 0 - - for items in childDomains: - dic = { - 'childDomain': items.domain, - 'path': items.path, - 'childLunch': '/websites/' + masterDomain + '/' + items.domain - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - final_json = json.dumps({'fetchStatus': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - - except BaseException,msg: - final_dic = {'fetchStatus': 0, 'error_message': str(msg)} - final_json = json.dumps(final_dic) - - return HttpResponse(final_json) - except KeyError: - final_dic = {'fetchStatus': 0, 'error_message': "Not Logged In, please refresh the page or login again."} - final_json = json.dumps(final_dic) - return HttpResponse(final_json) - -def listWebsites(request): - try: - userID = request.session['userID'] - try: - - currentACL = ACLManager.loadedACL(userID) - websites = ACLManager.findAllSites(currentACL, userID) - - pages = float(len(websites)) / float(10) - pagination = [] - - if pages <= 1.0: - pages = 1 - pagination.append('
  • ') - else: - pages = ceil(pages) - finalPages = int(pages) + 1 - - for i in range(1, finalPages): - pagination.append('
  • ' + str(i) + '
  • ') - - - return render(request,'websiteFunctions/listWebsites.html',{"pagination":pagination}) - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse("See CyberCP main log file.") - + wm = WebsiteManager() + return wm.fetchDomains(userID, json.loads(request.body)) except KeyError: return redirect(loadLoginPage) def getFurtherAccounts(request): try: userID = request.session['userID'] - try: - currentACL = ACLManager.loadedACL(userID) - - if request.method == 'POST': - try: - data = json.loads(request.body) - status = data['page'] - pageNumber = int(status) - - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + ' [getFurtherAccounts]') - - finalPageNumber = ((pageNumber * 10)) - 10 - endPageNumber = finalPageNumber + 10 - websites = ACLManager.findWebsiteObjects(currentACL, userID)[finalPageNumber:endPageNumber] - - json_data = "[" - checker = 0 - - try: - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile("Failed to read machine IP, error:" + str(msg)) - ipAddress = "192.168.100.1" - - for items in websites: - if items.state == 0: - state = "Suspended" - else: - state = "Active" - dic = {'domain': items.domain, 'adminEmail': items.adminEmail,'ipAddress':ipAddress,'admin': items.admin.userName,'package': items.package.packageName,'state':state} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data +',' + json.dumps(dic) - - json_data = json_data + ']' - final_dic = {'listWebSiteStatus': 1, 'error_message': "None", "data": json_data} - final_json = json.dumps(final_dic) - - - return HttpResponse(final_json) - - except BaseException,msg: - dic = {'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - - except KeyError,msg: - dic = {'listWebSiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) + wm = WebsiteManager() + return wm.getFurtherAccounts(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def submitWebsiteDeletion(request): try: + userID = request.session['userID'] - try: - if request.method == 'POST': - data = json.loads(request.body) - websiteName = data['websiteName'] + wm = WebsiteManager() + return wm.submitWebsiteDeletion(userID, json.loads(request.body)) - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - elif currentACL['deleteWebsite'] == 1: - pass - else: - return ACLManager.loadErrorJson('websiteDeleteStatus', 0) - - - numberOfWebsites = str(Websites.objects.count() + ChildDomains.objects.count()) - - ## Deleting master domain - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " deleteVirtualHostConfigurations --virtualHostName " + websiteName + \ - " --numberOfSites " + numberOfWebsites - - subprocess.check_output(shlex.split(execPath)) - - data_ret = {'websiteDeleteStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException,msg: - data_ret = {'websiteDeleteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except KeyError,msg: - data_ret = {'websiteDeleteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + except KeyError: + return redirect(loadLoginPage) def submitDomainDeletion(request): try: - val = request.session['userID'] - try: - if request.method == 'POST': - data = json.loads(request.body) - websiteName = data['websiteName'] - childDomain = ChildDomains.objects.get(domain=websiteName) - admin = Administrator.objects.get(pk=val) + userID = request.session['userID'] + wm = WebsiteManager() + return wm.submitDomainDeletion(userID, json.loads(request.body)) - if childDomain.master.admin == admin: - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " deleteDomain --virtualHostName " + websiteName - - subprocess.check_output(shlex.split(execPath)) - - data_ret = {'websiteDeleteStatus': 1,'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - data_ret = {'websiteDeleteStatus': 0, 'error_message': "You can not delete this child domain, as master domain is not owned by logged in user."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException,msg: - data_ret = {'websiteDeleteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except KeyError,msg: - data_ret = {'websiteDeleteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + except KeyError: + return redirect(loadLoginPage) def submitWebsiteStatus(request): try: + userID = request.session['userID'] - try: - if request.method == 'POST': - data = json.loads(request.body) - websiteName = data['websiteName'] - state = data['state'] + wm = WebsiteManager() + return wm.submitWebsiteStatus(userID, json.loads(request.body)) - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - elif currentACL['suspendWebsite'] == 1: - pass - else: - return ACLManager.loadErrorJson('websiteStatus', 0) - - website = Websites.objects.get(domain=websiteName) - - if state == "Suspend": - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName - command = "sudo mv " + confPath + " " + confPath + "-suspended" - subprocess.call(shlex.split(command)) - installUtilities.reStartLiteSpeed() - website.state = 0 - else: - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + websiteName - - command = "sudo mv " + confPath + "-suspended" + " " + confPath - subprocess.call(shlex.split(command)) - - command = "chown -R " + "lsadm" + ":" + "lsadm" + " " + confPath - cmd = shlex.split(command) - subprocess.call(cmd) - - installUtilities.reStartLiteSpeed() - website.state = 1 - - website.save() - - data_ret = {'websiteStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException,msg: - - - data_ret = {'websiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - except KeyError,msg: - data_ret = {'websiteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + except KeyError: + return redirect(loadLoginPage) def submitWebsiteModify(request): try: + userID = request.session['userID'] - try: + wm = WebsiteManager() + return wm.submitWebsiteModify(userID, json.loads(request.body)) - if request.method == 'POST': - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - elif currentACL['modifyWebsite'] == 1: - pass - else: - return ACLManager.loadErrorJson('modifyStatus', 0) - - packs = ACLManager.loadPackages(userID, currentACL) - admins = ACLManager.loadAllUsers(userID) - - ## Get packs name - - json_data = "[" - checker = 0 - - - for items in packs: - dic = {"pack":items} - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - - json_data = json_data + ']' - - ### Get admin names - - admin_data = "[" - checker = 0 - - for items in admins: - dic = {"adminNames": items} - - if checker == 0: - admin_data = admin_data + json.dumps(dic) - checker = 1 - else: - admin_data = admin_data + ',' + json.dumps(dic) - - admin_data = admin_data + ']' - - - data = json.loads(request.body) - websiteToBeModified = data['websiteToBeModified'] - - modifyWeb = Websites.objects.get(domain=websiteToBeModified) - - - email = modifyWeb.adminEmail - currentPack = modifyWeb.package.packageName - owner = modifyWeb.admin.userName - - data_ret = {'modifyStatus': 1,'error_message': "None","adminEmail":email, - "packages":json_data,"current_pack":currentPack,"adminNames":admin_data,'currentAdmin':owner} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException,msg: - dic = {'modifyStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - except KeyError,msg: - data_ret = {'modifyStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + except KeyError: + return redirect(loadLoginPage) def saveWebsiteChanges(request): try: + userID = request.session['userID'] - try: - if request.method == 'POST': + wm = WebsiteManager() + return wm.saveWebsiteChanges(userID, json.loads(request.body)) - data = json.loads(request.body) - domain = data['domain'] - package = data['packForWeb'] - email = data['email'] - phpVersion = data['phpVersion'] - newUser = data['admin'] - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] == 1: - pass - elif currentACL['modifyWebsite'] == 1: - pass - else: - return ACLManager.loadErrorJson('saveStatus', 0) - - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + domain - completePathToConfigFile = confPath + "/vhost.conf" - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'saveStatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## php changes ends - - newOwner = Administrator.objects.get(userName=newUser) - - modifyWeb = Websites.objects.get(domain=domain) - webpack = Package.objects.get(packageName=package) - - modifyWeb.package = webpack - modifyWeb.adminEmail = email - modifyWeb.phpSelection = phpVersion - modifyWeb.admin = newOwner - - - modifyWeb.save() - - data_ret = {'saveStatus': 1,'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException,msg: - data_ret = {'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except KeyError,msg: - data_ret = {'saveStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + except KeyError: + return redirect(loadLoginPage) def domain(request, domain): try: + userID = request.session['userID'] + wm = WebsiteManager(domain) + return wm.loadDomainHome(request, userID) - admin = Administrator.objects.get(pk=userID) - - if Websites.objects.filter(domain=domain).exists(): - currentACL = ACLManager.loadedACL(userID) - website = Websites.objects.get(domain=domain) - - Data = {} - - Data['ftpTotal'] = website.package.ftpAccounts - Data['ftpUsed'] = website.users_set.all().count() - - Data['databasesUsed'] = website.databases_set.all().count() - Data['databasesTotal'] = website.package.dataBases - - Data['domain'] = domain - - diskUsageDetails = virtualHostUtilities.getDiskUsage("/home/" + domain, website.package.diskSpace) - - ## bw usage calculation - - try: - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " findDomainBW --virtualHostName " + domain + " --bandwidth " + str( - website.package.bandwidth) - - output = subprocess.check_output(shlex.split(execPath)) - bwData = output.split(",") - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - bwData = [0, 0] - - ## bw usage calculations - - Data['bwInMBTotal'] = website.package.bandwidth - Data['bwInMB'] = bwData[0] - Data['bwUsage'] = bwData[1] - - if diskUsageDetails != None: - if diskUsageDetails[1] > 100: - diskUsageDetails[1] = 100 - - Data['diskUsage'] = diskUsageDetails[1] - Data['diskInMB'] = diskUsageDetails[0] - Data['diskInMBTotal'] = website.package.diskSpace - else: - Data['diskUsage'] = 0 - Data['diskInMB'] = 0 - Data['diskInMBTotal'] = website.package.diskSpace - - return render(request, 'websiteFunctions/website.html', Data) - - else: - return render(request, 'websiteFunctions/website.html', {"error":1,"domain": "This domain does not exists."}) except KeyError: return redirect(loadLoginPage) def launchChild(request, domain, childDomain): try: userID = request.session['userID'] - admin = Administrator.objects.get(pk=userID) - - if ChildDomains.objects.filter(domain=childDomain).exists(): - currentACL = ACLManager.loadedACL(userID) - website = Websites.objects.get(domain=domain) - - Data = {} - - Data['ftpTotal'] = website.package.ftpAccounts - Data['ftpUsed'] = website.users_set.all().count() - - Data['databasesUsed'] = website.databases_set.all().count() - Data['databasesTotal'] = website.package.dataBases - - Data['domain'] = domain - Data['childDomain'] = childDomain - - diskUsageDetails = virtualHostUtilities.getDiskUsage("/home/" + domain, website.package.diskSpace) - - ## bw usage calculation - - try: - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - execPath = execPath + " findDomainBW --virtualHostName " + domain + " --bandwidth " + str( - website.package.bandwidth) - - output = subprocess.check_output(shlex.split(execPath)) - bwData = output.split(",") - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - bwData = [0, 0] - - ## bw usage calculations - - Data['bwInMBTotal'] = website.package.bandwidth - Data['bwInMB'] = bwData[0] - Data['bwUsage'] = bwData[1] - - if diskUsageDetails != None: - if diskUsageDetails[1] > 100: - diskUsageDetails[1] = 100 - - Data['diskUsage'] = diskUsageDetails[1] - Data['diskInMB'] = diskUsageDetails[0] - Data['diskInMBTotal'] = website.package.diskSpace - else: - Data['diskUsage'] = 0 - Data['diskInMB'] = 0 - Data['diskInMBTotal'] = website.package.diskSpace - - return render(request, 'websiteFunctions/launchChild.html', Data) - else: - return render(request, 'websiteFunctions/launchChild.html', {"error":1,"domain": "This child domain does not exists"}) + wm = WebsiteManager(domain, childDomain) + return wm.launchChild(request, userID) except KeyError: return redirect(loadLoginPage) def getDataFromLogFile(request): try: userID = request.session['userID'] - data = json.loads(request.body) - logType = data['logType'] - virtualHost = data['virtualHost'] - page = data['page'] - - - if logType == 1: - fileName = "/home/" + virtualHost + "/logs/" + virtualHost + ".access_log" - else: - fileName = "/home/" + virtualHost + "/logs/" + virtualHost + ".error_log" - - ## get Logs - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " getAccessLogs --path " + fileName + " --page " + str(page) - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - final_json = json.dumps( - {'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) - return HttpResponse(final_json) - - ## get log ends here. - - - data = output.split("\n") - - json_data = "[" - checker = 0 - - for items in reversed(data): - if len(items) > 10: - logData = items.split(" ") - domain = logData[0].strip('"') - ipAddress = logData[1] - time = (logData[4]).strip("[").strip("]") - resource = logData[7].strip('"') - size = logData[10].replace('"', '') - - dic = {'domain': domain, - 'ipAddress': ipAddress, - 'time': time, - 'resource': resource, - 'size': size, - } - - if checker == 0: - json_data = json_data + json.dumps(dic) - checker = 1 - else: - json_data = json_data + ',' + json.dumps(dic) - - json_data = json_data + ']' - final_json = json.dumps({'logstatus': 1, 'error_message': "None", "data": json_data}) - return HttpResponse(final_json) - - ## - - except KeyError,msg: - data_ret = {'logstatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + wm = WebsiteManager() + return wm.getDataFromLogFile(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def fetchErrorLogs(request): try: userID = request.session['userID'] - - data = json.loads(request.body) - virtualHost = data['virtualHost'] - page = data['page'] - - fileName = "/home/" + virtualHost + "/logs/" + virtualHost + ".error_log" - - ## get Logs - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " getErrorLogs --path " + fileName + " --page " + str(page) - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - final_json = json.dumps( - {'logstatus': 0, 'error_message': "Not able to fetch logs, see CyberPanel main log file!"}) - return HttpResponse(final_json) - - ## get log ends here. - - final_json = json.dumps({'logstatus': 1, 'error_message': "None", "data": output}) - return HttpResponse(final_json) - - except BaseException,msg: - final_json = json.dumps({'logstatus': 0, 'error_message': str(msg)}) - return HttpResponse(final_json) + wm = WebsiteManager() + return wm.fetchErrorLogs(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def getDataFromConfigFile(request): try: userID = request.session['userID'] - if request.method == 'POST': - try: - data = json.loads(request.body) - virtualHost = data['virtualHost'] - - filePath = installUtilities.Server_root_path + "/conf/vhosts/" + virtualHost + "/vhost.conf" - - command = 'sudo cat ' + filePath - configData = subprocess.check_output(shlex.split(command)) - - if len(configData) == 0: - status = {"configstatus": 0, "error_message": "Configuration file is currently empty!"} - - final_json = json.dumps(status) - return HttpResponse(final_json) - - status = {"configstatus": 1, "configData": configData} - final_json = json.dumps(status) - return HttpResponse(final_json) - - except BaseException, msg: - data_ret = {'configstatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except KeyError, msg: - status = {"configstatus":0,"error":"Could not fetch data from log file, please see CyberCP main log file through command line."} - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[getDataFromConfigFile]") - return HttpResponse("Not Logged in as admin") + wm = WebsiteManager() + return wm.getDataFromConfigFile(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def saveConfigsToFile(request): try: userID = request.session['userID'] - - if request.method == 'POST': - try: - data = json.loads(request.body) - virtualHost = data['virtualHost'] - - currentACL = ACLManager.loadedACL(userID) - - if currentACL['admin'] != 1: - return ACLManager.loadErrorJson('configstatus', 0) - - - ## writing data temporary to file - - mailUtilities.checkHome() - - tempPath = "/home/cyberpanel/"+str(randint(1000, 9999)) - - vhost = open(tempPath, "w") - - vhost.write(data['configData']) - - vhost.close() - - ## writing data temporary to file - - filePath = installUtilities.Server_root_path + "/conf/vhosts/"+virtualHost+"/vhost.conf" - - ## save configuration data - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " saveVHostConfigs --path " + filePath + " --tempPath " + tempPath - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - status = {"configstatus": 1} - - final_json = json.dumps(status) - return HttpResponse(final_json) - else: - data_ret = {'configstatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## save configuration data ends - - - except BaseException, msg: - data_ret = {'configstatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - - except KeyError, msg: - status = {"configstatus":0,"error":"Could not save, see CyberPanel main log file."} - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[saveConfigsToFile]") - return HttpResponse("Not Logged in as admin") + wm = WebsiteManager() + return wm.saveConfigsToFile(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def getRewriteRules(request): try: userID = request.session['userID'] - if request.method == 'POST': - try: - data = json.loads(request.body) - virtualHost = data['virtualHost'] - - try: - childDom = ChildDomains.objects.get(domain=virtualHost) - filePath = childDom.path + '/.htaccess' - - except: - website = Websites.objects.get(domain=virtualHost) - filePath = "/home/" + virtualHost + "/public_html/.htaccess" - - try: - rewriteRules = open(filePath,"r").read() - - if len(rewriteRules) == 0: - - status = {"rewriteStatus": 1, "error_message": "Rules file is currently empty"} - final_json = json.dumps(status) - return HttpResponse(final_json) - - status = {"rewriteStatus": 1, "rewriteRules": rewriteRules} - - final_json = json.dumps(status) - return HttpResponse(final_json) - except IOError: - status = {"rewriteStatus": 1, "error_message": "none","rewriteRules":""} - final_json = json.dumps(status) - return HttpResponse(final_json) - - except BaseException, msg: - data_ret = {'rewriteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - - except KeyError, msg: - status = {"logstatus":0,"error":"Could not fetch data from log file, please see CyberCP main log file through command line."} - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[getDataFromConfigFile]") - return HttpResponse("Not Logged in as admin") + wm = WebsiteManager() + return wm.getRewriteRules(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def saveRewriteRules(request): try: userID = request.session['userID'] - - if request.method == 'POST': - try: - data = json.loads(request.body) - virtualHost = data['virtualHost'] - - ## writing data temporary to file - - mailUtilities.checkHome() - tempPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - vhost = open(tempPath, "w") - vhost.write(data['rewriteRules']) - vhost.close() - - ## writing data temporary to file - - admin = Administrator.objects.get(pk=userID) - currentACL = ACLManager.loadedACL(userID) - - try: - childDomain = ChildDomains.objects.get(domain=virtualHost) - filePath = childDomain.path + '/.htaccess' - except: - filePath = "/home/" + virtualHost + "/public_html/.htaccess" - - ## save configuration data - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " saveRewriteRules --virtualHostName "+ virtualHost + " --path " + filePath + " --tempPath " + tempPath - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - status = {"rewriteStatus": 1, 'error_message': output} - final_json = json.dumps(status) - return HttpResponse(final_json) - else: - data_ret = {'rewriteStatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## save configuration data ends - - except BaseException, msg: - data_ret = {'rewriteStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except KeyError, msg: - status = {"rewriteStatus":0,"error":"Could not save, see main log file."} - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[saveConfigsToFile]") - return HttpResponse("Not Logged in as admin") + wm = WebsiteManager() + return wm.saveRewriteRules(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def saveSSL(request): try: userID = request.session['userID'] - try: - if request.method == 'POST': - - data = json.loads(request.body) - domain = data['virtualHost'] - - mailUtilities.checkHome() - - ## writing data temporary to file - - - tempKeyPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - vhost = open(tempKeyPath, "w") - vhost.write(data['key']) - vhost.close() - - tempCertPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - vhost = open(tempCertPath, "w") - vhost.write(data['cert']) - vhost.close() - - ## writing data temporary to file - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " saveSSL --virtualHostName " + domain + " --tempKeyPath " + tempKeyPath + " --tempCertPath " + tempCertPath - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - data_ret = {'sslStatus': 1, 'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - logging.CyberCPLogFileWriter.writeToFile( - output) - data_ret = {'sslStatus': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## save configuration data ends - - - except BaseException,msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Can not create directory to stroe SSL [saveSSL]]") - data_ret = {'sslStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except KeyError,msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg) + " [Can not create directory to stroe SSL [saveSSL]]") - data_ret = {'sslStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + wm = WebsiteManager() + return wm.saveSSL(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def changePHP(request): try: userID = request.session['userID'] - try: - if request.method == 'POST': - - data = json.loads(request.body) - childDomain = data['childDomain'] - phpVersion = data['phpSelection'] - - admin = Administrator.objects.get(pk=userID) - currentACL = ACLManager.loadedACL(userID) - - confPath = virtualHostUtilities.Server_root + "/conf/vhosts/" + childDomain - completePathToConfigFile = confPath + "/vhost.conf" - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " changePHP --phpVersion '" + phpVersion + "' --path " + completePathToConfigFile - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'changePHP': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - data_ret = {'changePHP': 1,'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException,msg: - data_ret = {'changePHP': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except KeyError,msg: - data_ret = {'changePHP': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + wm = WebsiteManager() + return wm.changePHP(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def listCron(request): try: userID = request.session['userID'] - try: - currentACL = ACLManager.loadedACL(userID) - - websitesName = ACLManager.findAllSites(currentACL, userID) - - return render(request, 'websiteFunctions/listCron.html', {'websiteList': websitesName}) - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse(str(msg)) + wm = WebsiteManager() + return wm.listCron(request, userID) except KeyError: return redirect(loadLoginPage) def getWebsiteCron(request): try: userID = request.session['userID'] - if request.method == 'POST': - try: - currentACL = ACLManager.loadedACL(userID) - - data = json.loads(request.body) - domain = data['domain'] - - admin = Administrator.objects.get(pk=request.session['userID']) - website = Websites.objects.get(domain=domain) - - if Websites.objects.filter(domain=domain).exists(): - pass - else: - dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - cronPath = "/var/spool/cron/" + website.externalApp - cmd = 'sudo test -e ' + cronPath + ' && echo Exists' - output = os.popen(cmd).read() - - if "Exists" not in output: - data_ret = {'getWebsiteCron': 1, "user": website.externalApp, "crons": {}} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - cronPath = "/var/spool/cron/" + website.externalApp - crons = [] - - try: - f = subprocess.check_output(["sudo", "cat", cronPath]) - print f - except subprocess.CalledProcessError as error: - dic = {'getWebsiteCron': 0, 'error_message': 'Unable to access Cron file'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - counter = 0 - for line in f.split("\n"): - if line: - split = line.split(" ", 5) - print line - print split - if len(split) == 6: - counter += 1 - crons.append({"line": counter, - "minute": split[0], - "hour": split[1], - "monthday": split[2], - "month": split[3], - "weekday": split[4], - "command": split[5]}) - - print json.dumps(crons) - - data_ret = {'getWebsiteCron': 1, "user": website.externalApp, "crons": crons} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException, msg: - print msg - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - except KeyError, msg: - status = {"getWebsiteCron": 0, "error": "Not Logged in as admin"} - final_json = json.dumps(status) - return HttpResponse(final_json) + wm = WebsiteManager() + return wm.getWebsiteCron(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def getCronbyLine(request): try: userID = request.session['userID'] - if request.method == 'POST': - try: - currentACL = ACLManager.loadedACL(userID) - data = json.loads(request.body) - domain = data['domain'] - line = data['line'] - - line -= 1 - admin = Administrator.objects.get(pk=request.session['userID']) - website = Websites.objects.get(domain=domain) - - if Websites.objects.filter(domain=domain).exists(): - pass - else: - dic = {'getWebsiteCron': 0, 'error_message': 'You do not own this domain'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - cronPath = "/var/spool/cron/" + website.externalApp - crons = [] - - try: - f = subprocess.check_output(["sudo", "cat", cronPath]) - print f - except subprocess.CalledProcessError as error: - dic = {'getWebsiteCron': 0, 'error_message': 'Unable to access Cron file'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - f = f.split("\n") - cron = f[line] - - if not cron: - dic = {'getWebsiteCron': 0, 'error_message': 'Cron line empty'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - cron = cron.split(" ", 5) - if len(cron) != 6: - dic = {'getWebsiteCron': 0, 'error_message': 'Cron line incorrect'} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - data_ret = {"getWebsiteCron": 1, - "user": website.externalApp, - "cron": { - "minute": cron[0], - "hour": cron[1], - "monthday": cron[2], - "month": cron[3], - "weekday": cron[4], - "command": cron[5], - }, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException, msg: - print msg - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - except KeyError, msg: - status = {"getWebsiteCron": 0, "error": "Not Logged in"} - final_json = json.dumps(status) - return HttpResponse(final_json) + wm = WebsiteManager() + return wm.getCronbyLine(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def saveCronChanges(request): try: userID = request.session['userID'] - if request.method == 'POST': - try: - currentACL = ACLManager.loadedACL(userID) - data = json.loads(request.body) - domain = data['domain'] - line = data['line'] - - minute = data['minute'] - hour = data['hour'] - monthday = data['monthday'] - month = data['month'] - weekday = data['weekday'] - command = data['command'] - - website = Websites.objects.get(domain=domain) - - cronPath = "/var/spool/cron/" + website.externalApp - tempPath = "/home/cyberpanel/" + website.externalApp + str(randint(10000, 99999)) + ".cron.tmp" - - finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) - - o = subprocess.call(['sudo', 'cp', cronPath, tempPath]) - if o is not 0: - data_ret = {'addNewCron': 0, 'error_message': 'Unable to copy to temporary files'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - # Confirming that directory is read/writable - o = subprocess.call(['sudo', 'chown', 'cyberpanel:cyberpanel', tempPath]) - if o is not 0: - data_ret = {'addNewCron': 0, 'error_message': 'Error Changing Permissions'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - with open(tempPath, 'r') as file: - data = file.readlines() - - data[line] = finalCron + '\n' - - with open(tempPath, 'w') as file: - file.writelines(data) - print 'test' - - output = subprocess.call(["sudo", "/usr/bin/crontab", "-u", website.externalApp, tempPath]) - - os.remove(tempPath) - if output != 0: - data_ret = {'addNewCron': 0, 'error_message': 'Incorrect Syntax cannot be accepted.'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - data_ret = {"getWebsiteCron": 1, - "user": website.externalApp, - "cron": finalCron, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException, msg: - print msg - dic = {'getWebsiteCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - except KeyError, msg: - status = {"getWebsiteCron": 0, "error": "Not Logged in"} - final_json = json.dumps(status) - return HttpResponse(final_json) + wm = WebsiteManager() + return wm.saveCronChanges(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def remCronbyLine(request): try: userID = request.session['userID'] - if request.method == 'POST': - try: - data = json.loads(request.body) - domain = data['domain'] - line = data['line'] - - line -= 1 - - website = Websites.objects.get(domain=domain) - - cronPath = "/var/spool/cron/" + website.externalApp - cmd = 'sudo test -e ' + cronPath + ' && echo Exists' - output = os.popen(cmd).read() - - if "Exists" not in output: - data_ret = {'remCronbyLine': 0, 'error_message': 'No Cron exists for this user'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - cronPath = "/var/spool/cron/" + website.externalApp - tempPath = "/home/cyberpanel/" + website.externalApp + str(randint(10000, 99999)) + ".cron.tmp" - - o = subprocess.call(['sudo', 'cp', cronPath, tempPath]) - if o is not 0: - data_ret = {'addNewCron': 0, 'error_message': 'Unable to copy to temporary files'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - # Confirming that directory is read/writable - o = subprocess.call(['sudo', 'chown', 'cyberpanel:cyberpanel', tempPath]) - if o is not 0: - data_ret = {'addNewCron': 0, 'error_message': 'Error Changing Permissions'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - with open(tempPath, 'r') as file: - data = file.readlines() - - removedLine = data.pop(line) - - with open(tempPath, 'w') as file: - file.writelines(data) - - output = subprocess.call(["sudo", "/usr/bin/crontab", "-u", website.externalApp, tempPath]) - - os.remove(tempPath) - if output != 0: - data_ret = {'addNewCron': 0, 'error_message': 'Incorrect Syntax cannot be accepted'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - data_ret = {"remCronbyLine": 1, - "user": website.externalApp, - "removeLine": removedLine, - "line": line} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException, msg: - print msg - dic = {'remCronbyLine': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - except KeyError, msg: - status = {"remCronbyLine": 0, "error": "Not Logged in"} - final_json = json.dumps(status) - return HttpResponse(final_json) + wm = WebsiteManager() + return wm.remCronbyLine(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def addNewCron(request): try: userID = request.session['userID'] - if request.method == 'POST': - try: - currentACL = ACLManager.loadedACL(userID) - data = json.loads(request.body) - domain = data['domain'] - - minute = data['minute'] - hour = data['hour'] - monthday = data['monthday'] - month = data['month'] - weekday = data['weekday'] - command = data['command'] - - website = Websites.objects.get(domain=domain) - - cronPath = "/var/spool/cron/" + website.externalApp - cmd = 'sudo test -e ' + cronPath + ' && echo Exists' - output = os.popen(cmd).read() - - if "Exists" not in output: - echo = subprocess.Popen(('echo'), stdout=subprocess.PIPE) - output = subprocess.call(('sudo', 'crontab', '-u', website.externalApp, '-'), stdin=echo.stdout) - echo.wait() - echo.stdout.close() - # Confirmation - o = subprocess.call(["sudo", "cp", "/dev/null", cronPath]) - - cronPath = "/var/spool/cron/" + website.externalApp - tempPath = "/home/cyberpanel/" + website.externalApp + str(randint(10000, 99999)) + ".cron.tmp" - - finalCron = "%s %s %s %s %s %s" % (minute, hour, monthday, month, weekday, command) - - o = subprocess.call(['sudo', 'cp', cronPath, tempPath]) - if o is not 0: - data_ret = {'addNewCron': 0, 'error_message': 'Unable to copy to temporary files'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - # Confirming that directory is read/writable - o = subprocess.call(['sudo', 'chown', 'cyberpanel:cyberpanel', tempPath]) - if o is not 0: - data_ret = {'addNewCron': 0, 'error_message': 'Error Changing Permissions'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - with open(tempPath, "a") as file: - file.write(finalCron + "\n") - - output = subprocess.call(["sudo", "/usr/bin/crontab", "-u", website.externalApp, tempPath]) - - os.remove(tempPath) - if output != 0: - data_ret = {'addNewCron': 0, 'error_message': 'Incorrect Syntax cannot be accepted'} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - - data_ret = {"addNewCron": 1, - "user": website.externalApp, - "cron": finalCron} - final_json = json.dumps(data_ret) - return HttpResponse(final_json) - except BaseException, msg: - print msg - dic = {'addNewCron': 0, 'error_message': str(msg)} - json_data = json.dumps(dic) - return HttpResponse(json_data) - - except KeyError, msg: - status = {"addNewCron": 0, "error": "Not Logged in"} - final_json = json.dumps(status) - return HttpResponse(final_json) + wm = WebsiteManager() + return wm.addNewCron(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def domainAlias(request, domain): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - try: - - if ACLManager.checkOwnership(domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - - aliasManager = AliasManager(domain) - noAlias, finalAlisList = aliasManager.fetchAlisForDomains() - - path = "/home/" + domain + "/public_html" - - return render(request, 'websiteFunctions/domainAlias.html', { - 'masterDomain': domain, - 'aliases':finalAlisList, - 'path':path, - 'noAlias':noAlias - }) - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse(str(msg)) + wm = WebsiteManager(domain) + return wm.domainAlias(request, userID) except KeyError: return redirect(loadLoginPage) def submitAliasCreation(request): try: userID = request.session['userID'] - currentACL = ACLManager.loadedACL(userID) - admin = Administrator.objects.get(pk=userID) - - if request.method == 'POST': - - if ACLManager.checkOwnership(domain, admin, currentACL) == 1: - pass - else: - return ACLManager.loadError() - - - data = json.loads(request.body) - - masterDomain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - ssl = data['ssl'] - - sslpath = "/home/" + masterDomain + "/public_html" - - ## Create Configurations - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " createAlias --masterDomain " + masterDomain + " --aliasDomain " + aliasDomain + " --ssl " + str( - ssl) + " --sslPath " + sslpath + " --administratorEmail " + admin.email + ' --websiteOwner ' + admin.userName - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'createAliasStatus': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Create Configurations ends here - - data_ret = {'createAliasStatus': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'createAliasStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + wm = WebsiteManager() + return wm.submitAliasCreation(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def issueAliasSSL(request): try: userID = request.session['userID'] - if request.method == 'POST': - currentACL = ACLManager.loadedACL(userID) - data = json.loads(request.body) - - masterDomain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - - admin = Administrator.objects.get(pk=userID) - - sslpath = "/home/" + masterDomain + "/public_html" - - ## Create Configurations - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " issueAliasSSL --masterDomain " + masterDomain + " --aliasDomain " + aliasDomain + " --sslPath " + sslpath + " --administratorEmail " + admin.email - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'sslStatus': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Create Configurations ends here - - - - data_ret = {'sslStatus': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - - except BaseException, msg: - data_ret = {'sslStatus': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + wm = WebsiteManager() + return wm.issueAliasSSL(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def delateAlias(request): try: userID = request.session['userID'] - if request.method == 'POST': - data = json.loads(request.body) - - masterDomain = data['masterDomain'] - aliasDomain = data['aliasDomain'] - - ## Create Configurations - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " deleteAlias --masterDomain " + masterDomain + " --aliasDomain " + aliasDomain - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'deleteAlias': 0, 'error_message': output, "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Create Configurations ends here - - data_ret = {'deleteAlias': 1, 'error_message': "None", "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - - except BaseException, msg: - data_ret = {'deleteAlias': 0, 'error_message': str(msg), "existsStatus": 0} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + wm = WebsiteManager() + return wm.delateAlias(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def changeOpenBasedir(request): try: userID = request.session['userID'] - try: - if request.method == 'POST': - - data = json.loads(request.body) - domainName = data['domainName'] - openBasedirValue = data['openBasedirValue'] - - currentACL = ACLManager.loadedACL(userID) - if currentACL['admin'] != 1: - return ACLManager.loadErrorJson('changeOpenBasedir', 0) - - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " changeOpenBasedir --virtualHostName '" + domainName + "' --openBasedirValue " + openBasedirValue - - - output = subprocess.check_output(shlex.split(execPath)) - - if output.find("1,None") > -1: - pass - else: - data_ret = {'changeOpenBasedir': 0, 'error_message': output} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - - data_ret = {'changeOpenBasedir': 1,'error_message': "None"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException,msg: - data_ret = {'changeOpenBasedir': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except KeyError,msg: - data_ret = {'changeOpenBasedir': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + wm = WebsiteManager() + return wm.changeOpenBasedir(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def applicationInstaller(request): try: @@ -1749,476 +326,94 @@ def applicationInstaller(request): def wordpressInstall(request, domain): try: userID = request.session['userID'] - return render(request, 'websiteFunctions/installWordPress.html', {'domainName' : domain}) + wm = WebsiteManager(domain) + return wm.wordpressInstall(request, userID) except KeyError: return redirect(loadLoginPage) def installWordpress(request): try: - val = request.session['userID'] - admin = Administrator.objects.get(pk=val) - - if request.method == 'POST': - try: - data = json.loads(request.body) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['blogTitle'] = data['blogTitle'] - extraArgs['adminUser'] = data['adminUser'] - extraArgs['adminPassword'] = data['adminPassword'] - extraArgs['adminEmail'] = data['adminEmail'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - - background = ApplicationInstaller('wordpress', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'installStatus': 1, 'error_message': 'None', 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException, msg: - data_ret = {'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except KeyError, msg: - status = {"installStatus":0,"error":str(msg)} - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[installWordpress]") - return HttpResponse("Not Logged in as admin") + userID = request.session['userID'] + wm = WebsiteManager() + return wm.installWordpress(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def installWordpressStatus(request): try: - val = request.session['userID'] - admin = Administrator.objects.get(pk=val) - if request.method == 'POST': - try: - data = json.loads(request.body) - statusFile = data['statusFile'] - - statusData = open(statusFile, 'r').readlines() - - lastLine = statusData[-1] - - if lastLine.find('[200]') > -1: - data_ret = { 'abort':1, 'installStatus': 1, 'installationProgress': "100", 'currentStatus': 'Successfully Installed.' } - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - elif lastLine.find('[404]') > -1: - data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", 'error_message': lastLine} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - else: - progress = lastLine.split(',') - currentStatus = progress[0] - installationProgress = progress[1] - data_ret = {'abort': 0, 'installStatus': 0, 'installationProgress': installationProgress, 'currentStatus': currentStatus} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except KeyError, msg: - data_ret = {'abort': 1, 'installStatus': 0, 'installationProgress': "0", 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + userID = request.session['userID'] + wm = WebsiteManager() + return wm.installWordpressStatus(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def joomlaInstall(request, domain): try: userID = request.session['userID'] - return render(request, 'websiteFunctions/installJoomla.html', {'domainName' : domain}) + wm = WebsiteManager(domain) + return wm.joomlaInstall(request, userID) except KeyError: return redirect(loadLoginPage) def installJoomla(request): try: - val = request.session['userID'] - - if request.method == 'POST': - try: - data = json.loads(request.body) - domainName = data['domain'] - home = data['home'] - - sitename = data['sitename'] - username = data['username'] - password = data['password'] - prefix = data['prefix'] - - mailUtilities.checkHome() - - tempStatusPath = "/home/cyberpanel/" + str(randint(1000, 9999)) - - statusFile = open(tempStatusPath, 'w') - statusFile.writelines('Setting up paths,0') - statusFile.close() - - finalPath = "" - - admin = Administrator.objects.get(pk=val) - - ## DB Creation - - statusFile = open(tempStatusPath, 'w') - statusFile.writelines('Creating database..,10') - statusFile.close() - - dbName = randomPassword.generate_pass() - dbUser = dbName - dbPassword = randomPassword.generate_pass() - - if Databases.objects.filter(dbName=dbName).exists() or Databases.objects.filter( - dbUser=dbUser).exists(): - data_ret = {'installStatus': 0, - 'error_message': "0,This database or user is already taken."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - result = mysqlUtilities.createDatabase(dbName, dbUser, dbPassword) - - if result == 1: - pass - else: - data_ret = {'installStatus': 0, - 'error_message': "0,Not able to create database."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## - - - - try: - website = ChildDomains.objects.get(domain=domainName) - externalApp = website.master.externalApp - - if website.master.package.dataBases > website.master.databases_set.all().count(): - pass - else: - data_ret = {'installStatus': 0, - 'error_message': "0,Maximum database limit reached for this website."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if home == '0': - path = data['path'] - finalPath = website.path.rstrip('/') + "/" + path + "/" - else: - finalPath = website.path + "/" - - db = Databases(website=website.master, dbName=dbName, dbUser=dbUser) - db.save() - - except: - website = Websites.objects.get(domain=domainName) - externalApp = website.externalApp - - if website.package.dataBases > website.databases_set.all().count(): - pass - else: - data_ret = {'installStatus': 0, - 'error_message': "0,Maximum database limit reached for this website."} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - if home == '0': - path = data['path'] - finalPath = "/home/" + domainName + "/public_html/" + path + "/" - else: - finalPath = "/home/" + domainName + "/public_html/" - - - db = Databases(website=website, dbName=dbName, dbUser=dbUser) - db.save() - - - - if finalPath.find("..") > -1: - data_ret = {'installStatus': 0, - 'error_message': "Specified path must be inside virtual host home!"} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation - salt = randomPassword.generate_pass(32) - #return salt - password_hash = hashlib.md5(password + salt).hexdigest() - password = password_hash + ":" + salt - - statusFile = open(tempStatusPath, 'w') - statusFile.writelines('Downloading Joomla Core..,20') - statusFile.close() - - - execPath = "sudo python " + virtualHostUtilities.cyberPanel + "/plogical/virtualHostUtilities.py" - - execPath = execPath + " installJoomla --virtualHostName " + domainName + \ - " --virtualHostUser " + externalApp + " --path " + finalPath + " --dbName " + dbName + \ - " --dbUser " + dbUser + " --dbPassword " + dbPassword + " --username " + username + \ - " --password " + password +" --prefix " + prefix + " --sitename '" + sitename + "'" \ - + " --tempStatusPath " + tempStatusPath - - #return execPath - - - output = subprocess.Popen(shlex.split(execPath)) - - data_ret = {"installStatus": 1, 'tempStatusPath': tempStatusPath} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - - ## Installation ends - - except BaseException, msg: - data_ret = {'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except KeyError, msg: - status = {"installStatus":0,"error":str(msg)} - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[installJoomla]") - return HttpResponse("Not Logged in as admin") + userID = request.session['userID'] + wm = WebsiteManager() + return wm.installJoomla(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def setupGit(request, domain): try: userID = request.session['userID'] - try: - path = '/home/cyberpanel/' + domain + '.git' - - if os.path.exists(path): - - ipFile = "/etc/cyberpanel/machineIP" - f = open(ipFile) - ipData = f.read() - ipAddress = ipData.split('\n', 1)[0] - - webhookURL = 'https://' + ipAddress + ':8090/websites/' + domain + '/gitNotify' - - return render(request, 'websiteFunctions/setupGit.html', - {'domainName': domain, 'installed': 1, 'webhookURL': webhookURL}) - else: - command = 'sudo cat /root/.ssh/cyberpanel.pub' - deploymentKey = subprocess.check_output(shlex.split(command)).strip('\n') - - return render(request, 'websiteFunctions/setupGit.html', {'domainName' : domain, 'deploymentKey': deploymentKey, 'installed': 0}) - except BaseException, msg: - logging.CyberCPLogFileWriter.writeToFile(str(msg)) - return HttpResponse(str(msg)) + wm = WebsiteManager(domain) + return wm.setupGit(request, userID) except KeyError: return redirect(loadLoginPage) def setupGitRepo(request): try: - val = request.session['userID'] - admin = Administrator.objects.get(pk=val) - - if request.method == 'POST': - try: - data = json.loads(request.body) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['username'] = data['username'] - extraArgs['reponame'] = data['reponame'] - extraArgs['branch'] = data['branch'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - extraArgs['defaultProvider'] = data['defaultProvider'] - - - background = ApplicationInstaller('git', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'installStatus': 1, 'error_message': 'None', 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException, msg: - data_ret = {'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except KeyError, msg: - status = {"installStatus":0,"error":str(msg)} - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[installWordpress]") - return HttpResponse("Not Logged in as admin") + userID = request.session['userID'] + wm = WebsiteManager() + return wm.setupGitRepo(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def gitNotify(request, domain): try: - if request.method == 'POST': - try: - - extraArgs = {} - extraArgs['domain'] = domain - - background = ApplicationInstaller('pull', extraArgs) - background.start() - - data_ret = {'pulled': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except BaseException, msg: - data_ret = {'pulled': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except KeyError, msg: - data_ret = {"pulled":0,"error":str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) + wm = WebsiteManager(domain) + return wm.gitNotify() + except KeyError: + return redirect(loadLoginPage) def detachRepo(request): try: - val = request.session['userID'] - admin = Administrator.objects.get(pk=val) - - if request.method == 'POST': - try: - data = json.loads(request.body) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['domainName'] = data['domain'] - extraArgs['admin'] = admin - - - background = ApplicationInstaller('detach', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException, msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except KeyError, msg: - status = {"status":0,"error":str(msg)} - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[installWordpress]") - return HttpResponse("Not Logged in as admin") + userID = request.session['userID'] + wm = WebsiteManager() + return wm.detachRepo(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def changeBranch(request): try: - val = request.session['userID'] - admin = Administrator.objects.get(pk=val) - - if request.method == 'POST': - try: - data = json.loads(request.body) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['domainName'] = data['domain'] - extraArgs['githubBranch'] = data['githubBranch'] - extraArgs['admin'] = admin - - - background = ApplicationInstaller('changeBranch', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'status': 1, 'error_message': 'None'} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except BaseException, msg: - data_ret = {'status': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - - except KeyError, msg: - status = {"status":0,"error":str(msg)} - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[installWordpress]") - return HttpResponse("Not Logged in as admin") + userID = request.session['userID'] + wm = WebsiteManager() + return wm.changeBranch(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage) def installPrestaShop(request, domain): try: userID = request.session['userID'] - - return render(request, 'websiteFunctions/installPrestaShop.html', {'domainName' : domain}) - + wm = WebsiteManager(domain) + return wm.installPrestaShop(request, userID) except KeyError: return redirect(loadLoginPage) def prestaShopInstall(request): try: - val = request.session['userID'] - admin = Administrator.objects.get(id=val) - if request.method == 'POST': - try: - data = json.loads(request.body) - - mailUtilities.checkHome() - - extraArgs = {} - extraArgs['admin'] = admin - extraArgs['domainName'] = data['domain'] - extraArgs['home'] = data['home'] - extraArgs['shopName'] = data['shopName'] - extraArgs['firstName'] = data['firstName'] - extraArgs['lastName'] = data['lastName'] - extraArgs['databasePrefix'] = data['databasePrefix'] - extraArgs['email'] = data['email'] - extraArgs['password'] = data['password'] - extraArgs['tempStatusPath'] = "/home/cyberpanel/" + str(randint(1000, 9999)) - - if data['home'] == '0': - extraArgs['path'] = data['path'] - - background = ApplicationInstaller('prestashop', extraArgs) - background.start() - - time.sleep(2) - - data_ret = {'installStatus': 1, 'error_message': 'None', 'tempStatusPath': extraArgs['tempStatusPath']} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - ## Installation ends - - except BaseException, msg: - data_ret = {'installStatus': 0, 'error_message': str(msg)} - json_data = json.dumps(data_ret) - return HttpResponse(json_data) - - except KeyError, msg: - status = {"installStatus":0,"error":str(msg)} - logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[installJoomla]") - return HttpResponse("Not Logged in as admin") + userID = request.session['userID'] + wm = WebsiteManager() + return wm.prestaShopInstall(userID, json.loads(request.body)) + except KeyError: + return redirect(loadLoginPage)