Merge branch 'stable' into patch-1

This commit is contained in:
Usman Nasir
2021-07-21 07:47:18 +05:00
committed by GitHub
190 changed files with 31877 additions and 23342 deletions

1
.gitignore vendored
View File

@@ -4,3 +4,4 @@
*.pyc
.idea
venv
/.venv/

View File

@@ -1,121 +0,0 @@
From 348f6dbaa4b3e7141c9d32e1c44e3ea1ba2d9984 Mon Sep 17 00:00:00 2001
From: qtwrk <qtwrk555@gmail.com>
Date: Tue, 10 Mar 2020 17:23:30 +0100
Subject: [PATCH] fix some issue on self-signed cert
---
cyberpanel.sh | 4 ++--
cyberpanel_upgrade.sh | 55 +++++++++++++++++++++++++++++++++++++++++--
2 files changed, 55 insertions(+), 4 deletions(-)
diff --git a/cyberpanel.sh b/cyberpanel.sh
index d4ce5caf..d657d3e3 100644
--- a/cyberpanel.sh
+++ b/cyberpanel.sh
@@ -1123,7 +1123,7 @@ dnQualifier = CyberPanel
[server_exts]
extendedKeyUsage = 1.3.6.1.5.5.7.3.1
EOF
-openssl req -x509 -config /root/cyberpanel/cert_conf -extensions 'server_exts' -nodes -days 820 -newkey rsa:3072 -keyout /usr/local/lscp/conf/key.pem -out /usr/local/lscp/conf/cert.pem
+openssl req -x509 -config /root/cyberpanel/cert_conf -extensions 'server_exts' -nodes -days 820 -newkey rsa:2048 -keyout /usr/local/lscp/conf/key.pem -out /usr/local/lscp/conf/cert.pem
if [[ $VERSION == "OLS" ]] ; then
key_path="/usr/local/lsws/admin/conf/webadmin.key"
@@ -1133,7 +1133,7 @@ else
cert_path="/usr/local/lsws/admin/conf/cert/admin.crt"
fi
-openssl req -x509 -config /root/cyberpanel/cert_conf -extensions 'server_exts' -nodes -days 820 -newkey rsa:3072 -keyout $key_path -out $cert_path
+openssl req -x509 -config /root/cyberpanel/cert_conf -extensions 'server_exts' -nodes -days 820 -newkey rsa:2048 -keyout $key_path -out $cert_path
rm -f /root/cyberpanel/cert_conf
}
diff --git a/cyberpanel_upgrade.sh b/cyberpanel_upgrade.sh
index db0c76bd..41004b66 100644
--- a/cyberpanel_upgrade.sh
+++ b/cyberpanel_upgrade.sh
@@ -26,6 +26,44 @@ if [[ $SERVER_COUNTRY == "CN" ]] ; then
GIT_CONTENT_URL="gitee.com/qtwrk/cyberpanel/raw"
fi
+regenerate_cert() {
+cat << EOF > /usr/local/CyberCP/cert_conf
+[req]
+prompt=no
+distinguished_name=cyberpanel
+[cyberpanel]
+commonName = www.example.com
+countryName = CP
+localityName = CyberPanel
+organizationName = CyberPanel
+organizationalUnitName = CyberPanel
+stateOrProvinceName = CP
+emailAddress = mail@example.com
+name = CyberPanel
+surname = CyberPanel
+givenName = CyberPanel
+initials = CP
+dnQualifier = CyberPanel
+[server_exts]
+extendedKeyUsage = 1.3.6.1.5.5.7.3.1
+EOF
+if [[ $1 == "8090" ]] ; then
+openssl req -x509 -config /usr/local/CyberCP/cert_conf -extensions 'server_exts' -nodes -days 820 -newkey rsa:2048 -keyout /usr/local/lscp/conf/key.pem -out /usr/local/lscp/conf/cert.pem
+fi
+
+if [[ $1 == "7080" ]] ; then
+ if [[ -f /usr/local/lsws/admin/conf/webadmin.key ]] ; then
+ key_path="/usr/local/lsws/admin/conf/webadmin.key"
+ cert_path="/usr/local/lsws/admin/conf/webadmin.crt"
+ else
+ key_path="/usr/local/lsws/admin/conf/cert/admin.key"
+ cert_path="/usr/local/lsws/admin/conf/cert/admin.crt"
+ fi
+openssl req -x509 -config /usr/local/CyberCP/cert_conf -extensions 'server_exts' -nodes -days 820 -newkey rsa:2048 -keyout $key_path -out $cert_path
+fi
+rm -f /usr/local/CyberCP/cert_conf
+
+}
input_branch() {
echo -e "\nPress Enter key to continue with latest version or Enter specific version such as: \e[31m1.9.4\e[39m , \e[31m1.9.5\e[39m ...etc"
@@ -233,6 +271,19 @@ fi
install_utility
+output=$(timeout 3 openssl s_client -connect 127.0.0.1:8090 2>/dev/null)
+echo $output | grep -q "mail@example.com"
+if [[ $? == "0" ]] ; then
+# it is using default installer generated cert
+regenerate_cert 8090
+fi
+output=$(timeout 3 openssl s_client -connect 127.0.0.1:7080 2>/dev/null)
+echo $output | grep -q "mail@example.com"
+if [[ $? == "0" ]] ; then
+regenerate_cert 7080
+fi
+
+
if [[ $SERVER_OS == "CentOS7" ]] ; then
sed -i 's|error_reporting = E_ALL \&amp; ~E_DEPRECATED \&amp; ~E_STRICT|error_reporting = E_ALL \& ~E_DEPRECATED \& ~E_STRICT|g' /usr/local/lsws/{lsphp72,lsphp73}/etc/php.ini
@@ -245,14 +296,14 @@ yum list installed lsphp74-devel
fi
if [[ $SERVER_OS == "Ubuntu" ]] ; then
- dpkg -l lsphp74-dev
+ dpkg -l lsphp74-dev > /dev/null 2>&1
if [[ $? != "0" ]] ; then
apt install -y lsphp74-dev
fi
fi
if [[ ! -f /usr/local/lsws/lsphp74/lib64/php/modules/zip.so ]] && [[ $SERVER_OS == "CentOS7" ]] ; then
- yum list installed libzip-devel
+ yum list installed libzip-devel > /dev/null 2>&1
if [[ $? == "0" ]] ; then
yum remove -y libzip-devel
fi
--
2.17.1

View File

@@ -10,7 +10,7 @@ from django.shortcuts import HttpResponse
from math import ceil
from websiteFunctions.models import Websites
from CLManager.models import CLPackages
from plogical.httpProc import httpProc
class CLManagerMain(multi.Thread):
@@ -27,29 +27,14 @@ class CLManagerMain(multi.Thread):
self.submitCageFSInstall()
elif self.function == 'enableOrDisable':
self.enableOrDisable()
except BaseException as msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + ' [ContainerManager.run]')
def renderC(self):
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
ipAddress = ipData.split('\n', 1)[0]
data = {}
data['CL'] = 0
data['activatedPath'] = 0
data['ipAddress'] = ipAddress
CLPath = '/etc/sysconfig/cloudlinux'
activatedPath = '/home/cyberpanel/cloudlinux'
@@ -60,11 +45,14 @@ class CLManagerMain(multi.Thread):
data['activatedPath'] = 1
if data['CL'] == 0:
return render(self.request, 'CLManager/notAvailable.html', data)
proc = httpProc(self.request, 'CLManager/notAvailable.html', data, 'admin')
return proc.render()
elif data['activatedPath'] == 0:
return render(self.request, 'CLManager/notAvailable.html', data)
proc = httpProc(self.request, 'CLManager/notAvailable.html', data, 'admin')
return proc.render()
else:
return render(self.request, 'CLManager/cloudLinux.html', data)
proc = httpProc(self.request, 'CLManager/cloudLinux.html', data, 'admin')
return proc.render()
def submitCageFSInstall(self):
try:

View File

@@ -243,10 +243,6 @@ def main():
elif args["function"] == "submitinstallImunifyAV":
CageFS.submitinstallImunifyAV()
if __name__ == "__main__":
main()

View File

@@ -2,17 +2,18 @@ from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^CreatePackage$', views.CreatePackage, name='CreatePackageCL'),
url(r'^listPackages$', views.listPackages, name='listPackagesCL'),
url(r'^monitorUsage$', views.monitorUsage, name='monitorUsage'),
url(r'^CageFS$', views.CageFS, name='CageFS'),
url(r'^submitCageFSInstall$', views.submitCageFSInstall, name='submitCageFSInstall'),
url(r'^submitWebsiteListing$', views.getFurtherAccounts, name='submitWebsiteListing'),
url(r'^enableOrDisable$', views.enableOrDisable, name='enableOrDisable'),
url(r'^CreatePackage$', views.CreatePackage, name='CreatePackageCL'),
url(r'^submitCreatePackage$', views.submitCreatePackage, name='submitCreatePackageCL'),
url(r'^listPackages$', views.listPackages, name='listPackagesCL'),
url(r'^fetchPackages$', views.fetchPackages, name='fetchPackagesCL'),
url(r'^deleteCLPackage$', views.deleteCLPackage, name='deleteCLPackage'),
url(r'^saveSettings$', views.saveSettings, name='saveSettings'),
url(r'^monitorUsage$', views.monitorUsage, name='monitorUsage'),
url(r'^manage/(?P<domain>(.*))$', views.websiteContainerLimit, name='websiteContainerLimitCL'),
url(r'^getUsageData$', views.getUsageData, name='getUsageData'),
# url(r'^submitWebsiteListing$', views.getFurtherAccounts, name='submitWebsiteListing'),
# url(r'^enableOrDisable$', views.enableOrDisable, name='enableOrDisable'),
# url(r'^submitCreatePackage$', views.submitCreatePackage, name='submitCreatePackageCL'),
# url(r'^fetchPackages$', views.fetchPackages, name='fetchPackagesCL'),
# url(r'^deleteCLPackage$', views.deleteCLPackage, name='deleteCLPackage'),
# url(r'^saveSettings$', views.saveSettings, name='saveSettings'),
# url(r'^manage/(?P<domain>(.*))$', views.websiteContainerLimit, name='websiteContainerLimitCL'),
# url(r'^getUsageData$', views.getUsageData, name='getUsageData'),
]

View File

@@ -4,8 +4,8 @@ class CLMain():
def __init__(self):
self.path = '/usr/local/CyberCP/version.txt'
#versionInfo = json.loads(open(self.path, 'r').read())
self.version = '2.0'
self.build = '3'
self.version = '2.1'
self.build = '1'
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)

View File

@@ -14,7 +14,6 @@ import argparse
import json
from CLScript.CLMain import CLMain
class CloudLinuxResellers(CLMain):
def __init__(self, id, name):
@@ -23,17 +22,26 @@ class CloudLinuxResellers(CLMain):
self.name = name
def listAll(self, owner=None):
import pwd
users = []
acl = ACL.objects.get(name='reseller')
from plogical.vhost import vhost
for items in Administrator.objects.filter(acl=acl):
if self.name != None:
if self.name != items.userName:
continue
try:
uid = pwd.getpwnam(items.userName).pw_uid
except:
vhost.addUser(items.userName, '/home/%s' % (items.userName))
uid = pwd.getpwnam(items.userName).pw_uid
user = {'name': items.userName,
"locale_code": "EN_us",
"email": items.email,
"id": None
"id": uid
}
users.append(user)

View File

@@ -81,7 +81,7 @@ class CloudLinuxUsers(CLMain):
for webs in websites:
try:
itemPackage = webs.package
package = {'name': itemPackage.packageName, 'owner': webs.externalApp}
package = {'name': itemPackage.packageName, 'owner': webs.admin.userName}
user = {}
@@ -92,7 +92,12 @@ class CloudLinuxUsers(CLMain):
user['username'] = webs.externalApp
if self.ow:
user['owner'] = webs.externalApp
if webs.admin.owner == 1:
user['owner'] = webs.admin.userName
else:
from loginSystem.models import Administrator
oAdmin = Administrator.objects.get(pk=webs.admin.owner)
user['owner'] = oAdmin.userName
if self.domain:
user['domain'] = webs.domain
@@ -133,7 +138,11 @@ class CloudLinuxUsers(CLMain):
if self.owner == None:
websites = Websites.objects.all()
else:
websites = Websites.objects.filter(externalApp=self.owner)
from loginSystem.models import Administrator
from plogical.acl import ACLManager
oAdmin = Administrator.objects.get(userName=self.owner)
currentACL = ACLManager.loadedACL(oAdmin.pk)
websites = ACLManager.findWebsiteObjects(currentACL, oAdmin.pk)
if self.username != None:
websites = websites.filter(externalApp=self.username)

View File

@@ -2,10 +2,15 @@
import getpass
def main():
import pwd
if getpass.getuser() == 'root':
userType = "admin"
else:
userType = "user"
try:
uid = pwd.getpwnam(getpass.getuser()).pw_uid
userType = 'reseller'
except:
userType = 'user'
data = """{
"userName": "%s",

View File

@@ -194,7 +194,7 @@ fixperms_cyberpanel () {
echo "Fixing public_html...."
tput sgr0
#Fix perms of public_html itself
chown "$verbose" "$account":"$account" "$HOMEDIR"/public_html
chown "$verbose" "$account":nobody "$HOMEDIR"/public_html
chmod "$verbose" 755 "$HOMEDIR"/public_html
tput bold

View File

@@ -2,22 +2,21 @@
#systemctl stop firewalld
check_return() {
#check previous command result , 0 = ok , non-0 = something wrong.
if [[ $? -eq "0" ]] ; then
:
else
echo -e "\ncommand failed, exiting..."
exit
fi
#check previous command result , 0 = ok , non-0 = something wrong.
if [[ $? -eq "0" ]]; then
:
else
echo -e "\ncommand failed, exiting..."
exit
fi
}
echo 'backup configs';
cp /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf-bak_$(date '+%Y-%m-%d_%H_%M:%S');
cp /etc/postfix/master.cf /etc/postfix/master.cf-bak_$(date '+%Y-%m-%d_%H_%M:%S');
cp /etc/postfix/main.cf /etc/postfix/main.cf-bak_$(date '+%Y-%m-%d_%H_%M:%S');
echo 'backup configs'
cp /etc/dovecot/dovecot.conf /etc/dovecot/dovecot.conf-bak_$(date '+%Y-%m-%d_%H_%M:%S')
cp /etc/postfix/master.cf /etc/postfix/master.cf-bak_$(date '+%Y-%m-%d_%H_%M:%S')
cp /etc/postfix/main.cf /etc/postfix/main.cf-bak_$(date '+%Y-%m-%d_%H_%M:%S')
cp /etc/dovecot/dovecot-sql.conf.ext /etc/dovecot/dovecot-sql.conf.ext-bak_$(date '+%Y-%m-%d_%H_%M:%S')
ZONE=$(firewall-cmd --get-default-zone)
firewall-cmd --zone=$ZONE --add-port=4190/tcp --permanent
systemctl stop firewalld
@@ -27,167 +26,131 @@ csf -x
MAILSCANNER=/etc/MailScanner
if [ -d $MAILSCANNER ];then
echo "MailScanner found. If you wish to reinstall then remove the package and revert"
echo "Postfix back to its original config at /etc/postfix/main.cf and remove"
echo "/etc/MailScanner and /usr/share/MailScanner directories"
exit
if [ -d $MAILSCANNER ]; then
echo "MailScanner found. If you wish to reinstall then remove the package and revert"
echo "Postfix back to its original config at /etc/postfix/main.cf and remove"
echo "/etc/MailScanner and /usr/share/MailScanner directories"
exit
fi
if [ -f /etc/os-release ];then
OS=$(head -1 /etc/os-release)
UBUNTUVERSION=$(sed '6q;d' /etc/os-release)
CENTOSVERSION=$(sed '5q;d' /etc/os-release)
CLNVERSION=$(sed '3q;d' /etc/os-release)
fi
if [ "$CENTOSVERSION" = "VERSION_ID=\"7\"" ];then
setenforce 0
yum install -y perl yum-utils perl-CPAN
yum install -y gcc cpp perl bzip2 zip make patch automake rpm-build perl-Archive-Zip perl-Filesys-Df perl-OLE-Storage_Lite perl-Sys-Hostname-Long perl-Sys-SigAction perl-Net-CIDR perl-DBI perl-MIME-tools perl-DBD-SQLite binutils glibc-devel perl-Filesys-Df zlib unzip zlib-devel wget mlocate clamav "perl(DBD::mysql)"
rpm -Uvh https://forensics.cert.org/centos/cert/7/x86_64/unrar-5.4.0-1.el7.x86_64.rpm
export PERL_MM_USE_DEFAULT=1
curl -L https://cpanmin.us | perl - App::cpanminus
perl -MCPAN -e 'install Encoding::FixLatin'
perl -MCPAN -e 'install Digest::SHA1'
perl -MCPAN -e 'install Geo::IP'
perl -MCPAN -e 'install Razor2::Client::Agent'
perl -MCPAN -e 'install Net::Patricia'
freshclam -v
DIR=/etc/mail/spamassassin
if [ -d "$DIR" ]; then
sa-update
else
echo "Please install spamassassin through the CyberPanel interface before proceeding"
exit
fi
elif [ "$CENTOSVERSION" = "VERSION_ID=\"8\"" ];then
setenforce 0
yum install -y perl yum-utils perl-CPAN
dnf --enablerepo=powertools install -y perl-IO-stringy
dnf --enablerepo=PowerTools install -y perl-IO-stringy
yum install -y gcc cpp perl bzip2 zip make patch automake rpm-build perl-Archive-Zip perl-Filesys-Df perl-OLE-Storage_Lite perl-Net-CIDR perl-DBI perl-MIME-tools perl-DBD-SQLite binutils glibc-devel perl-Filesys-Df zlib unzip zlib-devel wget mlocate clamav clamav-update "perl(DBD::mysql)"
rpm -Uvh https://forensics.cert.org/centos/cert/8/x86_64/unrar-5.4.0-1.el8.x86_64.rpm
export PERL_MM_USE_DEFAULT=1
curl -L https://cpanmin.us | perl - App::cpanminus
perl -MCPAN -e 'install Encoding::FixLatin'
perl -MCPAN -e 'install Digest::SHA1'
perl -MCPAN -e 'install Geo::IP'
perl -MCPAN -e 'install Razor2::Client::Agent'
perl -MCPAN -e 'install Sys::Hostname::Long'
perl -MCPAN -e 'install Sys::SigAction'
freshclam -v
### Check SpamAssasin before moving forward
DIR=/etc/mail/spamassassin
if [ -d "$DIR" ]; then
sa-update
if [ -d "$DIR" ]; then
sa-update
else
echo "Please install spamassassin through the CyberPanel interface before proceeding"
exit
echo "Please install spamassassin through the CyberPanel interface before proceeding"
exit
fi
elif [ "$CLNVERSION" = "ID=\"cloudlinux\"" ];then
setenforce 0
yum install -y perl yum-utils perl-CPAN
yum install -y gcc cpp perl bzip2 zip make patch automake rpm-build perl-Archive-Zip perl-Filesys-Df perl-OLE-Storage_Lite perl-Sys-Hostname-Long perl-Sys-SigAction perl-Net-CIDR perl-DBI perl-MIME-tools perl-DBD-SQLite binutils glibc-devel perl-Filesys-Df zlib unzip zlib-devel wget mlocate clamav "perl(DBD::mysql)"
rpm -Uvh https://forensics.cert.org/centos/cert/7/x86_64/unrar-5.4.0-1.el7.x86_64.rpm
export PERL_MM_USE_DEFAULT=1
curl -L https://cpanmin.us | perl - App::cpanminus
perl -MCPAN -e 'install Encoding::FixLatin'
perl -MCPAN -e 'install Digest::SHA1'
perl -MCPAN -e 'install Geo::IP'
perl -MCPAN -e 'install Razor2::Client::Agent'
perl -MCPAN -e 'install Net::Patricia'
freshclam -v
DIR=/etc/mail/spamassassin
if [ -d "$DIR" ]; then
sa-update
else
echo "Please install spamassassin through the CyberPanel interface before proceeding"
exit
if [ -f /etc/os-release ]; then
OS=$(head -1 /etc/os-release)
UBUNTUVERSION=$(sed '6q;d' /etc/os-release)
CENTOSVERSION=$(sed '5q;d' /etc/os-release)
CLNVERSION=$(sed '3q;d' /etc/os-release)
fi
elif [ "$OS" = "NAME=\"Ubuntu\"" ];then
if [ "$CENTOSVERSION" = "VERSION_ID=\"7\"" ]; then
apt-get install -y libmysqlclient-dev
setenforce 0
yum install -y perl yum-utils perl-CPAN
yum install -y gcc cpp perl bzip2 zip make patch automake rpm-build perl-Archive-Zip perl-Filesys-Df perl-OLE-Storage_Lite perl-Sys-Hostname-Long perl-Sys-SigAction perl-Net-CIDR perl-DBI perl-MIME-tools perl-DBD-SQLite binutils glibc-devel perl-Filesys-Df zlib unzip zlib-devel wget mlocate clamav "perl(DBD::mysql)"
apt-get install -y cpanminus gcc perl bzip2 zip make patch automake rpm libarchive-zip-perl libfilesys-df-perl libole-storage-lite-perl libsys-hostname-long-perl libsys-sigaction-perl libregexp-common-net-cidr-perl libmime-tools-perl libdbd-sqlite3-perl binutils build-essential libfilesys-df-perl zlib1g unzip mlocate clamav libdbd-mysql-perl unrar libclamav-dev libclamav-client-perl libclamunrar9
rpm -Uvh https://forensics.cert.org/centos/cert/7/x86_64/unrar-5.4.0-1.el7.x86_64.rpm
export PERL_MM_USE_DEFAULT=1
curl -L https://cpanmin.us | perl - App::cpanminus
perl -MCPAN -e 'install Encoding::FixLatin'
perl -MCPAN -e 'install Digest::SHA1'
perl -MCPAN -e 'install Geo::IP'
perl -MCPAN -e 'install Razor2::Client::Agent'
perl -MCPAN -e 'install Net::Patricia'
cpanm Encoding::FixLatin
cpanm Digest::SHA1
cpanm Geo::IP
cpanm Razor2::Client::Agent
cpanm Net::Patricia
cpanm Net::CIDR
freshclam -v
sudo systemctl stop clamav-freshclam.service
elif [ "$CENTOSVERSION" = "VERSION_ID=\"8\"" ]; then
freshclam
setenforce 0
yum install -y perl yum-utils perl-CPAN
dnf --enablerepo=powertools install -y perl-IO-stringy
dnf --enablerepo=PowerTools install -y perl-IO-stringy
yum install -y gcc cpp perl bzip2 zip make patch automake rpm-build perl-Archive-Zip perl-Filesys-Df perl-OLE-Storage_Lite perl-Net-CIDR perl-DBI perl-MIME-tools perl-DBD-SQLite binutils glibc-devel perl-Filesys-Df zlib unzip zlib-devel wget mlocate clamav clamav-update "perl(DBD::mysql)"
sudo systemctl start clamav-freshclam.service
rpm -Uvh https://forensics.cert.org/centos/cert/8/x86_64/unrar-5.4.0-1.el8.x86_64.rpm
DIR=/etc/spamassassin
if [ -d "$DIR" ]; then
export PERL_MM_USE_DEFAULT=1
curl -L https://cpanmin.us | perl - App::cpanminus
apt-get -y install razor pyzor libencode-detect-perl libgeo-ip-perl libnet-patricia-perl
sa-update
else
echo "Please install spamassassin through the CyberPanel interface before proceeding"
exit
fi
perl -MCPAN -e 'install Encoding::FixLatin'
perl -MCPAN -e 'install Digest::SHA1'
perl -MCPAN -e 'install Geo::IP'
perl -MCPAN -e 'install Razor2::Client::Agent'
perl -MCPAN -e 'install Sys::Hostname::Long'
perl -MCPAN -e 'install Sys::SigAction'
freshclam -v
elif [ "$CLNVERSION" = "ID=\"cloudlinux\"" ]; then
setenforce 0
yum install -y perl yum-utils perl-CPAN
yum install -y gcc cpp perl bzip2 zip make patch automake rpm-build perl-Archive-Zip perl-Filesys-Df perl-OLE-Storage_Lite perl-Sys-Hostname-Long perl-Sys-SigAction perl-Net-CIDR perl-DBI perl-MIME-tools perl-DBD-SQLite binutils glibc-devel perl-Filesys-Df zlib unzip zlib-devel wget mlocate clamav "perl(DBD::mysql)"
rpm -Uvh https://forensics.cert.org/centos/cert/7/x86_64/unrar-5.4.0-1.el7.x86_64.rpm
export PERL_MM_USE_DEFAULT=1
curl -L https://cpanmin.us | perl - App::cpanminus
perl -MCPAN -e 'install Encoding::FixLatin'
perl -MCPAN -e 'install Digest::SHA1'
perl -MCPAN -e 'install Geo::IP'
perl -MCPAN -e 'install Razor2::Client::Agent'
perl -MCPAN -e 'install Net::Patricia'
freshclam -v
elif [ "$OS" = "NAME=\"Ubuntu\"" ]; then
apt-get install -y libmysqlclient-dev
apt-get install -y cpanminus gcc perl bzip2 zip make patch automake rpm libarchive-zip-perl libfilesys-df-perl libole-storage-lite-perl libsys-hostname-long-perl libsys-sigaction-perl libregexp-common-net-cidr-perl libmime-tools-perl libdbd-sqlite3-perl binutils build-essential libfilesys-df-perl zlib1g unzip mlocate clamav libdbd-mysql-perl unrar libclamav-dev libclamav-client-perl libclamunrar9
cpanm Encoding::FixLatin
cpanm Digest::SHA1
cpanm Geo::IP
cpanm Razor2::Client::Agent
cpanm Net::Patricia
cpanm Net::CIDR
sudo systemctl stop clamav-freshclam.service
freshclam
sudo systemctl start clamav-freshclam.service
fi
echo "header_checks = regexp:/etc/postfix/header_checks" >> /etc/postfix/main.cf
echo "/^Received:/ HOLD" >> /etc/postfix/header_checks
echo "header_checks = regexp:/etc/postfix/header_checks" >>/etc/postfix/main.cf
echo "/^Received:/ HOLD" >>/etc/postfix/header_checks
systemctl restart postfix
if [ "$OS" = "NAME=\"Ubuntu\"" ];then
wget https://github.com/MailScanner/v5/releases/download/5.3.3-1/MailScanner-5.3.3-1.noarch.deb
dpkg -i *.noarch.deb
if [ "$OS" = "NAME=\"Ubuntu\"" ]; then
wget https://github.com/MailScanner/v5/releases/download/5.3.3-1/MailScanner-5.3.3-1.noarch.deb
dpkg -i *.noarch.deb
mkdir /var/run/MailScanner
mkdir /var/lock/subsys
mkdir /var/lock/subsys/MailScanner
chown -R postfix:postfix /var/run/MailScanner
chown -R postfix:postfix /var/lock/subsys/MailScanner
chown -R postfix:postfix /var/spool/MailScanner
mkdir /var/run/MailScanner
mkdir /var/lock/subsys
mkdir /var/lock/subsys/MailScanner
chown -R postfix:postfix /var/run/MailScanner
chown -R postfix:postfix /var/lock/subsys/MailScanner
chown -R postfix:postfix /var/spool/MailScanner
elif [ "$OS" = "NAME=\"CentOS Linux\"" ];then
wget https://github.com/MailScanner/v5/releases/download/5.3.3-1/MailScanner-5.3.3-1.rhel.noarch.rpm
rpm -Uvh *.rhel.noarch.rpm
elif [ "$OS" = "NAME=\"CentOS Linux\"" ]; then
wget https://github.com/MailScanner/v5/releases/download/5.3.3-1/MailScanner-5.3.3-1.rhel.noarch.rpm
rpm -Uvh *.rhel.noarch.rpm
elif [ "$OS" = "NAME=\"CloudLinux\"" ];then
wget https://github.com/MailScanner/v5/releases/download/5.3.3-1/MailScanner-5.3.3-1.rhel.noarch.rpm
rpm -Uvh *.rhel.noarch.rpm
elif [ "$OS" = "NAME=\"CloudLinux\"" ]; then
wget https://github.com/MailScanner/v5/releases/download/5.3.3-1/MailScanner-5.3.3-1.rhel.noarch.rpm
rpm -Uvh *.rhel.noarch.rpm
fi
mkdir /var/spool/MailScanner/spamassassin
@@ -234,8 +197,15 @@ PASSWORD=$(cat /etc/cyberpanel/mysqlPassword)
USER=root
DATABASE=mailscanner
ADMINPASS=$(cat /etc/cyberpanel/adminPass)
mysql -u${USER} -p${PASSWORD} < "/usr/local/CyberCP/public/mailwatch/create.sql"
mysql -u${USER} -p${PASSWORD} -e "use mailscanner";
### Fix a bug in MailWatch SQL File
sed -i 's/char(512)/char(255)/g' /usr/local/CyberCP/public/mailwatch/create.sql
##
mysql -u${USER} -p${PASSWORD} <"/usr/local/CyberCP/public/mailwatch/create.sql"
mysql -u${USER} -p${PASSWORD} -e "use mailscanner"
mysql -u${USER} -D${DATABASE} -p${PASSWORD} -e "GRANT ALL ON mailscanner.* TO root@localhost IDENTIFIED BY '${PASSWORD}';"
mysql -u${USER} -D${DATABASE} -p${PASSWORD} -e "FLUSH PRIVILEGES;"
mysql -u${USER} -D${DATABASE} -p${PASSWORD} -e "INSERT INTO mailscanner.users SET username = 'admin', password = MD5('${ADMINPASS}'), fullname = 'admin', type = 'A';"
@@ -247,11 +217,11 @@ sed -i "s/^define('DB_PASS',.*/define('DB_PASS','${PASSWORD}');/" /usr/local/Cyb
sed -i "s/^define('MAILWATCH_HOME',.*/define(\'MAILWATCH_HOME\', \'\/usr\/local\/CyberCP\/public\/mailwatch\/mailscanner');/" /usr/local/CyberCP/public/mailwatch/mailscanner/conf.php
MSDEFAULT=/etc/MailScanner/defaults
if [ -f "$MSDEFAULT" ];then
sed -i 's/^run_mailscanner=.*/run_mailscanner=1/' /etc/MailScanner/defaults
elif [ ! -f "$MSDEFAULT" ];then
touch /etc/MailScanner/defaults
echo "run_mailscanner=1" >> /etc/MailScanner/defaults
if [ -f "$MSDEFAULT" ]; then
sed -i 's/^run_mailscanner=.*/run_mailscanner=1/' /etc/MailScanner/defaults
elif [ ! -f "$MSDEFAULT" ]; then
touch /etc/MailScanner/defaults
echo "run_mailscanner=1" >>/etc/MailScanner/defaults
fi
cp /usr/local/CyberCP/public/mailwatch/MailScanner_perl_scripts/MailWatchConf.pm /usr/share/MailScanner/perl/custom/
@@ -268,125 +238,121 @@ systemctl restart mailscanner
IPADDRESS=$(cat /etc/cyberpanel/machineIP)
### Furhter onwards is sieve configurations
echo 'Setting up spamassassin and sieve to deliver spam to Junk folder by default'
#echo "If you wish mailscanner/spamassassin to send spam email to a spam folder please follow the tutorial on the Cyberpanel Website"
echo 'Fix protocols'
sed -i 's/^protocols =.*/protocols = imap pop3 lmtp sieve/g' /etc/dovecot/dovecot.conf
sed -i "s|^user_query.*|user_query = SELECT '5000' as uid, '5000' as gid, '/home/vmail/%d/%n' as home,mail FROM e_users WHERE email='%u';|g" /etc/dovecot/dovecot-sql.conf.ext
if [ "$OS" = "NAME=\"Ubuntu\"" ];then
if [ "$UBUNTUVERSION" = "VERSION_ID=\"18.04\"" ];then
apt-get install -y dovecot-managesieved dovecot-sieve dovecot-lmtpd net-tools pflogsumm
elif [ "$UBUNTUVERSION" = "VERSION_ID=\"20.04\"" ];then
apt-get install -y libmysqlclient-dev
sed -e '/deb/ s/^#*/#/' -i /etc/apt/sources.list.d/dovecot.list
apt install -y dovecot-lmtpd dovecot-managesieved dovecot-sieve net-tools pflogsumm
fi
elif [ "$CENTOSVERSION" = "VERSION_ID=\"7\"" ];then
yum install -y nano net-tools dovecot-pigeonhole postfix-perl-scripts
elif [ "$CENTOSVERSION" = "VERSION_ID=\"8\"" ];then
rpm -Uvh http://mirror.ghettoforge.org/distributions/gf/el/8/gf/x86_64/gf-release-8-11.gf.el8.noarch.rpm
dnf --enablerepo=gf-plus upgrade -y dovecot23*
dnf --enablerepo=gf-plus install -y dovecot23-pigeonhole
dnf install -y net-tools postfix-perl-scripts
elif [ "$CLNVERSION" = "ID=\"cloudlinux\"" ];then
yum install -y nano net-tools dovecot-pigeonhole postfix-perl-scripts
fi
# Create Sieve files
mkdir -p /etc/dovecot/sieve/global
touch /var/log/{dovecot-lda-errors.log,dovecot-lda.log}
touch /var/log/{dovecot-sieve-errors.log,dovecot-sieve.log}
touch /var/log/{dovecot-lmtp-errors.log,dovecot-lmtp.log}
touch /etc/dovecot/sieve/default.sieve
chown vmail: -R /etc/dovecot/sieve
chown vmail:mail /var/log/dovecot-*
echo 'Create Sieve Default spam to Junk rule'
cat >> /etc/dovecot/sieve/default.sieve <<EOL
require "fileinto";
if header :contains "X-Spam-Flag" "YES" {
fileinto "INBOX.Junk E-mail";
}
EOL
echo "Adding Sieve to /etc/dovecot/dovecot.conf"
cat >> /etc/dovecot/dovecot.conf <<EOL
service managesieve-login {
inet_listener sieve {
port = 4190
}
}
service managesieve {
}
protocol sieve {
managesieve_max_line_length = 65536
managesieve_implementation_string = dovecot
log_path = /var/log/dovecot-sieve-errors.log
info_log_path = /var/log/dovecot-sieve.log
}
plugin {
sieve = /home/vmail/%d/%n/dovecot.sieve
sieve_global_path = /etc/dovecot/sieve/default.sieve
sieve_dir = /home/vmail/%d/%n/sieve
sieve_global_dir = /etc/dovecot/sieve/global/
}
protocol lda {
mail_plugins = $mail_plugins sieve quota
postmaster_address = postmaster@example.com
hostname = server.example.com
auth_socket_path = /var/run/dovecot/auth-master
log_path = /var/log/dovecot-lda-errors.log
info_log_path = /var/log/dovecot-lda.log
}
protocol lmtp {
mail_plugins = $mail_plugins sieve quota
log_path = /var/log/dovecot-lmtp-errors.log
info_log_path = /var/log/dovecot-lmtp.log
}
EOL
hostname=$(hostname);
echo 'Fix postmaster email in sieve'
postmaster_address=$(grep postmaster_address /etc/dovecot/dovecot.conf | sed 's/.*=//' |sed -e 's/^[ \t]*//'| sort -u)
sed -i "s|postmaster@example.com|$postmaster_address|g" /etc/dovecot/dovecot.conf
sed -i "s|server.example.com|$hostname|g" /etc/dovecot/dovecot.conf
sed -i "s|postmaster@example.com|$postmaster_address|g" /etc/dovecot/dovecot.conf
#Sieve the global spam filter
sievec /etc/dovecot/sieve/default.sieve
#Sieve the global spam filter
sievec /etc/dovecot/sieve/default.sieve
if [ "$OS" = "NAME=\"Ubuntu\"" ];then
sed -i 's|^spamassassin.*|spamassassin unix - n n - - pipe flags=DROhu user=vmail:vmail argv=/usr/bin/spamc -f -e /usr/lib/dovecot/deliver -f ${sender} -d ${user}@${nexthop}|g' /etc/postfix/master.cf
elif [ "$OS" = "NAME=\"CentOS Linux\"" ];then
sed -i 's|^spamassassin.*|spamassassin unix - n n - - pipe flags=DROhu user=vmail:vmail argv=/usr/bin/spamc -f -e /usr/libexec/dovecot/deliver -f ${sender} -d ${user}@${nexthop}|g' /etc/postfix/master.cf
elif [ "$OS" = "NAME=\"CloudLinux\"" ];then
sed -i 's|^spamassassin.*|spamassassin unix - n n - - pipe flags=DROhu user=vmail:vmail argv=/usr/bin/spamc -f -e /usr/libexec/dovecot/deliver -f ${sender} -d ${user}@${nexthop}|g' /etc/postfix/master.cf
fi
#echo 'Setting up spamassassin and sieve to deliver spam to Junk folder by default'
##echo "If you wish mailscanner/spamassassin to send spam email to a spam folder please follow the tutorial on the Cyberpanel Website"
#echo 'Fix protocols'
#sed -i 's/^protocols =.*/protocols = imap pop3 lmtp sieve/g' /etc/dovecot/dovecot.conf
#
#sed -i "s|^user_query.*|user_query = SELECT '5000' as uid, '5000' as gid, '/home/vmail/%d/%n' as home,mail FROM e_users WHERE email='%u';|g" /etc/dovecot/dovecot-sql.conf.ext
#
#if [ "$OS" = "NAME=\"Ubuntu\"" ]; then
# if [ "$UBUNTUVERSION" = "VERSION_ID=\"18.04\"" ]; then
# apt-get install -y dovecot-managesieved dovecot-sieve dovecot-lmtpd net-tools pflogsumm
# elif [ "$UBUNTUVERSION" = "VERSION_ID=\"20.04\"" ]; then
# apt-get install -y libmysqlclient-dev
# sed -e '/deb/ s/^#*/#/' -i /etc/apt/sources.list.d/dovecot.list
# apt install -y dovecot-lmtpd dovecot-managesieved dovecot-sieve net-tools pflogsumm
# fi
#
#elif [ "$CENTOSVERSION" = "VERSION_ID=\"7\"" ]; then
#
# yum install -y nano net-tools dovecot-pigeonhole postfix-perl-scripts
#
#elif [ "$CENTOSVERSION" = "VERSION_ID=\"8\"" ]; then
#
# rpm -Uvh http://mirror.ghettoforge.org/distributions/gf/el/8/gf/x86_64/gf-release-8-11.gf.el8.noarch.rpm
# dnf --enablerepo=gf-plus upgrade -y dovecot23*
# dnf --enablerepo=gf-plus install -y dovecot23-pigeonhole
# dnf install -y net-tools postfix-perl-scripts
#
#elif [ "$CLNVERSION" = "ID=\"cloudlinux\"" ]; then
# yum install -y nano net-tools dovecot-pigeonhole postfix-perl-scripts
#fi
#
## Create Sieve files
#mkdir -p /etc/dovecot/sieve/global
#touch /var/log/{dovecot-lda-errors.log,dovecot-lda.log}
#touch /var/log/{dovecot-sieve-errors.log,dovecot-sieve.log}
#touch /var/log/{dovecot-lmtp-errors.log,dovecot-lmtp.log}
#touch /etc/dovecot/sieve/default.sieve
#chown vmail: -R /etc/dovecot/sieve
#chown vmail:mail /var/log/dovecot-*
#
#echo 'Create Sieve Default spam to Junk rule'
#cat >>/etc/dovecot/sieve/default.sieve <<EOL
#require "fileinto";
#if header :contains "X-Spam-Flag" "YES" {
# fileinto "INBOX.Junk E-mail";
#}
#EOL
#
#echo "Adding Sieve to /etc/dovecot/dovecot.conf"
#cat >>/etc/dovecot/dovecot.conf <<EOL
#
#service managesieve-login {
# inet_listener sieve {
# port = 4190
# }
#}
#service managesieve {
#}
#protocol sieve {
# managesieve_max_line_length = 65536
# managesieve_implementation_string = dovecot
# log_path = /var/log/dovecot-sieve-errors.log
# info_log_path = /var/log/dovecot-sieve.log
#}
#plugin {
#sieve = /home/vmail/%d/%n/dovecot.sieve
#sieve_global_path = /etc/dovecot/sieve/default.sieve
#sieve_dir = /home/vmail/%d/%n/sieve
#sieve_global_dir = /etc/dovecot/sieve/global/
#}
#protocol lda {
# mail_plugins = $mail_plugins sieve quota
# postmaster_address = postmaster@example.com
# hostname = server.example.com
# auth_socket_path = /var/run/dovecot/auth-master
# log_path = /var/log/dovecot-lda-errors.log
# info_log_path = /var/log/dovecot-lda.log
#}
#protocol lmtp {
# mail_plugins = $mail_plugins sieve quota
# log_path = /var/log/dovecot-lmtp-errors.log
# info_log_path = /var/log/dovecot-lmtp.log
#}
#EOL
#
#hostname=$(hostname)
#
#echo 'Fix postmaster email in sieve'
#postmaster_address=$(grep postmaster_address /etc/dovecot/dovecot.conf | sed 's/.*=//' | sed -e 's/^[ \t]*//' | sort -u)
#
#sed -i "s|postmaster@example.com|$postmaster_address|g" /etc/dovecot/dovecot.conf
#sed -i "s|server.example.com|$hostname|g" /etc/dovecot/dovecot.conf
#sed -i "s|postmaster@example.com|$postmaster_address|g" /etc/dovecot/dovecot.conf
#
##Sieve the global spam filter
#sievec /etc/dovecot/sieve/default.sieve
#
##Sieve the global spam filter
#sievec /etc/dovecot/sieve/default.sieve
#
#if [ "$OS" = "NAME=\"Ubuntu\"" ]; then
# sed -i 's|^spamassassin.*|spamassassin unix - n n - - pipe flags=DROhu user=vmail:vmail argv=/usr/bin/spamc -f -e /usr/lib/dovecot/deliver -f ${sender} -d ${user}@${nexthop}|g' /etc/postfix/master.cf
#
#elif [ "$OS" = "NAME=\"CentOS Linux\"" ]; then
# sed -i 's|^spamassassin.*|spamassassin unix - n n - - pipe flags=DROhu user=vmail:vmail argv=/usr/bin/spamc -f -e /usr/libexec/dovecot/deliver -f ${sender} -d ${user}@${nexthop}|g' /etc/postfix/master.cf
#
#elif [ "$OS" = "NAME=\"CloudLinux\"" ]; then
# sed -i 's|^spamassassin.*|spamassassin unix - n n - - pipe flags=DROhu user=vmail:vmail argv=/usr/bin/spamc -f -e /usr/libexec/dovecot/deliver -f ${sender} -d ${user}@${nexthop}|g' /etc/postfix/master.cf
#
#fi
echo 'Restart and check services are up'
systemctl restart dovecot && systemctl restart postfix && systemctl restart spamassassin && systemctl restart mailscanner;
systemctl restart dovecot && systemctl restart postfix && systemctl restart spamassassin && systemctl restart mailscanner
csf -e

View File

@@ -1,28 +1,28 @@
#!/bin/bash
## Uninstall Mailscanner CyberPanel
if [ -f /etc/os-release ];then
OS=$(head -1 /etc/os-release)
UBUNTUVERSION=$(sed '6q;d' /etc/os-release)
CENTOSVERSION=$(sed '5q;d' /etc/os-release)
CLNVERSION=$(sed '3q;d' /etc/os-release)
if [ -f /etc/os-release ]; then
OS=$(head -1 /etc/os-release)
UBUNTUVERSION=$(sed '6q;d' /etc/os-release)
CENTOSVERSION=$(sed '5q;d' /etc/os-release)
CLNVERSION=$(sed '3q;d' /etc/os-release)
fi
systemctl stop mailscanner
if [ "$OS" = "NAME=\"Ubuntu\"" ];then
apt purge -y mailscanner
if [ "$OS" = "NAME=\"Ubuntu\"" ]; then
apt purge -y mailscanner
elif
[ "$OS" = "NAME=\"CentOS Linux\"" ]
then
yum remove -y MailScanner
elif [ "$OS" = "NAME=\"CentOS Linux\"" ];then
yum remove -y MailScanner
elif [ "$OS" = "NAME=\"CloudLinux\"" ];then
yum remove -y MailScanner
elif [ "$OS" = "NAME=\"CloudLinux\"" ]; then
yum remove -y MailScanner
fi
sed -i '/\/^Received:\/ HOLD/d' /etc/postfix/header_checks
rm -rf /etc/MailScanner
rm -rf /usr/share/MailScanner

View File

@@ -6,8 +6,12 @@
# Create the session path directories and chmod it for security to 1733 like the existing one is.
mkdir -p /var/lib/lsphp/session/lsphp{53,54,55,56,70,71,72,73,74}
chmod -R 1733 /var/lib/lsphp/session/lsphp{53,54,55,56,70,71,72,73,74}
for version in $(ls /usr/local/lsws|grep lsphp);
do
mkdir -p "/var/lib/lsphp/session/$version"
chmod -R 1733 "/var/lib/lsphp/session/$version"
done
YUM_CMD=$(which yum 2> /dev/null)

View File

@@ -1,7 +1,7 @@
# coding=utf-8
from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging
import json
from django.shortcuts import HttpResponse
from django.shortcuts import HttpResponse, render
import re
from loginSystem.models import Administrator
@@ -10,6 +10,12 @@ class secMiddleware:
HIGH = 0
LOW = 1
def get_client_ip(request):
ip = request.META.get('HTTP_CF_CONNECTING_IP')
if ip is None:
ip = request.META.get('REMOTE_ADDR')
return ip
def __init__(self, get_response):
self.get_response = get_response
@@ -17,7 +23,7 @@ class secMiddleware:
try:
uID = request.session['userID']
admin = Administrator.objects.get(pk=uID)
ipAddr = request.META.get('REMOTE_ADDR')
ipAddr = get_client_ip(request)
if ipAddr.find('.') > -1:
if request.session['ipAddr'] == ipAddr or admin.securityLevel == secMiddleware.LOW:
@@ -25,20 +31,19 @@ class secMiddleware:
else:
del request.session['userID']
del request.session['ipAddr']
logging.writeToFile(request.META.get('REMOTE_ADDR'))
logging.writeToFile(get_client_ip(request))
final_dic = {'error_message': "Session reuse detected, IPAddress logged.",
"errorMessage": "Session reuse detected, IPAddress logged."}
final_json = json.dumps(final_dic)
return HttpResponse(final_json)
else:
ipAddr = request.META.get('REMOTE_ADDR').split(':')[:3]
ipAddr = get_client_ip(request).split(':')[:3]
if request.session['ipAddr'] == ipAddr or admin.securityLevel == secMiddleware.LOW:
pass
else:
del request.session['userID']
del request.session['ipAddr']
logging.writeToFile(request.META.get('REMOTE_ADDR'))
logging.writeToFile(get_client_ip(request))
final_dic = {'error_message': "Session reuse detected, IPAddress logged.",
"errorMessage": "Session reuse detected, IPAddress logged."}
final_json = json.dumps(final_dic)
@@ -67,7 +72,7 @@ class secMiddleware:
final_json = json.dumps(final_dic)
return HttpResponse(final_json)
if request.build_absolute_uri().find('webhook') > -1 or request.build_absolute_uri().find('saveSpamAssassinConfigurations') > -1 or request.build_absolute_uri().find('docker') > -1 or request.build_absolute_uri().find('cloudAPI') > -1 or request.build_absolute_uri().find('filemanager') > -1 or request.build_absolute_uri().find('verifyLogin') > -1 or request.build_absolute_uri().find('submitUserCreation') > -1:
if request.build_absolute_uri().find('api/verifyConn') > -1 or request.build_absolute_uri().find('webhook') > -1 or request.build_absolute_uri().find('saveSpamAssassinConfigurations') > -1 or request.build_absolute_uri().find('docker') > -1 or request.build_absolute_uri().find('cloudAPI') > -1 or request.build_absolute_uri().find('filemanager') > -1 or request.build_absolute_uri().find('verifyLogin') > -1 or request.build_absolute_uri().find('submitUserCreation') > -1:
continue
if key == 'recordContentAAAA' or key == 'backupDestinations' or key == 'ports' \
or key == 'imageByPass' or key == 'passwordByPass' or key == 'cronCommand' \
@@ -96,18 +101,25 @@ class secMiddleware:
logging.writeToFile(str(msg))
response = self.get_response(request)
return response
# else:
# try:
# if request.path.find('cloudAPI/') > -1 or request.path.find('api/') > -1:
# pass
# else:
# uID = request.session['userID']
# except:
# return render(request, 'loginSystem/login.html', {})
response = self.get_response(request)
response['X-XSS-Protection'] = "1; mode=block"
#response['Strict-Transport-Security'] = "max-age=31536000; includeSubDomains; preload"
response['X-Frame-Options'] = "sameorigin"
response['Content-Security-Policy'] = "script-src 'self' https://www.jsdelivr.com"
response['Content-Security-Policy'] = "connect-src *;"
response['Content-Security-Policy'] = "font-src 'self' 'unsafe-inline' https://www.jsdelivr.com https://fonts.googleapis.com"
response['Content-Security-Policy'] = "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://www.jsdelivr.com https://cdnjs.cloudflare.com https://maxcdn.bootstrapcdn.com https://cdn.jsdelivr.net"
#response['Content-Security-Policy'] = "default-src 'self' cyberpanel.cloud *.cyberpanel.cloud"
response['X-Content-Type-Options'] = "nosniff"
response['Referrer-Policy'] = "same-origin"
return response
return response

View File

@@ -114,7 +114,7 @@ DATABASES = {
'USER': 'cyberpanel',
'PASSWORD': 'Bz9gF7Hr7X4RtD',
'HOST': 'localhost',
'PORT':''
'PORT': ''
},
'rootdb': {
'ENGINE': 'django.db.backends.mysql',

View File

@@ -0,0 +1,7 @@
from enum import Enum
class IncBackupPath(Enum):
SFTP = "/home/cyberpanel/sftp"
AWS = "/home/cyberpanel/aws"
# WASABI = "/home/cyberpanel/wasabi"

View File

@@ -0,0 +1,8 @@
from enum import Enum, auto
class IncBackupProvider(Enum):
LOCAL = auto()
SFTP = auto()
AWS = auto()
# WASABI = auto()

View File

@@ -219,9 +219,16 @@ class IncJobs(multi.Thread):
try:
logging.statusWriter(self.statusPath, 'Backing up data..', 1)
backupPath = '/home/%s' % (self.website.domain)
# Define our excludes file for use with restic
backupExcludesFile = '/home/%s/backup-exclude.conf' % (self.website.domain)
resticBackupExcludeCMD = ' --exclude-file=%s' % (backupExcludesFile)
if self.backupDestinations == 'local':
backupPath = '/home/%s' % (self.website.domain)
command = 'restic -r %s backup %s --password-file %s --exclude %s' % (self.repoPath, backupPath, self.passwordFile, self.repoPath)
# If /home/%s/backup-exclude.conf file exists lets pass this to restic by appending the command to end.
if os.path.isfile(backupExcludesFile):
command = command + resticBackupExcludeCMD
snapShotid = ProcessUtilities.outputExecutioner(command).split(' ')[-2]
newSnapshot = JobSnapshots(job=self.jobid, type='data:%s' % (backupPath), snapshotid=snapShotid, destination=self.backupDestinations)
@@ -230,8 +237,10 @@ class IncJobs(multi.Thread):
elif self.backupDestinations[:4] == 'sftp':
remotePath = '/home/backup/%s' % (self.website.domain)
backupPath = '/home/%s' % (self.website.domain)
command = 'export PATH=${PATH}:/usr/bin && restic -r %s:%s backup %s --password-file %s --exclude %s' % (self.backupDestinations, remotePath, backupPath, self.passwordFile, self.repoPath)
# If /home/%s/backup-exclude.conf file exists lets pass this to restic by appending the command to end.
if os.path.isfile(backupExcludesFile):
command = command + resticBackupExcludeCMD
snapShotid = ProcessUtilities.outputExecutioner(command).split(' ')[-2]
newSnapshot = JobSnapshots(job=self.jobid, type='data:%s' % (remotePath), snapshotid=snapShotid,
destination=self.backupDestinations)
@@ -312,13 +321,23 @@ class IncJobs(multi.Thread):
try:
logging.statusWriter(self.statusPath, 'Will first initiate backup repo..', 1)
# Define our excludes file for use with restic
backupExcludesFile = '/home/%s/backup-exclude.conf' % (self.website.domain)
resticBackupExcludeCMD = ' --exclude-file=%s' % (backupExcludesFile)
if self.backupDestinations == 'local':
command = 'restic init --repo %s --password-file %s' % (self.repoPath, self.passwordFile)
# If /home/%s/backup-exclude.conf file exists lets pass this to restic by appending the command to end.
if os.path.isfile(backupExcludesFile):
command = command + resticBackupExcludeCMD
ProcessUtilities.executioner(command, self.website.externalApp)
elif self.backupDestinations[:4] == 'sftp':
remotePath = '/home/backup/%s' % (self.website.domain)
command = 'export PATH=${PATH}:/usr/bin && restic init --repo %s:%s --password-file %s' % (self.backupDestinations, remotePath, self.passwordFile)
# If /home/%s/backup-exclude.conf file exists lets pass this to restic by appending the command to end.
if os.path.isfile(backupExcludesFile):
command = command + resticBackupExcludeCMD
ProcessUtilities.executioner(command)
logging.statusWriter(self.statusPath, 'Repo %s initiated for %s.' % (self.backupDestinations, self.website.domain), 1)

View File

@@ -1,8 +1,10 @@
#!/usr/local/CyberCP/bin/python
import os
import os.path
import shlex
import subprocess
import sys
import requests
sys.path.append('/usr/local/CyberCP')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
@@ -83,9 +85,7 @@ class IncJobs(multi.Thread):
result = self.getRemoteBackups()
activator = 0
json_data = "["
checker = 0
json_data = []
if result[0].find('unable to open config file') == -1:
for items in reversed(result):
@@ -98,20 +98,11 @@ class IncJobs(multi.Thread):
if activator:
entry = items.split(' ')
dic = {'id': entry[0],
'date': "%s %s" % (entry[2], entry[3]),
'host': entry[5],
'path': entry[-1]
}
if checker == 0:
json_data = json_data + json.dumps(dic)
checker = 1
else:
json_data = json_data + ',' + json.dumps(dic)
json_data = json_data + ']'
json_data.append({'id': entry[0],
'date': "%s %s" % (entry[2], entry[3]),
'host': entry[5],
'path': entry[-1]
})
final_json = json.dumps({'status': 1, 'error_message': "None", "data": json_data})
return HttpResponse(final_json)
@@ -144,14 +135,23 @@ class IncJobs(multi.Thread):
secret = open(path, 'r').read()
return key, secret
def awsFunction(self, fType, backupPath=None, snapshotID=None, bType=None):
## Last argument delete is set when the snapshot is to be deleted from this repo, when this argument is set, any preceding argument is not used
def awsFunction(self, fType, backupPath=None, snapshotID=None, bType=None, delete=None):
try:
if fType == 'backup':
key, secret = self.getAWSData()
command = 'export AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s && restic -r s3:s3.amazonaws.com/%s backup %s --password-file %s' % (
key, secret, self.website.domain, backupPath, self.passwordFile)
# Define our excludes file for use with restic
backupExcludesFile = '/home/%s/backup-exclude.conf' % (self.website.domain)
resticBackupExcludeCMD = ' --exclude-file=%s' % (backupExcludesFile)
command = 'export AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s && restic -r s3:s3.amazonaws.com/%s backup %s --password-file %s --exclude /home/%s/backup --exclude /home/%s/incbackup' % (
key, secret, self.website.domain, backupPath, self.passwordFile, self.website.domain, self.website.domain)
# If /home/%s/backup-exclude.conf file exists lets pass this to restic by appending the command to end.
if os.path.isfile(backupExcludesFile):
command = command + resticBackupExcludeCMD
result = ProcessUtilities.outputExecutioner(command)
if result.find('saved') == -1:
@@ -186,6 +186,27 @@ class IncJobs(multi.Thread):
if result.find('restoring') == -1:
logging.statusWriter(self.statusPath, 'Failed: %s. [5009]' % (result), 1)
return 0
elif delete:
self.backupDestinations = self.jobid.destination
key, secret = self.getAWSData()
command = 'export AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s && restic -r s3:s3.amazonaws.com/%s forget %s --password-file %s' % (
key, secret, self.website, snapshotID, self.passwordFile)
result = ProcessUtilities.outputExecutioner(command)
if result.find('removed snapshot') > -1 or result.find('deleted') > -1:
pass
else:
logging.statusWriter(self.statusPath, 'Failed: %s. [5009]' % (result), 1)
return 0
command = 'export AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s && restic -r s3:s3.amazonaws.com/%s prune --password-file %s' % (
key, secret, self.website, self.passwordFile)
ProcessUtilities.outputExecutioner(command)
else:
self.backupDestinations = self.jobid.destination
@@ -207,10 +228,20 @@ class IncJobs(multi.Thread):
logging.statusWriter(self.statusPath, "%s [88][5009]" % (str(msg)), 1)
return 0
def localFunction(self, backupPath, type, restore=None):
## Last argument delete is set when the snapshot is to be deleted from this repo, when this argument is set, any preceding argument is not used
def localFunction(self, backupPath, type, restore=None, delete=None):
if restore == None:
command = 'restic -r %s backup %s --password-file %s --exclude %s' % (
self.repoPath, backupPath, self.passwordFile, self.repoPath)
# Define our excludes file for use with restic
backupExcludesFile = '/home/%s/backup-exclude.conf' % (self.website.domain)
resticBackupExcludeCMD = ' --exclude-file=%s' % (backupExcludesFile)
command = 'restic -r %s backup %s --password-file %s --exclude %s --exclude /home/%s/backup' % (
self.repoPath, backupPath, self.passwordFile, self.repoPath, self.website.domain)
# If /home/%s/backup-exclude.conf file exists lets pass this to restic by appending the command to end.
if os.path.isfile(backupExcludesFile):
command = command + resticBackupExcludeCMD
result = ProcessUtilities.outputExecutioner(command)
if result.find('saved') == -1:
@@ -228,6 +259,23 @@ class IncJobs(multi.Thread):
newSnapshot = JobSnapshots(job=self.jobid, type='%s:%s' % (type, backupPath), snapshotid=snapShotid,
destination=self.backupDestinations)
newSnapshot.save()
return 1
elif delete:
repoLocation = '/home/%s/incbackup' % (self.website)
command = 'restic -r %s forget %s --password-file %s' % (repoLocation, self.jobid.snapshotid, self.passwordFile)
result = ProcessUtilities.outputExecutioner(command)
if result.find('removed snapshot') > -1 or result.find('deleted') > -1:
pass
else:
logging.statusWriter(self.statusPath, 'Failed: %s. [5009]' % (result), 1)
return 0
command = 'restic -r %s prune --password-file %s' % (repoLocation, self.passwordFile)
ProcessUtilities.outputExecutioner(command)
return 1
else:
repoLocation = '/home/%s/incbackup' % (self.website)
@@ -242,11 +290,19 @@ class IncJobs(multi.Thread):
return 1
def sftpFunction(self, backupPath, type, restore=None):
## Last argument delete is set when the snapshot is to be deleted from this repo, when this argument is set, any preceding argument is not used
def sftpFunction(self, backupPath, type, restore=None, delete=None):
if restore == None:
# Define our excludes file for use with restic
backupExcludesFile = '/home/%s/backup-exclude.conf' % (self.website.domain)
resticBackupExcludeCMD = ' --exclude-file=%s' % (backupExcludesFile)
remotePath = '/home/backup/%s' % (self.website.domain)
command = 'export PATH=${PATH}:/usr/bin && restic -r %s:%s backup %s --password-file %s --exclude %s' % (
self.backupDestinations, remotePath, backupPath, self.passwordFile, self.repoPath)
command = 'export PATH=${PATH}:/usr/bin && restic -r %s:%s backup %s --password-file %s --exclude %s --exclude /home/%s/backup' % (
self.backupDestinations, remotePath, backupPath, self.passwordFile, self.repoPath, self.website.domain)
# If /home/%s/backup-exclude.conf file exists lets pass this to restic by appending the command to end.
if os.path.isfile(backupExcludesFile):
command = command + resticBackupExcludeCMD
result = ProcessUtilities.outputExecutioner(command)
if result.find('saved') == -1:
@@ -265,6 +321,20 @@ class IncJobs(multi.Thread):
destination=self.backupDestinations)
newSnapshot.save()
return 1
elif delete:
repoLocation = '/home/backup/%s' % (self.website)
command = 'export PATH=${PATH}:/usr/bin && restic -r %s:%s forget %s --password-file %s' % (
self.jobid.destination, repoLocation, self.jobid.snapshotid, self.passwordFile)
result = ProcessUtilities.outputExecutioner(command)
if result.find('removed snapshot') > -1 or result.find('deleted') > -1:
pass
else:
logging.statusWriter(self.statusPath, 'Failed: %s. [5009]' % (result), 1)
return 0
command = 'export PATH=${PATH}:/usr/bin && restic -r %s:%s prune --password-file %s' % (self.jobid.destination, repoLocation, self.passwordFile)
ProcessUtilities.outputExecutioner(command)
else:
if self.reconstruct == 'remote':
repoLocation = '/home/backup/%s' % (self.website)
@@ -426,6 +496,7 @@ class IncJobs(multi.Thread):
def restorePoint(self):
try:
self.statusPath = self.extraArgs['tempPath']
self.website = self.extraArgs['website']
jobid = self.extraArgs['jobid']
@@ -515,177 +586,29 @@ class IncJobs(multi.Thread):
def prepareBackupMeta(self):
try:
######### Generating meta
## XML Generation
metaFileXML = Element('metaFile')
child = SubElement(metaFileXML, 'masterDomain')
child.text = self.website.domain
child = SubElement(metaFileXML, 'phpSelection')
child.text = self.website.phpSelection
child = SubElement(metaFileXML, 'externalApp')
child.text = self.website.externalApp
childDomains = self.website.childdomains_set.all()
databases = self.website.databases_set.all()
## Child domains XML
childDomainsXML = Element('ChildDomains')
for items in childDomains:
childDomainXML = Element('domain')
child = SubElement(childDomainXML, 'domain')
child.text = items.domain
child = SubElement(childDomainXML, 'phpSelection')
child.text = items.phpSelection
child = SubElement(childDomainXML, 'path')
child.text = items.path
childDomainsXML.append(childDomainXML)
metaFileXML.append(childDomainsXML)
## Databases XML
databasesXML = Element('Databases')
for items in databases:
try:
dbuser = DBUsers.objects.get(user=items.dbUser)
userToTry = items.dbUser
except:
dbusers = DBUsers.objects.all().filter(user=items.dbUser)
for it in dbusers:
dbuser = it
break
userToTry = mysqlUtilities.mysqlUtilities.fetchuser(items.dbName)
if userToTry == 0 or userToTry == 1:
continue
try:
dbuser = DBUsers.objects.get(user=userToTry)
except:
dbusers = DBUsers.objects.all().filter(user=userToTry)
for it in dbusers:
dbuser = it
break
## Use the meta function from backup utils for future improvements.
databaseXML = Element('database')
if os.path.exists(ProcessUtilities.debugPath):
logging.writeToFile('Creating meta for %s. [IncBackupsControl.py]' % (self.website.domain))
child = SubElement(databaseXML, 'dbName')
child.text = items.dbName
child = SubElement(databaseXML, 'dbUser')
child.text = userToTry
child = SubElement(databaseXML, 'password')
child.text = dbuser.password
databasesXML.append(databaseXML)
metaFileXML.append(databasesXML)
## Get Aliases
aliasesXML = Element('Aliases')
aliases = backupUtilities.getAliases(self.website.domain)
for items in aliases:
child = SubElement(aliasesXML, 'alias')
child.text = items
metaFileXML.append(aliasesXML)
## Finish Alias
## DNS Records XML
try:
dnsRecordsXML = Element("dnsrecords")
dnsRecords = DNS.getDNSRecords(self.website.domain)
for items in dnsRecords:
dnsRecordXML = Element('dnsrecord')
child = SubElement(dnsRecordXML, 'type')
child.text = items.type
child = SubElement(dnsRecordXML, 'name')
child.text = items.name
child = SubElement(dnsRecordXML, 'content')
child.text = items.content
child = SubElement(dnsRecordXML, 'priority')
child.text = str(items.prio)
dnsRecordsXML.append(dnsRecordXML)
metaFileXML.append(dnsRecordsXML)
except BaseException as msg:
logging.statusWriter(self.statusPath, '%s. [158:prepMeta]' % (str(msg)), 1)
## Email accounts XML
try:
emailRecordsXML = Element('emails')
eDomain = eDomains.objects.get(domain=self.website.domain)
emailAccounts = eDomain.eusers_set.all()
for items in emailAccounts:
emailRecordXML = Element('emailAccount')
child = SubElement(emailRecordXML, 'email')
child.text = items.email
child = SubElement(emailRecordXML, 'password')
child.text = items.password
emailRecordsXML.append(emailRecordXML)
metaFileXML.append(emailRecordsXML)
except BaseException as msg:
pass
#logging.statusWriter(self.statusPath, '%s. [warning:179:prepMeta]' % (str(msg)), 1)
## Email meta generated!
def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")
## /home/example.com/backup/backup-example-06-50-03-Thu-Feb-2018/meta.xml -- metaPath
metaPath = '/home/cyberpanel/%s' % (str(randint(1000, 9999)))
xmlpretty = prettify(metaFileXML).encode('ascii', 'ignore')
metaFile = open(metaPath, 'w')
metaFile.write(xmlpretty.decode('utf-8'))
metaFile.close()
os.chmod(metaPath, 0o640)
from plogical.backupUtilities import backupUtilities
status, message, metaPath = backupUtilities.prepareBackupMeta(self.website.domain, None, None, None, 0)
## meta generated
logging.statusWriter(self.statusPath, 'Meta data is ready..', 1)
metaPathNew = '/home/%s/meta.xml' % (self.website.domain)
command = 'mv %s %s' % (metaPath, metaPathNew)
ProcessUtilities.executioner(command)
return 1
if status == 1:
logging.statusWriter(self.statusPath, 'Meta data is ready..', 1)
metaPathNew = '/home/%s/meta.xml' % (self.website.domain)
command = 'mv %s %s' % (metaPath, metaPathNew)
ProcessUtilities.executioner(command)
return 1
else:
logging.statusWriter(self.statusPath, "%s [544][5009]" % (message), 1)
return 0
except BaseException as msg:
logging.statusWriter(self.statusPath, "%s [207][5009]" % (str(msg)), 1)
logging.statusWriter(self.statusPath, "%s [548][5009]" % (str(msg)), 1)
return 0
def backupData(self):
@@ -717,6 +640,7 @@ class IncJobs(multi.Thread):
databases = self.website.databases_set.all()
for items in databases:
if mysqlUtilities.mysqlUtilities.createDatabaseBackup(items.dbName, '/home/cyberpanel') == 0:
return 0
@@ -749,6 +673,7 @@ class IncJobs(multi.Thread):
backupPath = '/home/vmail/%s' % (self.website.domain)
if os.path.exists(backupPath):
if self.backupDestinations == 'local':
if self.localFunction(backupPath, 'email') == 0:
return 0
@@ -796,6 +721,10 @@ class IncJobs(multi.Thread):
if self.backupDestinations == 'local':
command = 'restic init --repo %s --password-file %s' % (self.repoPath, self.passwordFile)
result = ProcessUtilities.outputExecutioner(command)
if os.path.exists(ProcessUtilities.debugPath):
logging.writeToFile(result)
if result.find('config file already exists') == -1:
logging.statusWriter(self.statusPath, result, 1)
@@ -804,6 +733,10 @@ class IncJobs(multi.Thread):
command = 'export PATH=${PATH}:/usr/bin && restic init --repo %s:%s --password-file %s' % (
self.backupDestinations, remotePath, self.passwordFile)
result = ProcessUtilities.outputExecutioner(command)
if os.path.exists(ProcessUtilities.debugPath):
logging.writeToFile(result)
if result.find('config file already exists') == -1:
logging.statusWriter(self.statusPath, result, 1)
else:
@@ -811,9 +744,12 @@ class IncJobs(multi.Thread):
command = 'export AWS_ACCESS_KEY_ID=%s AWS_SECRET_ACCESS_KEY=%s && restic -r s3:s3.amazonaws.com/%s init --password-file %s' % (
key, secret, self.website.domain, self.passwordFile)
result = ProcessUtilities.outputExecutioner(command)
if os.path.exists(ProcessUtilities.debugPath):
logging.writeToFile(result)
if result.find('config file already exists') == -1:
logging.statusWriter(self.statusPath, result, 1)
return 1
logging.statusWriter(self.statusPath,
'Repo %s initiated for %s.' % (self.backupDestinations, self.website.domain), 1)
@@ -840,6 +776,7 @@ Subject: %s
mailUtilities.SendEmail(sender, TO, message)
def createBackup(self):
self.statusPath = self.extraArgs['tempPath']
website = self.extraArgs['website']
self.backupDestinations = self.extraArgs['backupDestinations']
@@ -850,10 +787,34 @@ Subject: %s
### Checking if restic is installed before moving on
command = 'restic'
if ProcessUtilities.outputExecutioner(command).find('restic is a backup program which') == -1:
logging.statusWriter(self.statusPath, 'It seems restic is not installed, for incremental backups to work '
'restic must be installed. You can manually install restic using this '
'guide -> http://go.cyberpanel.net/restic. [5009]', 1)
try:
CentOSPath = '/etc/redhat-release'
if os.path.exists(CentOSPath):
command = 'yum install -y yum-plugin-copr'
ProcessUtilities.executioner(command)
command = 'yum copr enable -y copart/restic'
ProcessUtilities.executioner(command)
command = 'yum install -y restic'
ProcessUtilities.executioner(command)
else:
command = 'apt-get update -y'
ProcessUtilities.executioner(command)
command = 'apt-get install restic -y'
ProcessUtilities.executioner(command)
except:
logging.statusWriter(self.statusPath,
'It seems restic is not installed, for incremental backups to work '
'restic must be installed. You can manually install restic using this '
'guide -> https://go.cyberpanel.net/restic. [5009]', 1)
pass
return 0
## Restic check completed.
@@ -882,6 +843,8 @@ Subject: %s
if self.initiateRepo() == 0:
return 0
if self.prepareBackupMeta() == 0:
return 0
@@ -911,3 +874,38 @@ Subject: %s
'Failed to delete meta file: %s. [IncJobs.createBackup.591]' % str(msg), 1)
logging.statusWriter(self.statusPath, 'Completed', 1)
### Delete Snapshot
def DeleteSnapShot(self, inc_job):
try:
self.statusPath = logging.fileName
job_snapshots = inc_job.jobsnapshots_set.all()
### Fetch the website name from JobSnapshot object and set these variable as they are needed in called functions below
self.website = job_snapshots[0].job.website.domain
self.passwordFile = '/home/%s/%s' % (self.website, self.website)
for job_snapshot in job_snapshots:
## Functions above use the self.jobid varilable to extract information about this snapshot, so this below variable needs to be set
self.jobid = job_snapshot
if self.jobid.destination == 'local':
self.localFunction('none', 'none', 0, 1)
elif self.jobid.destination[:4] == 'sftp':
self.sftpFunction('none', 'none', 0, 1)
else:
self.awsFunction('restore', '', self.jobid.snapshotid, None, 1)
return 1
except BaseException as msg:
logging.statusWriter(self.statusPath, "%s [903:DeleteSnapShot][5009]" % (str(msg)), 1)
return 0

View File

@@ -1,13 +1,13 @@
from django.db import models
from websiteFunctions.models import Websites
from datetime import datetime
class IncJob(models.Model):
website = models.ForeignKey(Websites, on_delete=models.CASCADE)
date = models.DateTimeField(default=datetime.now, blank=True)
class JobSnapshots(models.Model):
job = models.ForeignKey(IncJob, on_delete=models.CASCADE)
type = models.CharField(max_length=300)
@@ -21,10 +21,9 @@ class BackupJob(models.Model):
websiteData = models.IntegerField()
websiteDatabases = models.IntegerField()
websiteDataEmails = models.IntegerField()
retention = models.IntegerField(default=0) # 0 being unlimited retention
class JobSites(models.Model):
job = models.ForeignKey(BackupJob, on_delete=models.CASCADE)
website = models.CharField(max_length=300)

View File

@@ -101,7 +101,7 @@ app.controller('createIncrementalBackups', function ($scope, $http, $timeout) {
function ListInitialDatas(response) {
if (response.data.status === 1) {
$scope.records = JSON.parse(response.data.data);
$scope.records = response.data.data;
} else {
new PNotify({
title: 'Error!',
@@ -240,7 +240,7 @@ app.controller('createIncrementalBackups', function ($scope, $http, $timeout) {
function ListInitialDatas(response) {
$scope.cyberpanelLoading = true;
if (response.data.status === 1) {
$scope.jobs = JSON.parse(response.data.data);
$scope.jobs = response.data.data;
} else {
new PNotify({
title: 'Operation Failed!',
@@ -358,7 +358,7 @@ app.controller('incrementalDestinations', function ($scope, $http) {
function ListInitialDatas(response) {
$scope.cyberpanelLoading = true;
if (response.data.status === 1) {
$scope.records = JSON.parse(response.data.data);
$scope.records = response.data.data;
} else {
new PNotify({
title: 'Operation Failed!',
@@ -599,6 +599,7 @@ app.controller('scheduleBackupInc', function ($scope, $http) {
var data = {
backupDestinations: $scope.backupDest,
backupFreq: $scope.backupFreq,
backupRetention: $scope.backupRetention,
websiteData: $scope.websiteData,
websiteEmails: $scope.websiteEmails,
websiteDatabases: $scope.websiteDatabases,
@@ -621,7 +622,7 @@ app.controller('scheduleBackupInc', function ($scope, $http) {
if (response.data.status === 1) {
new PNotify({
title: 'Success!',
text: 'Destination successfully removed.',
text: 'Operation successful.',
type: 'success'
});
} else {
@@ -668,12 +669,11 @@ app.controller('scheduleBackupInc', function ($scope, $http) {
function ListInitialDatas(response) {
$scope.cyberpanelLoading = true;
if (response.data.status === 1) {
$scope.records = JSON.parse(response.data.data);
var parsed = JSON.parse(response.data.data);
for (var j = 0; j < parsed.length; j++) {
websitesToBeBackedTemp.push(parsed[j].website);
}
let data = response.data.data;
$scope.records = data;
data.forEach(item => {
websitesToBeBackedTemp.push(item.website)
})
} else {
new PNotify({
title: 'Operation Failed!',
@@ -766,7 +766,7 @@ app.controller('scheduleBackupInc', function ($scope, $http) {
function ListInitialDatas(response) {
$scope.cyberpanelLoading = true;
if (response.data.status === 1) {
$scope.websites = JSON.parse(response.data.data);
$scope.websites = response.data.data;
if(response.data.websiteData === 1){
$scope.websiteData = true;
@@ -1074,7 +1074,7 @@ app.controller('restoreRemoteBackupsInc', function ($scope, $http, $timeout) {
function ListInitialDatas(response) {
$scope.cyberpanelLoading = true;
if (response.data.status === 1) {
$scope.records = JSON.parse(response.data.data);
$scope.records = response.data.data;
} else {
new PNotify({
title: 'Error!',

View File

@@ -10,7 +10,7 @@
<div class="container">
<div id="page-title">
<h2>{% trans "Schedule Back up" %} - <a target="_blank" href="http://cyberpanel.net/"
<h2>{% trans "Schedule Back up" %} - <a target="_blank" href="https://cyberpanel.net/"
style="height: 23px;line-height: 21px;"
class="btn btn-border btn-alt border-red btn-link font-red"
title=""><span>{% trans "Remote Backups" %}</span></a></h2>
@@ -50,6 +50,18 @@
</div>
</div>
<div ng-hide="scheduleRetention" class="form-group">
<label class="col-sm-3 control-label">{% trans "Select Backup Retention. Leave 0 for no limit" %}</label>
<div class="col-sm-9">
<div class="number">
<label>
<input ng-model="backupRetention" type="number" value="0">
</label>
</div>
</div>
</div>
<div ng-hide="scheduleFreq" class="form-group">
<label class="col-sm-3 control-label">{% trans "Backup Content" %}</label>
<div class="col-sm-9">

View File

@@ -55,7 +55,7 @@
</div>
<div ng-hide="destination" class="form-group">
<label class="col-sm-3 control-label">{% trans "Password" %}</label>
<label class="col-sm-3 control-label">{% trans "Encrypted Backup Password" %}</label>
<div class="col-sm-6">
<input type="password" name="password" class="form-control" ng-model="password"
required>

View File

@@ -2,24 +2,24 @@ from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^createBackup$', views.createBackup, name='createBackupInc'),
url(r'^restoreRemoteBackups$', views.restoreRemoteBackups, name='restoreRemoteBackupsInc'),
url(r'^backupDestinations$', views.backupDestinations, name='backupDestinationsInc'),
url(r'^addDestination$', views.addDestination, name='addDestinationInc'),
url(r'^populateCurrentRecords$', views.populateCurrentRecords, name='populateCurrentRecordsInc'),
url(r'^removeDestination$', views.removeDestination, name='removeDestinationInc'),
url(r'^fetchCurrentBackups$', views.fetchCurrentBackups, name='fetchCurrentBackupsInc'),
url(r'^submitBackupCreation$', views.submitBackupCreation, name='submitBackupCreationInc'),
url(r'^getBackupStatus$', views.getBackupStatus, name='getBackupStatusInc'),
url(r'^deleteBackup$', views.deleteBackup, name='deleteBackupInc'),
url(r'^fetchRestorePoints$', views.fetchRestorePoints, name='fetchRestorePointsInc'),
url(r'^restorePoint$', views.restorePoint, name='restorePointInc'),
url(r'^scheduleBackups$', views.scheduleBackups, name='scheduleBackupsInc'),
url(r'^submitBackupSchedule$', views.submitBackupSchedule, name='submitBackupScheduleInc'),
url(r'^scheduleDelete$', views.scheduleDelete, name='scheduleDeleteInc'),
url(r'^getCurrentBackupSchedules$', views.getCurrentBackupSchedules, name='getCurrentBackupSchedulesInc'),
url(r'^fetchSites$', views.fetchSites, name='fetchSites'),
url(r'^saveChanges$', views.saveChanges, name='saveChanges'),
url(r'^removeSite$', views.removeSite, name='removeSite'),
url(r'^addWebsite$', views.addWebsite, name='addWebsite'),
url(r'^createBackup$', views.create_backup, name='createBackupInc'),
url(r'^restoreRemoteBackups$', views.restore_remote_backups, name='restoreRemoteBackupsInc'),
url(r'^backupDestinations$', views.backup_destinations, name='backupDestinationsInc'),
url(r'^addDestination$', views.add_destination, name='addDestinationInc'),
url(r'^populateCurrentRecords$', views.populate_current_records, name='populateCurrentRecordsInc'),
url(r'^removeDestination$', views.remove_destination, name='removeDestinationInc'),
url(r'^fetchCurrentBackups$', views.fetch_current_backups, name='fetchCurrentBackupsInc'),
url(r'^submitBackupCreation$', views.submit_backup_creation, name='submitBackupCreationInc'),
url(r'^getBackupStatus$', views.get_backup_status, name='getBackupStatusInc'),
url(r'^deleteBackup$', views.delete_backup, name='deleteBackupInc'),
url(r'^fetchRestorePoints$', views.fetch_restore_points, name='fetchRestorePointsInc'),
url(r'^restorePoint$', views.restore_point, name='restorePointInc'),
url(r'^scheduleBackups$', views.schedule_backups, name='scheduleBackupsInc'),
url(r'^submitBackupSchedule$', views.submit_backup_schedule, name='submitBackupScheduleInc'),
url(r'^scheduleDelete$', views.schedule_delete, name='scheduleDeleteInc'),
url(r'^getCurrentBackupSchedules$', views.get_current_backup_schedules, name='getCurrentBackupSchedulesInc'),
url(r'^fetchSites$', views.fetch_sites, name='fetchSites'),
url(r'^saveChanges$', views.save_changes, name='saveChanges'),
url(r'^removeSite$', views.remove_site, name='removeSite'),
url(r'^addWebsite$', views.add_website, name='addWebsite'),
]

File diff suppressed because it is too large Load Diff

View File

@@ -26,6 +26,7 @@ Webhosting control panel that uses OpenLiteSpeed as web server.
* PHP 7.2
* PHP 7.3
* PHP 7.4
* PHP 8.0
# Installation Instructions

View File

@@ -13,7 +13,7 @@ import json
import threading as multi
import time
import asyncio
from plogical.processUtilities import ProcessUtilities
class SSHServer(multi.Thread):
OKGREEN = '\033[92m'
@@ -24,7 +24,8 @@ class SSHServer(multi.Thread):
@staticmethod
def findSSHPort():
try:
sshData = open('/etc/ssh/sshd_config', 'r').readlines()
sshData = ProcessUtilities.outputExecutioner('cat /etc/ssh/sshd_config').split('\n')
for items in sshData:
if items.find('Port') > -1:

View File

@@ -7,6 +7,8 @@ from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging
from loginSystem.views import loadLoginPage
from random import randint
import os
from plogical.httpProc import httpProc
from plogical.processUtilities import ProcessUtilities
from plogical.firewallUtilities import FirewallUtilities
from firewall.models import FirewallRules
@@ -16,44 +18,32 @@ import plogical.randomPassword
# Create your views here.
def terminal(request):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
password = plogical.randomPassword.generate_pass()
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
verifyPath = "/home/cyberpanel/" + str(randint(100000, 999999))
writeToFile = open(verifyPath, 'w')
writeToFile.write(password)
writeToFile.close()
password = plogical.randomPassword.generate_pass()
## setting up ssh server
path = '/etc/systemd/system/cpssh.service'
curPath = '/usr/local/CyberCP/WebTerminal/cpssh.service'
verifyPath = "/home/cyberpanel/" + str(randint(100000, 999999))
writeToFile = open(verifyPath, 'w')
writeToFile.write(password)
writeToFile.close()
if not os.path.exists(path):
command = 'mv %s %s' % (curPath, path)
ProcessUtilities.executioner(command)
## setting up ssh server
path = '/etc/systemd/system/cpssh.service'
curPath = '/usr/local/CyberCP/WebTerminal/cpssh.service'
command = 'systemctl start cpssh'
ProcessUtilities.executioner(command)
if not os.path.exists(path):
command = 'mv %s %s' % (curPath, path)
ProcessUtilities.executioner(command)
command = 'systemctl start cpssh'
ProcessUtilities.executioner(command)
FirewallUtilities.addRule('tcp', '5678', '0.0.0.0/0')
newFWRule = FirewallRules(name='terminal', proto='tcp', port='5678', ipAddress='0.0.0.0/0')
newFWRule.save()
return render(request, 'WebTerminal/WebTerminal.html', {'verifyPath': verifyPath, 'password': password})
except BaseException as msg:
logging.writeToFile(str(msg))
return redirect(loadLoginPage)
FirewallUtilities.addRule('tcp', '5678', '0.0.0.0/0')
newFWRule = FirewallRules(name='terminal', proto='tcp', port='5678', ipAddress='0.0.0.0/0')
newFWRule.save()
proc = httpProc(request, 'WebTerminal/WebTerminal.html',
{'verifyPath': verifyPath, 'password': password}, 'admin')
return proc.render()
def restart(request):
try:

View File

@@ -4,6 +4,8 @@ import os.path
import sys
import django
from plogical.httpProc import httpProc
sys.path.append('/usr/local/CyberCP')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
django.setup()
@@ -39,43 +41,28 @@ class BackupManager:
def loadBackupHome(self, request=None, userID=None, data=None):
try:
currentACL = ACLManager.loadedACL(userID)
return render(request, 'backup/index.html', currentACL)
proc = httpProc(request, 'backup/index.html', currentACL)
return proc.render()
except BaseException as msg:
return HttpResponse(str(msg))
def backupSite(self, request=None, userID=None, data=None):
try:
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'createBackup') == 0:
return ACLManager.loadError()
websitesName = ACLManager.findAllSites(currentACL, userID)
return render(request, 'backup/backup.html', {'websiteList': websitesName})
except BaseException as msg:
return HttpResponse(str(msg))
currentACL = ACLManager.loadedACL(userID)
websitesName = ACLManager.findAllSites(currentACL, userID)
proc = httpProc(request, 'backup/backup.html', {'websiteList': websitesName}, 'createBackup')
return proc.render()
def gDrive(self, request=None, userID=None, data=None):
try:
currentACL = ACLManager.loadedACL(userID)
admin = Administrator.objects.get(pk=userID)
if ACLManager.currentContextPermission(currentACL, 'createBackup') == 0:
return ACLManager.loadError()
gDriveAcctsList = []
gDriveAccts = admin.gdrive_set.all()
for items in gDriveAccts:
gDriveAcctsList.append(items.name)
websitesName = ACLManager.findAllSites(currentACL, userID)
return render(request, 'backup/googleDrive.html', {'accounts': gDriveAcctsList, 'websites': websitesName})
except BaseException as msg:
return HttpResponse(str(msg))
currentACL = ACLManager.loadedACL(userID)
admin = Administrator.objects.get(pk=userID)
gDriveAcctsList = []
gDriveAccts = admin.gdrive_set.all()
for items in gDriveAccts:
gDriveAcctsList.append(items.name)
websitesName = ACLManager.findAllSites(currentACL, userID)
proc = httpProc(request, 'backup/googleDrive.html', {'accounts': gDriveAcctsList, 'websites': websitesName},
'createBackup')
return proc.render()
def gDriveSetup(self, userID=None, request=None):
try:
@@ -356,32 +343,23 @@ class BackupManager:
return HttpResponse(json_data)
def restoreSite(self, request=None, userID=None, data=None):
try:
currentACL = ACLManager.loadedACL(userID)
path = os.path.join("/home", "backup")
if not os.path.exists(path):
proc = httpProc(request, 'backup/restore.html', None, 'restoreBackup')
return proc.render()
else:
all_files = []
ext = ".tar.gz"
if ACLManager.currentContextPermission(currentACL, 'restoreBackup') == 0:
return ACLManager.loadError()
command = 'sudo chown -R cyberpanel:cyberpanel ' + path
ACLManager.executeCall(command)
path = os.path.join("/home", "backup")
if not os.path.exists(path):
return render(request, 'backup/restore.html')
else:
all_files = []
ext = ".tar.gz"
command = 'sudo chown -R cyberpanel:cyberpanel ' + path
ACLManager.executeCall(command)
files = os.listdir(path)
for filename in files:
if filename.endswith(ext):
all_files.append(filename)
return render(request, 'backup/restore.html', {'backups': all_files})
except BaseException as msg:
return HttpResponse(str(msg))
files = os.listdir(path)
for filename in files:
if filename.endswith(ext):
all_files.append(filename)
proc = httpProc(request, 'backup/restore.html', {'backups': all_files}, 'restoreBackup')
return proc.render()
def getCurrentBackups(self, userID=None, data=None):
try:
@@ -695,16 +673,8 @@ class BackupManager:
return HttpResponse(final_json)
def backupDestinations(self, request=None, userID=None, data=None):
try:
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'addDeleteDestinations') == 0:
return ACLManager.loadError()
return render(request, 'backup/backupDestinations.html', {})
except BaseException as msg:
return HttpResponse(str(msg))
proc = httpProc(request, 'backup/backupDestinations.html', {}, 'addDeleteDestinations')
return proc.render()
def submitDestinationCreation(self, userID=None, data=None):
try:
@@ -726,7 +696,7 @@ class BackupManager:
finalDic['port'] = "22"
try:
finalDic['user'] = data['user']
finalDic['user'] = data['userName']
except:
finalDic['user'] = "root"
@@ -868,31 +838,21 @@ class BackupManager:
return HttpResponse(final_json)
def scheduleBackup(self, request, userID=None, data=None):
try:
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0:
return ACLManager.loadError()
destinations = NormalBackupDests.objects.all()
dests = []
for dest in destinations:
dests.append(dest.name)
websitesName = ACLManager.findAllSites(currentACL, userID)
return render(request, 'backup/backupSchedule.html', {'destinations': dests, 'websites': websitesName})
except BaseException as msg:
return HttpResponse(str(msg))
currentACL = ACLManager.loadedACL(userID)
destinations = NormalBackupDests.objects.all()
dests = []
for dest in destinations:
dests.append(dest.name)
websitesName = ACLManager.findAllSites(currentACL, userID)
proc = httpProc(request, 'backup/backupSchedule.html', {'destinations': dests, 'websites': websitesName},
'scheduleBackups')
return proc.render()
def getCurrentBackupSchedules(self, userID=None, data=None):
try:
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0:
if ACLManager.currentContextPermission(currentACL, 'scheduleBackups') == 0:
return ACLManager.loadErrorJson('fetchStatus', 0)
records = backupSchedules.objects.all()
@@ -926,15 +886,17 @@ class BackupManager:
selectedAccount = data['selectedAccount']
name = data['name']
backupFrequency = data['backupFrequency']
backupRetention = data['backupRetention']
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0:
if ACLManager.currentContextPermission(currentACL, 'scheduleBackups') == 0:
return ACLManager.loadErrorJson('scheduleStatus', 0)
nbd = NormalBackupDests.objects.get(name=selectedAccount)
config = {'frequency': backupFrequency}
config = {'frequency': backupFrequency,
'retention': backupRetention}
nbj = NormalBackupJobs(owner=nbd, name=name, config=json.dumps(config))
nbj.save()
@@ -950,7 +912,7 @@ class BackupManager:
try:
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0:
if ACLManager.currentContextPermission(currentACL, 'scheduleBackups') == 0:
return ACLManager.loadErrorJson('scheduleStatus', 0)
backupDest = data['destLoc']
@@ -1009,16 +971,8 @@ class BackupManager:
return HttpResponse(final_json)
def remoteBackups(self, request, userID=None, data=None):
try:
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'remoteBackups') == 0:
return ACLManager.loadError()
return render(request, 'backup/remoteBackups.html')
except BaseException as msg:
return HttpResponse(str(msg))
proc = httpProc(request, 'backup/remoteBackups.html', None, 'remoteBackups')
return proc.render()
def submitRemoteBackups(self, userID=None, data=None):
try:
@@ -1371,25 +1325,12 @@ class BackupManager:
return HttpResponse(json_data)
def backupLogs(self, request=None, userID=None, data=None):
try:
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
all_files = []
logFiles = BackupJob.objects.all().order_by('-id')
for logFile in logFiles:
all_files.append(logFile.logFile)
return render(request, 'backup/backupLogs.html', {'backups': all_files})
except BaseException as msg:
return HttpResponse(str(msg))
all_files = []
logFiles = BackupJob.objects.all().order_by('-id')
for logFile in logFiles:
all_files.append(logFile.logFile)
proc = httpProc(request, 'backup/backupLogs.html', {'backups': all_files}, 'admin')
return proc.render()
def fetchLogs(self, userID=None, data=None):
try:
@@ -1474,7 +1415,7 @@ class BackupManager:
page = int(str(data['page']).strip('\n'))
if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0:
if ACLManager.currentContextPermission(currentACL, 'scheduleBackups') == 0:
return ACLManager.loadErrorJson('scheduleStatus', 0)
nbd = NormalBackupJobs.objects.get(name=selectedAccount)
@@ -1526,6 +1467,11 @@ class BackupManager:
except:
frequency = 'Never'
try:
retention = config[IncScheduler.retention]
except:
retention = 'Never'
try:
currentStatus = config[IncScheduler.currentStatus]
except:
@@ -1560,7 +1506,7 @@ class BackupManager:
nbd = NormalBackupDests.objects.get(name=selectedAccount)
if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0:
if ACLManager.currentContextPermission(currentACL, 'scheduleBackups') == 0:
return ACLManager.loadErrorJson('scheduleStatus', 0)
allJobs = nbd.normalbackupjobs_set.all()
@@ -1587,7 +1533,7 @@ class BackupManager:
data = json.loads(request.body)
if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0:
if ACLManager.currentContextPermission(currentACL, 'scheduleBackups') == 0:
return ACLManager.loadErrorJson('scheduleStatus', 0)
selectedJob = data['selectedJob']
@@ -1648,7 +1594,7 @@ class BackupManager:
nbj = NormalBackupJobs.objects.get(name=selectedJob)
website = Websites.objects.get(domain=selectedWebsite)
if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0:
if ACLManager.currentContextPermission(currentACL, 'scheduleBackups') == 0:
return ACLManager.loadErrorJson('scheduleStatus', 0)
try:
@@ -1676,14 +1622,16 @@ class BackupManager:
selectedJob = data['selectedJob']
backupFrequency = data['backupFrequency']
backupRetention = data['backupRetention']
nbj = NormalBackupJobs.objects.get(name=selectedJob)
if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0:
if ACLManager.currentContextPermission(currentACL, 'scheduleBackups') == 0:
return ACLManager.loadErrorJson('scheduleStatus', 0)
config = json.loads(nbj.config)
config[IncScheduler.frequency] = backupFrequency
config[IncScheduler.retention] = backupRetention
nbj.config = json.dumps(config)
nbj.save()
@@ -1710,7 +1658,7 @@ class BackupManager:
nbj = NormalBackupJobs.objects.get(name=selectedJob)
if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0:
if ACLManager.currentContextPermission(currentACL, 'scheduleBackups') == 0:
return ACLManager.loadErrorJson('scheduleStatus', 0)
nbj.delete()
@@ -1737,7 +1685,7 @@ class BackupManager:
recordsToShow = int(data['recordsToShow'])
page = int(str(data['page']).strip('\n'))
if ACLManager.currentContextPermission(currentACL, 'scheDuleBackups') == 0:
if ACLManager.currentContextPermission(currentACL, 'scheduleBackups') == 0:
return ACLManager.loadErrorJson('scheduleStatus', 0)
nbj = NormalBackupJobs.objects.get(name=selectedJob)

View File

@@ -1,5 +1,3 @@
from django.db import models
class DBUsers(models.Model):

View File

@@ -6,6 +6,21 @@
app.controller('backupWebsiteControl', function ($scope, $http, $timeout) {
$(document).ready(function () {
$(".destinationHide").hide();
$('#create-backup-select').select2();
});
$('#create-backup-select').on('select2:select', function (e) {
var data = e.params.data;
$scope.websiteToBeBacked = data.text;
$(".destinationHide").show();
getBackupStatus();
populateCurrentRecords();
$scope.destination = false;
$scope.runningBackup = true;
});
$scope.destination = true;
$scope.backupButton = true;
$scope.backupLoading = true;
@@ -43,7 +58,6 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) {
};
function getBackupStatus() {
$scope.backupLoadingBottom = false;
@@ -111,12 +125,10 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) {
};
$scope.destinationSelection = function () {
$scope.backupButton = false;
};
function populateCurrentRecords() {
var websiteToBeBacked = $scope.websiteToBeBacked;
@@ -152,7 +164,6 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) {
};
$scope.createBackup = function () {
var websiteToBeBacked = $scope.websiteToBeBacked;
@@ -189,10 +200,8 @@ app.controller('backupWebsiteControl', function ($scope, $http, $timeout) {
};
$scope.deleteBackup = function (id) {
url = "/backup/deleteBackup";
var data = {
@@ -1238,7 +1247,8 @@ app.controller('googleDrive', function ($scope, $http) {
};
var data = {
selectedAccount: $scope.selectedAccount,
backupFrequency: $scope.backupFrequency
backupFrequency: $scope.backupFrequency,
backupRetention: $scope.backupRetention,
};
dataurl = "/backup/changeAccountFrequencygDrive";
@@ -1645,7 +1655,8 @@ app.controller('scheduleBackup', function ($scope, $http, $window) {
var data = {
selectedAccount: $scope.selectedAccountAdd,
name: $scope.name,
backupFrequency: $scope.backupFrequency
backupFrequency: $scope.backupFrequency,
backupRetention: $scope.backupRetention,
};
dataurl = "/backup/submitBackupSchedule";
@@ -1847,7 +1858,8 @@ app.controller('scheduleBackup', function ($scope, $http, $window) {
};
var data = {
selectedJob: $scope.selectedJob,
backupFrequency: $scope.backupFrequency
backupFrequency: $scope.backupFrequency,
backupRetention: $scope.backupRetention,
};
dataurl = "/backup/changeAccountFrequencyNormal";

View File

@@ -22,14 +22,13 @@
</h3>
<div class="example-box-wrapper">
<form action="/" class="form-horizontal bordered-row">
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Select Website" %} </label>
<div class="col-sm-6">
<select ng-change="fetchDetails()" ng-model="websiteToBeBacked" class="form-control">
<select id="create-backup-select" ng-model="websiteToBeBacked" class="form-control">
{% for items in websiteList %}
<option>{{ items }}</option>
{% endfor %}
@@ -37,7 +36,7 @@
</div>
</div>
<div ng-hide="destination" class="form-group">
<div class="form-group destinationHide">
<label class="col-sm-3 control-label">{% trans "Destination" %}</label>
<div class="col-sm-6">
<select ng-change="destinationSelection()" ng-model="backupDestinations" class="form-control">
@@ -75,7 +74,7 @@
<!---- if Back up is running------>
<div ng-hide="backupButton" class="form-group">
<div class="form-group destinationHide">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button type="button" ng-click="createBackup()" class="btn btn-primary btn-lg btn-block">{% trans "Create Back up" %}</button>

View File

@@ -12,7 +12,7 @@
<div ng-controller="scheduleBackup" class="container">
<div id="page-title">
<h2>{% trans "Schedule Back up" %} - <a target="_blank"
href="http://go.cyberpanel.net/remote-backup"
href="https://go.cyberpanel.net/remote-backup"
style="height: 23px;line-height: 21px; text-decoration: underline"
class="btn btn-border btn-alt border-red btn-link font-red"
title=""><span>{% trans "Remote Backups" %}</span></a>
@@ -24,7 +24,7 @@
<div class="panel-body">
<h3 class="title-hero">
{% trans "Create New Backup Schedule" %} <img ng-hide="cyberPanelLoading"
src="{% static 'images/loading.gif' %}">
src="{% static 'images/loading.gif' %}" alt="cyberPanelLoading">
</h3>
<div class="example-box-wrapper">
@@ -61,6 +61,16 @@
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Select Backup Retention. Leave 0 for no limit" %}</label>
<div class="col-sm-9">
<div class="number">
<label>
<input ng-model="backupRetention" type="number" value="0">
</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
@@ -81,7 +91,7 @@
<div class="panel-body">
<h3 class="title-hero">
{% trans "Manage Existing Back up Schedules" %} <img ng-hide="cyberPanelLoading"
src="{% static 'images/loading.gif' %}">
src="{% static 'images/loading.gif' %}" alt="cyberPanelLoading">
</h3>
<div class="example-box-wrapper">
@@ -133,6 +143,7 @@
<th>Last Run</th>
<th>All Sites</th>
<th>Frequency ({$ currently $})</th>
<th>Retention ({$ currently $})</th>
<th>Current Status</th>
</tr>
</thead>

View File

@@ -69,7 +69,7 @@
{% endif %}
{% if scheDuleBackups or admin %}
{% if scheduleBackups or admin %}
<div class="col-md-3 btn-min-width">
<a href="{% url 'scheduleBackup' %}" title="{% trans 'Schedule Back up' %}" class="tile-box tile-box-shortcut btn-primary">

File diff suppressed because one or more lines are too long

View File

@@ -528,9 +528,9 @@ body #nav-toggle.collapsed span {
width: 100px;
}
.closed-sidebar #header-logo .logo-content-small {
width: 62px;
width: 50px;
margin-left: 0;
left: 0px;
left: 15px;
display: block;
}
.closed-sidebar #header-logo .logo-content-big {

View File

@@ -98,6 +98,23 @@ app.filter('getwebsitename', function () {
};
});
function getWebsiteName(domain){
if (domain !== undefined) {
domain = domain.replace(/-/g, '');
var domainName = domain.split(".");
var finalDomainName = domainName[0];
if (finalDomainName.length > 5) {
finalDomainName = finalDomainName.substring(0, 4);
}
return finalDomainName;
}
}
app.controller('systemStatusInfo', function ($scope, $http, $timeout) {
//getStuff();
@@ -300,8 +317,8 @@ app.controller('adminController', function ($scope, $http, $timeout) {
$('.addDeleteDestinations').hide();
}
if (!Boolean(response.data.scheDuleBackups)) {
$('.scheDuleBackups').hide();
if (!Boolean(response.data.scheduleBackups)) {
$('.scheduleBackups').hide();
}
if (!Boolean(response.data.remoteBackups)) {

View File

@@ -0,0 +1,42 @@
{% extends "baseTemplate/index.html" %}
{% load i18n %}
{% block title %}{% trans "Home - CyberPanel" %}{% endblock %}
{% block content %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div class="container">
<div id="page-title">
<h2>{% trans "Home" %}</h2>
<p>{% trans "Use the tabs to navigate through the control panel." %}</p>
</div>
<!--- Hide statistics for non-admins--->
<div class="mx-10 col-lg-9 panel col-md-push-50">
<div class="panel-body">
<h3 class="content-box-header">
{% trans "Something went wrong..." %}
</h3>
<div class="example-box-wrapper mt-5">
<div class="alert alert-danger">
<h4 class="alert-title">Error</h4>
<p>Error: {{ error_message }}</p>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@@ -4,29 +4,28 @@
{% block content %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<div class="container">
<div id="page-title">
<h2>{% trans "Home" %}</h2>
<p>{% trans "Use the tabs to navigate through the control panel." %}</p>
</div>
<div class="container">
<div id="page-title">
<h2>{% trans "Home" %}</h2>
<p>{% trans "Use the tabs to navigate through the control panel." %}</p>
</div>
<!--- Hide statistics for non-admins--->
<div class="mx-10 col-lg-9 panel col-md-push-50">
<div class="panel-body">
<h3 class="content-box-header">
{% trans "Available Functions" %}
</h3>
<!--- Hide statistics for non-admins--->
<div class="mx-10 col-lg-9 panel col-md-push-50">
<div class="panel-body">
<h3 class="content-box-header">
{% trans "Available Functions" %}
</h3>
<div class="example-box-wrapper mt-5">
<div class="row mx-5">
<div class="col-md-4">
<a href="{% url 'loadUsersHome' %}" title="{% trans 'User Functions' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="example-box-wrapper mt-5">
<div class="row mx-5">
<div class="col-md-4">
<a href="{% url 'loadUsersHome' %}" title="{% trans 'User Functions' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Users" %}
</div>
@@ -34,10 +33,11 @@
<i class="fa fa-users"></i>
</div>
</a>
</div>
</div>
<div class="col-md-4">
<a href="{% url 'loadWebsitesHome' %}" title="{% trans 'Website Functions' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="col-md-4">
<a href="{% url 'loadWebsitesHome' %}" title="{% trans 'Website Functions' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Websites" %}
</div>
@@ -47,8 +47,9 @@
</a>
</div>
<div class="col-md-4">
<a href="{% url 'packagesHome' %}" title="{% trans 'Add/Modify Packages' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="col-md-4">
<a href="{% url 'packagesHome' %}" title="{% trans 'Add/Modify Packages' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Packages" %}
</div>
@@ -56,10 +57,11 @@
<i class="fa fa-cubes"></i>
</div>
</a>
</div>
</div>
<div class="col-md-4">
<a href="{% url 'loadDatabaseHome' %}" title="{% trans 'Database Functions' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="col-md-4">
<a href="{% url 'loadDatabaseHome' %}" title="{% trans 'Database Functions' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Databases" %}
</div>
@@ -67,10 +69,11 @@
<i class="fa fa-database"></i>
</div>
</a>
</div>
</div>
<div class="col-md-4">
<a href="{% url 'dnsHome' %}" title="{% trans 'Control DNS' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="col-md-4">
<a href="{% url 'dnsHome' %}" title="{% trans 'Control DNS' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "DNS" %}
</div>
@@ -78,10 +81,11 @@
<i class="fa fa-sitemap"></i>
</div>
</a>
</div>
</div>
<div class="col-md-4">
<a href="{% url 'loadFTPHome' %}" title="{% trans 'FTP Functions' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="col-md-4">
<a href="{% url 'loadFTPHome' %}" title="{% trans 'FTP Functions' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "FTP" %}
</div>
@@ -91,8 +95,9 @@
</a>
</div>
<div class="col-md-4">
<a href="{% url 'loadBackupHome' %}" title="{% trans 'Back up' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="col-md-4">
<a href="{% url 'loadBackupHome' %}" title="{% trans 'Back up' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Back up" %}
</div>
@@ -100,171 +105,175 @@
<i class="fa fa-clone"></i>
</div>
</a>
</div>
</div>
<div class="col-md-4">
<a href="{% url 'loadEmailHome' %}" title="{% trans 'Emails' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="col-md-4">
<a href="{% url 'loadEmailHome' %}" title="{% trans 'Emails' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Emails" %}
</div>
<div class="tile-content-wrapper">
<i class="fa fa-envelope"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'loadSSLHome' %}" title="{% trans 'SSL' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "SSL" %}
</div>
<div class="tile-content-wrapper">
<i class="fa fa-expeditedssl"></i>
</div>
</a>
</div>
{% if admin %}
<div class="col-md-4">
<a href="{% url 'serverStatusHome' %}" title="{% trans 'Server Status' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Emails" %}
{% trans "Status" %}
</div>
<div class="tile-content-wrapper">
<i class="fa fa-envelope"></i>
<i class="fa fa-server"></i>
</div>
</a>
</div>
</div>
<div class="col-md-4">
<a href="{% url 'loadSSLHome' %}" title="{% trans 'SSL' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="col-md-4">
<a href="{% url 'loadPHPHome' %}" title="{% trans 'PHP Configurations' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "SSL" %}
{% trans "PHP" %}
</div>
<div class="tile-content-wrapper">
<i class="fa fa-expeditedssl"></i>
<i class="fa fa-code"></i>
</div>
</a>
</div>
</div>
{% if admin %}
<div class="col-md-4">
<a href="{% url 'logsHome' %}" title="{% trans 'Logs' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Logs" %}
</div>
<div class="tile-content-wrapper">
<i class="fa fa-file"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'serverStatusHome' %}" title="{% trans 'Server Status' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Status" %}
</div>
<div class="tile-content-wrapper">
<i class="fa fa-server"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'securityHome' %}" title="{% trans 'Security' %}"
class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Security" %}
</div>
<div class="tile-content-wrapper">
<i class="fa fa-shield"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'loadPHPHome' %}" title="{% trans 'PHP Configurations' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "PHP" %}
</div>
<div class="tile-content-wrapper">
<i class="fa fa-code"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'logsHome' %}" title="{% trans 'Logs' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Logs" %}
</div>
<div class="tile-content-wrapper">
<i class="fa fa-file"></i>
</div>
</a>
</div>
<div class="col-md-4">
<a href="{% url 'securityHome' %}" title="{% trans 'Security' %}" class="tile-box tile-box-shortcut btn-primary">
<div class="tile-header">
{% trans "Security" %}
</div>
<div class="tile-content-wrapper">
<i class="fa fa-shield"></i>
</div>
</a>
</div>
{% endif %}
{% endif %}
</div>
</div>
</div>
</div>
</div>
</div>
{% if admin %}
<div ng-controller="homePageStatus" class="">
<div class="mx-10 col-md-2 panel panel-body col-md-pull-50">
<h3 class="content-box-header">
{% trans "Resources" %}
</h3>
<div class="example-box-wrapper">
<div class="row mx-5">
<div class="">
<div class="mb-10">
<h3 class="title-hero clearfix text-center text-muted">
{% trans "CPU Usage" %}
</h3>
<div class="content-box-wrapper">
<div class="row flex">
<div class="align-center">
<div id="redcircle" class="c100 red cpu">
<span>{$ cpuUsage $}%</span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="">
<div class="mb-10">
<h3 class="title-hero clearfix text-center text-muted">
{% trans "Ram Usage" %}
</h3>
<div class="content-box-wrapper">
<div class="row flex">
<div class="align-center">
<div id="greencircle" class="c100 p0 green ram">
<span>{$ ramUsage $}%</span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="">
<div class="mb-10">
<h3 class="title-hero clearfix text-center text-muted">
{% trans "Disk Usage '/'" %}
</h3>
<div class="content-box-wrapper">
<div class="row flex">
<div class="align-center">
<div id="pinkcircle" class="c100 pink disk">
<span>{$ diskUsage $}%</span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% if admin %}
<div ng-controller="homePageStatus" class="">
<div class="mx-10 col-md-2 panel panel-body col-md-pull-50">
<h3 class="content-box-header">
{% trans "Resources" %}
</h3>
<div class="example-box-wrapper">
<div class="row mx-5">
<div class="">
<div class="mb-10">
<h3 class="title-hero clearfix text-center text-muted">
{% trans "CPU Usage" %}
</h3>
<div class="content-box-wrapper">
<div class="row flex">
<div class="align-center">
<div id="redcircle" class="c100 red cpu">
<span>{$ cpuUsage $}%</span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="">
<div class="mb-10">
<h3 class="title-hero clearfix text-center text-muted">
{% trans "Ram Usage" %}
</h3>
<div class="content-box-wrapper">
<div class="row flex">
<div class="align-center">
<div id="greencircle" class="c100 p0 green ram">
<span>{$ ramUsage $}%</span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="">
<div class="mb-10">
<h3 class="title-hero clearfix text-center text-muted">
{% trans "Disk Usage '/'" %}
</h3>
<div class="content-box-wrapper">
<div class="row flex">
<div class="align-center">
<div id="pinkcircle" class="c100 pink disk">
<span>{$ diskUsage $}%</span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endif %}
</div>
{% endif %}
</div>
{% endblock %}

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
from django.shortcuts import render,redirect
from django.http import HttpResponse
from plogical.getSystemInformation import SystemInformation
@@ -16,29 +14,20 @@ from plogical.acl import ACLManager
from manageServices.models import PDNSStatus
from django.views.decorators.csrf import ensure_csrf_cookie
from plogical.processUtilities import ProcessUtilities
from plogical.httpProc import httpProc
# Create your views here.
VERSION = '2.0'
BUILD = 3
VERSION = '2.1'
BUILD = 1
@ensure_csrf_cookie
def renderBase(request):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
admin = 1
else:
admin = 0
cpuRamDisk = SystemInformation.cpuRamDisk()
finaData = {"admin": admin,'ramUsage':cpuRamDisk['ramUsage'],'cpuUsage':cpuRamDisk['cpuUsage'],'diskUsage':cpuRamDisk['diskUsage'] }
return render(request, 'baseTemplate/homePage.html', finaData)
except KeyError:
return redirect(loadLoginPage)
template = 'baseTemplate/homePage.html'
cpuRamDisk = SystemInformation.cpuRamDisk()
finaData = {'ramUsage': cpuRamDisk['ramUsage'], 'cpuUsage': cpuRamDisk['cpuUsage'],
'diskUsage': cpuRamDisk['diskUsage']}
proc = httpProc(request, template, finaData)
return proc.render()
def getAdminStatus(request):
try:
@@ -77,7 +66,8 @@ def getAdminStatus(request):
def getSystemStatus(request):
try:
val = request.session['userID']
currentACL = ACLManager.loadedACL(val)
HTTPData = SystemInformation.getSystemInformation()
json_data = json.dumps(HTTPData)
return HttpResponse(json_data)
@@ -90,47 +80,30 @@ def getLoadAverage(request):
one = loadAverage[0]
two = loadAverage[1]
three = loadAverage[2]
loadAvg = {"one": one, "two": two,"three": three}
json_data = json.dumps(loadAvg)
return HttpResponse(json_data)
@ensure_csrf_cookie
def versionManagment(request):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
## Get latest version
if currentACL['admin'] == 1:
pass
elif currentACL['versionManagement'] == 1:
pass
else:
return ACLManager.loadError()
getVersion = requests.get('https://cyberpanel.net/version.txt')
latest = getVersion.json()
latestVersion = latest['version']
latestBuild = latest['build']
## Get latest version
## Get local version
getVersion = requests.get('https://cyberpanel.net/version.txt')
currentVersion = VERSION
currentBuild = str(BUILD)
latest = getVersion.json()
template = 'baseTemplate/versionManagment.html'
finalData = {'build': currentBuild, 'currentVersion': currentVersion, 'latestVersion': latestVersion,
'latestBuild': latestBuild}
latestVersion = latest['version']
latestBuild = latest['build']
## Get local version
currentVersion = VERSION
currentBuild = str(BUILD)
return render(request, 'baseTemplate/versionManagment.html', {'build': currentBuild,
'currentVersion': currentVersion,
'latestVersion': latestVersion,
'latestBuild': latestBuild})
except KeyError:
return redirect(loadLoginPage)
proc = httpProc(request, template, finalData, 'versionManagement')
return proc.render()
def upgrade(request):
try:
@@ -224,4 +197,4 @@ def upgradeVersion(request):
return HttpResponse("Version upgrade OK.")
except BaseException as msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg))
return HttpResponse(str(msg))
return HttpResponse(str(msg))

View File

@@ -22,6 +22,7 @@ class cliParser:
parser.add_argument('--dkim', help='DKIM Signing')
parser.add_argument('--openBasedir', help='To enable or disable open_basedir protection for domain.')
parser.add_argument('--fileName', help='Complete path to a file that needs to be restored.')
parser.add_argument('--backupPath', help='Backup path to use when generating a backup.')
## Package Arguments.
@@ -69,4 +70,4 @@ class cliParser:
parser.add_argument('--siteTitle', help='Site Title for application installers.')
parser.add_argument('--path', help='Path for application installers.')
return parser.parse_args()
return parser.parse_args()

View File

@@ -1,7 +1,9 @@
#!/usr/local/CyberCP/bin/python
import os,sys
import os, sys
sys.path.append('/usr/local/CyberCP')
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
django.setup()
from inspect import stack
@@ -27,12 +29,19 @@ from plogical.backupSchedule import backupSchedule
# All that we see or seem is but a dream within a dream.
def get_cyberpanel_version():
with open('/usr/local/CyberCP/version.txt') as version:
version_file = version.read()
version = json.loads(str(version_file))
return f"{version['version']}.{version['build']}"
class cyberPanel:
def printStatus(self, operationStatus, errorMessage):
data = json.dumps({'success': operationStatus,
'errorMessage': errorMessage
})
})
print(data)
## Website Functions
@@ -42,10 +51,10 @@ class cyberPanel:
from random import randint
externalApp = "".join(re.findall("[a-zA-Z]+", domainName))[:5] + str(randint(1000, 9999))
phpSelection = 'PHP ' + php
try:
counter = 0
_externalApp=externalApp
_externalApp = externalApp
while True:
tWeb = Websites.objects.get(externalApp=externalApp)
externalApp = '%s%s' % (_externalApp, str(counter))
@@ -55,10 +64,10 @@ class cyberPanel:
time.sleep(2)
result = virtualHostUtilities.createVirtualHost(domainName, email, phpSelection, externalApp, ssl, dkim,
openBasedir, owner, package, 0)
openBasedir, owner, package, 0)
if result[0] == 1:
self.printStatus(1,'None')
self.printStatus(1, 'None')
else:
self.printStatus(0, result[1])
@@ -72,10 +81,11 @@ class cyberPanel:
path = '/home/' + masterDomain + '/public_html/' + domainName
phpSelection = 'PHP ' + php
result = virtualHostUtilities.createDomain(masterDomain, domainName, phpSelection, path, ssl, dkim, openBasedir, owner, 0)
result = virtualHostUtilities.createDomain(masterDomain, domainName, phpSelection, path, ssl, dkim,
openBasedir, owner, 0)
if result[0] == 1:
self.printStatus(1,'None')
self.printStatus(1, 'None')
else:
self.printStatus(0, result[1])
@@ -98,7 +108,7 @@ class cyberPanel:
result = virtualHostUtilities.deleteDomain(childDomain)
if result[0] == 1:
self.printStatus(1,'None')
self.printStatus(1, 'None')
else:
self.printStatus(0, result[1])
@@ -123,13 +133,14 @@ class cyberPanel:
state = "Suspended"
else:
state = "Active"
dic = {'domain': items.domain, 'adminEmail': items.adminEmail,'ipAddress':ipAddress,'admin': items.admin.userName,'package': items.package.packageName,'state':state}
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 + ',' + json.dumps(dic)
json_data = json_data + ']'
final_json = json.dumps(json_data)
@@ -149,14 +160,16 @@ class cyberPanel:
ipData = f.read()
ipAddress = ipData.split('\n', 1)[0]
table = PrettyTable(['ID','Domain', 'IP Address', 'Package', 'Owner', 'State', 'Email'])
table = PrettyTable(['ID', 'Domain', 'IP Address', 'Package', 'Owner', 'State', 'Email'])
for items in websites:
if items.state == 0:
state = "Suspended"
else:
state = "Active"
table.add_row([items.id, items.domain, ipAddress, items.package.packageName, items.admin.userName, state, items.adminEmail])
table.add_row(
[items.id, items.domain, ipAddress, items.package.packageName, items.admin.userName, state,
items.adminEmail])
print(table)
except BaseException as msg:
@@ -174,7 +187,7 @@ class cyberPanel:
result = vhost.changePHP(completePathToConfigFile, phpVersion)
if result[0] == 1:
self.printStatus(1,'None')
self.printStatus(1, 'None')
else:
self.printStatus(0, result[1])
@@ -333,13 +346,22 @@ class cyberPanel:
## Backup Functions
def createBackup(self, virtualHostName):
def createBackup(self, virtualHostName, backupPath=None):
try:
backupLogPath = "/usr/local/lscp/logs/backup_log."+time.strftime("%I-%M-%S-%a-%b-%Y")
# Setup default backup path to /home/<domain name>/backup if not passed in
if backupPath is None:
backupPath = '/home/' + virtualHostName + '/backup'
# remove trailing slash in path
backupPath = backupPath.rstrip("/")
backuptime = time.strftime("%m.%d.%Y_%H-%M-%S")
backupLogPath = "/usr/local/lscp/logs/backup_log." + backuptime
print('Backup logs to be generated in %s' % (backupLogPath))
backupSchedule.createLocalBackup(virtualHostName, backupLogPath)
tempStoragePath = backupPath + '/backup-' + virtualHostName + '-' + backuptime
backupName = 'backup-' + virtualHostName + '-' + backuptime
backupDomain = virtualHostName
backupUtilities.submitBackupCreation(tempStoragePath, backupName, backupPath, backupDomain)
except BaseException as msg:
logger.writeforCLI(str(msg), "Error", stack()[0][3])
@@ -378,7 +400,8 @@ class cyberPanel:
## Packages
def createPackage(self, owner, packageName, diskSpace, bandwidth, emailAccounts, dataBases, ftpAccounts, allowedDomains):
def createPackage(self, owner, packageName, diskSpace, bandwidth, emailAccounts, dataBases, ftpAccounts,
allowedDomains):
try:
admin = Administrator.objects.get(userName=owner)
@@ -422,7 +445,7 @@ class cyberPanel:
'bandwidth': items.bandwidth,
'ftpAccounts ': items.ftpAccounts,
'dataBases': items.dataBases,
'emailAccounts':items.emailAccounts
'emailAccounts': items.emailAccounts
}
if checker == 0:
@@ -445,10 +468,13 @@ class cyberPanel:
records = Package.objects.all()
table = PrettyTable(['Name', 'Domains', 'Disk Space', 'Bandwidth', 'FTP Accounts', 'Databases', 'Email Accounts'])
table = PrettyTable(
['Name', 'Domains', 'Disk Space', 'Bandwidth', 'FTP Accounts', 'Databases', 'Email Accounts'])
for items in records:
table.add_row([items.packageName, items.allowedDomains, items.diskSpace, items.bandwidth, items.ftpAccounts, items.dataBases, items.emailAccounts])
table.add_row(
[items.packageName, items.allowedDomains, items.diskSpace, items.bandwidth, items.ftpAccounts,
items.dataBases, items.emailAccounts])
print(table)
except BaseException as msg:
@@ -575,8 +601,8 @@ class cyberPanel:
for items in records:
dic = {
'email': items.email,
}
'email': items.email,
}
if checker == 0:
json_data = json_data + json.dumps(dic)
@@ -848,7 +874,8 @@ def main():
else:
openBasedir = 0
cyberpanel.createWebsite(args.package, args.owner, args.domainName, args.email, args.php, ssl, dkim, openBasedir)
cyberpanel.createWebsite(args.package, args.owner, args.domainName, args.email, args.php, ssl, dkim,
openBasedir)
elif args.function == "deleteWebsite":
completeCommandExample = 'cyberpanel deleteWebsite --domainName cyberpanel.net'
@@ -1077,8 +1104,6 @@ def main():
print("\n\nPlease enter value for Allowed Child Domains. For example:\n\n" + completeCommandExample + "\n\n")
return
cyberpanel.createPackage(args.owner, args.packageName, args.diskSpace, args.bandwidth, args.emailAccounts,
args.dataBases, args.ftpAccounts, args.allowedDomains)
elif args.function == "deletePackage":
@@ -1325,14 +1350,7 @@ def main():
ProcessUtilities.executioner(command)
elif args.function == 'version' or args.function == 'v' or args.function == 'V':
## Get CurrentVersion
with open('/usr/local/CyberCP/version.txt') as file:
file_contents = file.read()
version = re.search('\d.\d', file_contents)
version = version.group()
build = file_contents[-2:]
build = build[0:1]
currentversion = version + '.' + build
print (currentversion)
print(get_cyberpanel_version())
### User Functions
@@ -1565,6 +1583,5 @@ def main():
wm.installJoomla(1, data)
if __name__ == "__main__":
main()

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
from django.db import models
from websiteFunctions.models import Websites
# Create your models here.
class WPDeployments(models.Model):
owner = models.ForeignKey(Websites, on_delete=models.CASCADE)
config = models.TextField()

View File

@@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
from .cloudManager import CloudManager
import json
from loginSystem.models import Administrator
@@ -14,10 +13,14 @@ def router(request):
controller = data['controller']
serverUserName = data['serverUserName']
admin = Administrator.objects.get(userName=serverUserName)
cm = CloudManager(data, admin)
if serverUserName != 'admin':
return cm.ajaxPre(0, 'Only administrator can access API.')
if admin.api == 0:
return cm.ajaxPre(0, 'API Access Disabled.')
@@ -29,10 +32,44 @@ def router(request):
else:
return cm.verifyLogin(request)[1]
## Debug Log
import os
from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging
from plogical.processUtilities import ProcessUtilities
if os.path.exists(ProcessUtilities.debugPath):
logging.writeToFile('Current controller: %s' % (controller))
##
if controller == 'verifyLogin':
return cm.verifyLogin(request)[1]
elif controller == 'RunServerLevelEmailChecks':
return cm.RunServerLevelEmailChecks()
elif controller == 'DetachCluster':
return cm.DetachCluster()
elif controller == 'DebugCluster':
return cm.DebugCluster()
elif controller == 'CheckMasterNode':
return cm.CheckMasterNode()
elif controller == 'UptimeMonitor':
return cm.UptimeMonitor()
elif controller == 'SyncToMaster':
return cm.SyncToMaster()
elif controller == 'FetchMasterBootStrapStatus':
return cm.FetchMasterBootStrapStatus()
elif controller == 'FetchChildBootStrapStatus':
return cm.FetchChildBootStrapStatus()
elif controller == 'CreatePendingVirtualHosts':
return cm.CreatePendingVirtualHosts()
elif controller == 'BootMaster':
return cm.BootMaster()
elif controller == 'SwitchDNS':
return cm.SwitchDNS()
elif controller == 'BootChild':
return cm.BootChild()
elif controller == 'SetupCluster':
return cm.SetupCluster()
elif controller == 'ReadReport':
return cm.ReadReport()
elif controller == 'ResetEmailConfigurations':
@@ -57,12 +94,46 @@ def router(request):
return cm.getCurrentCloudBackups()
elif controller == 'fetchCloudBackupSettings':
return cm.fetchCloudBackupSettings()
elif controller == 'SubmitCyberPanelUpgrade':
return cm.SubmitCyberPanelUpgrade()
elif controller == 'saveCloudBackupSettings':
return cm.saveCloudBackupSettings()
elif controller == 'deleteCloudBackup':
return cm.deleteCloudBackup()
elif controller == 'SubmitCloudBackupRestore':
return cm.SubmitCloudBackupRestore()
elif controller == 'DeployWordPress':
return cm.DeployWordPress()
elif controller == 'FetchWordPressDetails':
return cm.FetchWordPressDetails()
elif controller == 'AutoLogin':
return cm.AutoLogin()
elif controller == 'DeletePlugins':
return cm.DeletePlugins()
elif controller == 'GetCurrentThemes':
return cm.GetCurrentThemes()
elif controller == 'UpdateThemes':
return cm.UpdateThemes()
elif controller == 'ChangeStateThemes':
return cm.ChangeStateThemes()
elif controller == 'DeleteThemes':
return cm.DeleteThemes()
elif controller == 'GetServerPublicSSHkey':
return cm.GetServerPublicSSHkey()
elif controller == 'SubmitPublicKey':
return cm.SubmitPublicKey()
elif controller == 'UpdateWPSettings':
return cm.UpdateWPSettings()
elif controller == 'GetCurrentPlugins':
return cm.GetCurrentPlugins()
elif controller == 'UpdatePlugins':
return cm.UpdatePlugins()
elif controller == 'ChangeState':
return cm.ChangeState()
elif controller == 'saveWPSettings':
return cm.saveWPSettings()
elif controller == 'WPScan':
return cm.WPScan()
elif controller == 'getCurrentS3Backups':
return cm.getCurrentS3Backups()
elif controller == 'deleteS3Backup':
@@ -205,6 +276,16 @@ def router(request):
return cm.getLogsFromFile(request)
elif controller == 'serverSSL':
return cm.serverSSL(request)
elif controller == 'CreateStaging':
return cm.CreateStaging(request)
elif controller == 'startSync':
return cm.startSync(request)
elif controller == 'SaveAutoUpdateSettings':
return cm.SaveAutoUpdateSettings()
elif controller == 'fetchWPSettings':
return cm.fetchWPSettings()
elif controller == 'updateWPCLI':
return cm.updateWPCLI()
elif controller == 'setupNode':
return cm.setupManager(request)
elif controller == 'fetchManagerTokens':
@@ -348,7 +429,6 @@ def router(request):
cm = CloudManager(None)
return cm.ajaxPre(0, str(msg))
@csrf_exempt
def access(request):
try:
serverUserName = request.GET.get('serverUserName')
@@ -361,6 +441,10 @@ def access(request):
return HttpResponse('API Access Disabled.')
if token == admin.token.lstrip('Basic ').rstrip('='):
try:
del request.session['userID']
except:
pass
request.session['userID'] = admin.pk
from django.shortcuts import redirect
from baseTemplate.views import renderBase

View File

@@ -1,11 +1,10 @@
from django.shortcuts import render
from plogical.processUtilities import ProcessUtilities
import threading as multi
from plogical.acl import ACLManager
import plogical.CyberCPLogFileWriter as logging
from serverStatus.serverStatusUtil import ServerStatusUtil
import os, stat
from plogical.httpProc import httpProc
class ContainerManager(multi.Thread):
defaultConf = """group {groupName}{
@@ -84,14 +83,6 @@ class ContainerManager(multi.Thread):
def renderC(self):
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
data = {}
data['OLS'] = 0
data['notInstalled'] = 0
@@ -99,17 +90,20 @@ class ContainerManager(multi.Thread):
if ProcessUtilities.decideServer() == ProcessUtilities.OLS:
data['OLS'] = 1
data['notInstalled'] = 0
return render(self.request, 'containerization/notAvailable.html', data)
proc = httpProc(self.request, 'containerization/notAvailable.html', data, 'admin')
return proc.render()
elif not ProcessUtilities.containerCheck():
data['OLS'] = 0
data['notInstalled'] = 1
return render(self.request, 'containerization/notAvailable.html', data)
proc = httpProc(self.request, 'containerization/notAvailable.html', data, 'admin')
return proc.render()
else:
if self.data == None:
self.data = {}
self.data['OLS'] = 0
self.data['notInstalled'] = 0
return render(self.request, self.templateName, self.data)
proc = httpProc(self.request, self.templateName, data, 'admin')
return proc.render()
def submitContainerInstall(self):
try:
@@ -165,7 +159,6 @@ class ContainerManager(multi.Thread):
# self.data['classID']) + ' protocol ip prio 10 handle 1: cgroup'
command = 'sudo tc filter add dev eth0 parent 10: protocol ip prio 10 handle 1: cgroup'
#logging.CyberCPLogFileWriter.writeToFile(command)
ProcessUtilities.executioner(command)
self.restartServices()

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -5,7 +5,6 @@ import django
sys.path.append('/usr/local/CyberCP')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
django.setup()
from django.shortcuts import render
from django.http import HttpResponse
import json
from plogical.acl import ACLManager
@@ -16,34 +15,29 @@ from databases.models import Databases, DBMeta
import argparse
from loginSystem.models import Administrator
import plogical.randomPassword as randomPassword
from plogical.httpProc import httpProc
from backup.models import DBUsers
class DatabaseManager:
REMOTE_ACCESS = 'remote_access'
def loadDatabaseHome(self, request = None, userID = None):
try:
return render(request, 'databases/index.html')
except BaseException as msg:
return HttpResponse(str(msg))
template = 'databases/index.html'
proc = httpProc(request, template, None, 'createDatabase')
return proc.render()
def phpMyAdmin(self, request = None, userID = None):
try:
return render(request, 'databases/phpMyAdmin.html')
except BaseException as msg:
return HttpResponse(str(msg))
template = 'databases/phpMyAdmin.html'
proc = httpProc(request, template, None, 'createDatabase')
return proc.render()
def createDatabase(self, request = None, userID = None):
try:
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'createDatabase') == 0:
return ACLManager.loadError()
websitesName = ACLManager.findAllSites(currentACL, userID)
return render(request, 'databases/createDatabase.html', {'websitesList': websitesName})
except BaseException as msg:
return HttpResponse(str(msg))
currentACL = ACLManager.loadedACL(userID)
websitesName = ACLManager.findAllSites(currentACL, userID)
template = 'databases/createDatabase.html'
proc = httpProc(request, template, {'websitesList': websitesName}, 'createDatabase')
return proc.render()
def submitDBCreation(self, userID = None, data = None, rAPI = None):
try:
@@ -84,18 +78,11 @@ class DatabaseManager:
return HttpResponse(json_data)
def deleteDatabase(self, request = None, userID = None):
try:
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'deleteDatabase') == 0:
return ACLManager.loadError()
websitesName = ACLManager.findAllSites(currentACL, userID)
return render(request, 'databases/deleteDatabase.html', {'websitesList': websitesName})
except BaseException as msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg))
return HttpResponse(str(msg))
currentACL = ACLManager.loadedACL(userID)
websitesName = ACLManager.findAllSites(currentACL, userID)
template = 'databases/deleteDatabase.html'
proc = httpProc(request, template, {'websitesList': websitesName}, 'deleteDatabase')
return proc.render()
def fetchDatabases(self, userID = None, data = None):
try:
@@ -171,16 +158,11 @@ class DatabaseManager:
return HttpResponse(json_data)
def listDBs(self, request = None, userID = None):
try:
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'listDatabases') == 0:
return ACLManager.loadError()
websitesName = ACLManager.findAllSites(currentACL, userID)
return render(request, 'databases/listDataBases.html', {'websiteList': websitesName})
except BaseException as msg:
return HttpResponse(str(msg))
currentACL = ACLManager.loadedACL(userID)
AllWebsites = ACLManager.findAllSites(currentACL, userID)
template = 'databases/listDataBases.html'
proc = httpProc(request, template, {'AllWebsites': AllWebsites}, 'listDatabases')
return proc.render()
def changePassword(self, userID = None, data = None):
try:
@@ -269,12 +251,16 @@ class DatabaseManager:
db = Databases.objects.filter(dbUser=userName)
admin = Administrator.objects.get(pk=userID)
if ACLManager.checkOwnership(db[0].website.domain, admin, currentACL) == 1:
pass
else:
return ACLManager.loadErrorJson()
mysqlUtilities.allowRemoteAccess(db[0].dbName, userName, remoteIP)
mysqlUtilities.createDatabase(db[0].dbName, userName, 'cyberpanel', 0, remoteIP)
dbUserInMysql = DBUsers.objects.get(user=userName, host='localhost')
mysqlUtilities.changePassword(userName, dbUserInMysql.password, 1, remoteIP)
metaData = {'remoteIP': remoteIP}

View File

@@ -10,6 +10,10 @@ class Databases(models.Model):
dbName = models.CharField(max_length=50,unique=True)
dbUser = models.CharField(max_length=50)
class DatabasesUsers(models.Model):
owner = models.ForeignKey(Databases, on_delete=models.CASCADE)
username = models.CharField(max_length=50,unique=True)
class DBMeta(models.Model):
database = models.ForeignKey(Databases, on_delete=models.CASCADE)
key = models.CharField(max_length=200)

View File

@@ -6,25 +6,31 @@
/* Java script code to create database */
app.controller('createDatabase', function ($scope, $http) {
$scope.createDatabaseLoading = true;
$scope.dbDetails = true;
$scope.databaseCreationFailed = true;
$scope.databaseCreated = true;
$scope.couldNotConnect = true;
$scope.generatedPasswordView = true;
$(document).ready(function () {
$(".dbDetails").hide();
$(".generatedPasswordDetails").hide();
$('#create-database-select').select2();
});
$('#create-database-select').on('select2:select', function (e) {
var data = e.params.data;
$scope.databaseWebsite = data.text;
$(".dbDetails").show();
$("#domainDatabase").text(getWebsiteName(data.text));
$("#domainUsername").text(getWebsiteName(data.text));
});
$scope.showDetailsBoxes = function () {
$scope.dbDetails = false;
};
}
$scope.createDatabaseLoading = true;
$scope.createDatabase = function () {
$scope.createDatabaseLoading = false;
$scope.dbDetails = false;
$scope.databaseCreationFailed = true;
$scope.databaseCreated = true;
$scope.couldNotConnect = true;
var databaseWebsite = $scope.databaseWebsite;
@@ -65,26 +71,24 @@ app.controller('createDatabase', function ($scope, $http) {
function ListInitialDatas(response) {
if (response.data.createDBStatus == 1) {
if (response.data.createDBStatus === 1) {
$scope.createDatabaseLoading = true;
$scope.dbDetails = false;
$scope.databaseCreationFailed = true;
$scope.databaseCreated = false;
$scope.couldNotConnect = true;
}
else {
new PNotify({
title: 'Success!',
text: 'Database successfully created.',
type: 'success'
});
} else {
$scope.createDatabaseLoading = true;
$scope.dbDetails = false;
$scope.databaseCreationFailed = false;
$scope.databaseCreated = true;
$scope.couldNotConnect = true;
$scope.errorMessage = response.data.error_message;
new PNotify({
title: 'Operation Failed!',
text: response.data.error_message,
type: 'error'
});
}
@@ -96,21 +100,23 @@ app.controller('createDatabase', function ($scope, $http) {
$scope.createDatabaseLoading = true;
$scope.dbDetails = true;
$scope.databaseCreationFailed = true;
$scope.databaseCreated = true;
$scope.couldNotConnect = false;
new PNotify({
title: 'Operation Failed!',
text: 'Could not connect to server, please refresh this page',
type: 'error'
});
}
};
$scope.generatePassword = function () {
$scope.generatedPasswordView = false;
$(".generatedPasswordDetails").show();
$scope.dbPassword = randomPassword(16);
};
$scope.usePassword = function () {
$scope.generatedPasswordView = true;
$(".generatedPasswordDetails").hide();
};
});
@@ -170,9 +176,7 @@ app.controller('deleteDatabase', function ($scope, $http) {
$scope.couldNotConnect = true;
}
else {
} else {
$scope.deleteDatabaseLoading = true;
$scope.fetchedDatabases = true;
$scope.databaseDeletionFailed = false;
@@ -240,9 +244,7 @@ app.controller('deleteDatabase', function ($scope, $http) {
$scope.couldNotConnect = true;
}
else {
} else {
$scope.deleteDatabaseLoading = true;
$scope.fetchedDatabases = true;
$scope.databaseDeletionFailed = false;
@@ -344,8 +346,7 @@ app.controller('listDBs', function ($scope, $http) {
$scope.dbLoading = true;
$scope.domainFeteched = $scope.selectedDomain;
}
else {
} else {
$scope.notificationsBox = false;
$scope.canNotChangePassword = false;
$scope.dbLoading = true;
@@ -411,8 +412,7 @@ app.controller('listDBs', function ($scope, $http) {
$scope.domainFeteched = $scope.selectedDomain;
}
else {
} else {
$scope.recordsFetched = true;
$scope.passwordChanged = true;
$scope.canNotChangePassword = true;
@@ -481,8 +481,7 @@ app.controller('listDBs', function ($scope, $http) {
$scope.dbHost = response.data.dbHost;
}
else {
} else {
new PNotify({
title: 'Operation Failed!',
text: response.data.error_message,
@@ -537,8 +536,7 @@ app.controller('listDBs', function ($scope, $http) {
type: 'success'
});
}
else {
} else {
new PNotify({
title: 'Operation Failed!',
text: response.data.error_message,
@@ -570,7 +568,7 @@ app.controller('listDBs', function ($scope, $http) {
app.controller('phpMyAdmin', function ($scope, $http, $window) {
$scope.cyberPanelLoading = true;
$scope.generateAccess = function() {
$scope.generateAccess = function () {
$scope.cyberPanelLoading = false;
@@ -593,12 +591,14 @@ app.controller('phpMyAdmin', function ($scope, $http, $window) {
if (response.data.status === 1) {
var rUrl = '/phpmyadmin/phpmyadminsignin.php?username=' + response.data.username + '&token=' + response.data.token;
$window.location.href = rUrl;
} else {
}
else {}
}
function cantLoadInitialDatas(response) {$scope.cyberPanelLoading = true;}
function cantLoadInitialDatas(response) {
$scope.cyberPanelLoading = true;
}
}

View File

@@ -25,7 +25,7 @@
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Select Website" %}</label>
<div class="col-sm-6">
<select ng-change="showDetailsBoxes()" ng-model="databaseWebsite" class="form-control">
<select id="create-database-select" ng-model="databaseWebsite" class="form-control">
{% for items in websitesList %}
<option>{{ items }}</option>
{% endfor %}
@@ -35,24 +35,23 @@
<div ng-hide="dbDetails" class="form-group">
<div class="form-group dbDetails">
<label class="col-sm-3 control-label">{% trans "Database Name" %}</label>
<div class="col-sm-6">
<input name="dom" type="text" class="form-control" ng-model="dbName" required>
</div>
<div class="current-pack">{$databaseWebsite|getwebsitename$}_{$ dbName $}</div>
<div class="current-pack"><span id="domainDatabase"></span>_{$ dbName $}</div>
</div>
<div ng-hide="dbDetails" class="form-group">
<div class="form-group dbDetails">
<label class="col-sm-3 control-label">{% trans "User Name" %}</label>
<div class="col-sm-6">
<input type="text" name="email" class="form-control" ng-model="dbUsername" required>
</div>
<div class="current-pack">{$databaseWebsite|getwebsitename$}_{$ dbUsername $}</div>
<div class="current-pack"><span id="domainUsername"></span>_{$ dbUsername $}</div>
</div>
<div ng-hide="dbDetails" class="form-group">
<div class="form-group dbDetails">
<label class="col-sm-3 control-label">{% trans "Password" %}</label>
<div class="col-sm-6">
<input type="password" name="email" class="form-control" ng-model="dbPassword" required>
@@ -62,7 +61,7 @@
</div>
</div>
<div ng-hide="generatedPasswordView" class="form-group">
<div class="form-group generatedPasswordDetails">
<label class="col-sm-3 control-label">{% trans "Generated Password" %}</label>
<div class="col-sm-6">
<input type="text" name="email" class="form-control" ng-model="dbPassword" required>
@@ -73,37 +72,13 @@
</div>
<div ng-hide="dbDetails" class="form-group">
<div class="form-group dbDetails">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button type="button" ng-click="createDatabase()" class="btn btn-primary btn-lg">{% trans "Create Database" %}</button>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<div ng-hide="databaseCreationFailed" class="alert alert-danger">
<p>{% trans "Cannot create database. Error message:" %} {$ errorMessage $}</p>
</div>
<div ng-hide="databaseCreated" class="alert alert-success">
<p>{% trans "Database created successfully." %}</p>
</div>
<div ng-hide="couldNotConnect" class="alert alert-danger">
<p>{% trans "Could not connect to server. Please refresh this page." %}</p>
</div>
</div>
</div>
</form>

View File

@@ -10,7 +10,9 @@
<div class="container">
<div id="page-title">
<h2>{% trans "List Databases" %}</h2>
<h2>{% trans "List Databases" %}
<a class="pull-right btn btn-primary" href="{% url "createDatabase" %}">{% trans "Create Database" %}</a>
</h2>
<p>{% trans "List Databases or change their passwords." %}</p>
</div>
<div ng-controller="listDBs" class="panel">
@@ -26,7 +28,7 @@
<label class="col-sm-3 control-label">{% trans "Select Domain" %}</label>
<div class="col-sm-6">
<select ng-change="fetchDBs()" ng-model="selectedDomain" class="form-control">
{% for items in websiteList %}
{% for items in AllWebsites %}
<option>{{ items }}</option>
{% endfor %}
</select>

View File

@@ -24,12 +24,15 @@
<p>{% trans "Auto-login for PHPMYAdmin is now supported. Click the button below to generate auto-access for PHPMYAdmin" %}</p>
<br>
<a ng-click="generateAccess()" href="#">
<button class="btn btn-primary">Access Now <img ng-hide="cyberPanelLoading" src="{% static 'images/loading.gif' %}"></button>
<button id="phpMyAdminlogin" class="btn btn-primary">Access Now <img ng-hide="cyberPanelLoading" src="{% static 'images/loading.gif' %}"></button>
</a>
</div>
</div>
</div>
<!-- Here we are making the phpmyadmin page autoload in current tab -->
<script type="text/javascript">
$(document).ready(function(){$(function(){$('#phpMyAdminlogin').click();});});
</script>
</div>
{% endblock %}
{% endblock %}

View File

@@ -173,7 +173,12 @@ def generateAccess(request):
try:
GlobalUserDB.objects.get(username=admin.userName).delete()
except:
pass
try:
gbobs = GlobalUserDB.objects.filter(username=admin.userName)
for gbobs in gbobs:
gbobs.delete()
except:
pass
password = randomPassword.generate_pass()
token = randomPassword.generate_pass()

View File

@@ -4,10 +4,10 @@ import errno
import os.path
import sys
import django
sys.path.append('/usr/local/CyberCP')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
django.setup()
from django.shortcuts import render
from django.http import HttpResponse
import json
try:
@@ -24,6 +24,7 @@ import CloudFlare
import re
import plogical.CyberCPLogFileWriter as logging
from plogical.processUtilities import ProcessUtilities
from plogical.httpProc import httpProc
class DNSManager:
defaultNameServersPath = '/home/cyberpanel/defaultNameservers'
@@ -37,29 +38,23 @@ class DNSManager:
self.email = data[0].rstrip('\n')
self.key = data[1].rstrip('\n')
def loadDNSHome(self, request = None, userID = None):
try:
admin = Administrator.objects.get(pk=userID)
return render(request, 'dns/index.html', {"type": admin.type})
except BaseException as msg:
return HttpResponse(str(msg))
admin = Administrator.objects.get(pk=userID)
template = 'dns/index.html'
proc = httpProc(request, template, {"type": admin.type}, 'createDNSZone')
return proc.render()
def createNameserver(self, request = None, userID = None):
try:
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'createNameServer') == 0:
return ACLManager.loadError()
mailUtilities.checkHome()
mailUtilities.checkHome()
if os.path.exists('/home/cyberpanel/powerdns'):
finalData = {"status": 1}
else:
finalData = {"status": 0}
if os.path.exists('/home/cyberpanel/powerdns'):
return render(request, "dns/createNameServer.html", {"status": 1})
else:
return render(request, "dns/createNameServer.html", {"status": 0})
except BaseException as msg:
return HttpResponse(str(msg))
template = 'dns/createNameServer.html'
proc = httpProc(request, template, finalData, 'createNameServer')
return proc.render()
def NSCreation(self, userID = None, data = None):
try:
@@ -118,17 +113,15 @@ class DNSManager:
return HttpResponse(final_json)
def createDNSZone(self, request = None, userID = None):
try:
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'createDNSZone') == 0:
return ACLManager.loadError()
if os.path.exists('/home/cyberpanel/powerdns'):
return render(request, 'dns/createDNSZone.html', {"status": 1})
else:
return render(request, 'dns/createDNSZone.html', {"status": 0})
except BaseException as msg:
return HttpResponse(str(msg))
if os.path.exists('/home/cyberpanel/powerdns'):
finalData = {'status': 1}
else:
finalData = {'status': 0}
template = 'dns/createDNSZone.html'
proc = httpProc(request, template, finalData, 'createDNSZone')
return proc.render()
def zoneCreation(self, userID = None, data = None):
try:
@@ -140,7 +133,7 @@ class DNSManager:
zoneDomain = data['zoneDomain']
newZone = Domains(admin=admin, name=zoneDomain, type="NATIVE")
newZone = Domains(admin=admin, name=zoneDomain, type="MASTER")
newZone.save()
content = "ns1." + zoneDomain + " hostmaster." + zoneDomain + " 1 10800 3600 604800 3600"
@@ -166,21 +159,17 @@ class DNSManager:
return HttpResponse(final_json)
def addDeleteDNSRecords(self, request = None, userID = None):
try:
currentACL = ACLManager.loadedACL(userID)
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'addDeleteRecords') == 0:
return ACLManager.loadError()
if not os.path.exists('/home/cyberpanel/powerdns'):
finalData = {"status": 0}
else:
finalData = {"status": 1}
if not os.path.exists('/home/cyberpanel/powerdns'):
return render(request, 'dns/addDeleteDNSRecords.html', {"status": 0})
domainsList = ACLManager.findAllDomains(currentACL, userID)
return render(request, 'dns/addDeleteDNSRecords.html', {"domainsList": domainsList, "status": 1})
except BaseException as msg:
return HttpResponse(str(msg))
finalData['domainsList'] = ACLManager.findAllDomains(currentACL, userID)
template = 'dns/addDeleteDNSRecords.html'
proc = httpProc(request, template, finalData, 'addDeleteRecords')
return proc.render()
def getCurrentRecordsForDomain(self, userID = None, data = None):
try:
@@ -280,7 +269,7 @@ class DNSManager:
if recordType == "A":
recordContentA = data['recordContentA'] ## IP or ponting value
recordContentA = data['recordContentA'] ## IP or pointing value
if recordName == "@":
value = zoneDomain
@@ -320,7 +309,7 @@ class DNSManager:
else:
value = recordName + "." + zoneDomain
recordContentAAAA = data['recordContentAAAA'] ## IP or ponting value
recordContentAAAA = data['recordContentAAAA'] ## IP or pointing value
DNS.createDNSRecord(zone, value, recordType, recordContentAAAA, 0, ttl)
@@ -335,7 +324,7 @@ class DNSManager:
else:
value = recordName + "." + zoneDomain
recordContentCNAME = data['recordContentCNAME'] ## IP or ponting value
recordContentCNAME = data['recordContentCNAME'] ## IP or pointing value
DNS.createDNSRecord(zone, value, recordType, recordContentCNAME, 0, ttl)
@@ -350,7 +339,7 @@ class DNSManager:
else:
value = recordName + "." + zoneDomain
recordContentSPF = data['recordContentSPF'] ## IP or ponting value
recordContentSPF = data['recordContentSPF'] ## IP or pointing value
DNS.createDNSRecord(zone, value, recordType, recordContentSPF, 0, ttl)
@@ -365,7 +354,7 @@ class DNSManager:
else:
value = recordName + "." + zoneDomain
recordContentTXT = data['recordContentTXT'] ## IP or ponting value
recordContentTXT = data['recordContentTXT'] ## IP or pointing value
DNS.createDNSRecord(zone, value, recordType, recordContentTXT, 0, ttl)
@@ -415,7 +404,7 @@ class DNSManager:
value = recordName
else:
value = recordName + "." + zoneDomain
recordContentCAA = data['recordContentCAA'] ## IP or ponting value
recordContentCAA = data['recordContentCAA'] ## IP or pointing value
DNS.createDNSRecord(zone, value, recordType, recordContentCAA, 0, ttl)
final_dic = {'status': 1, 'add_status': 1, 'error_message': "None"}
@@ -499,22 +488,16 @@ class DNSManager:
return HttpResponse(final_json)
def deleteDNSZone(self, request = None, userID = None):
currentACL = ACLManager.loadedACL(userID)
if not os.path.exists('/home/cyberpanel/powerdns'):
finalData = {"status": 0}
else:
finalData = {"status": 1}
try:
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'deleteZone') == 0:
return ACLManager.loadError()
if not os.path.exists('/home/cyberpanel/powerdns'):
return render(request, 'dns/addDeleteDNSRecords.html', {"status": 0})
domainsList = ACLManager.findAllDomains(currentACL, userID)
return render(request, 'dns/deleteDNSZone.html', {"domainsList": domainsList, "status": 1})
except BaseException as msg:
return HttpResponse(str(msg))
finalData['domainsList'] = ACLManager.findAllDomains(currentACL, userID)
template = 'dns/deleteDNSZone.html'
proc = httpProc(request, template, finalData, 'deleteZone')
return proc.render()
def submitZoneDeletion(self, userID = None, data = None):
try:
@@ -549,46 +532,36 @@ class DNSManager:
return HttpResponse(final_json)
def configureDefaultNameServers(self, request=None, userID=None):
currentACL = ACLManager.loadedACL(userID)
try:
currentACL = ACLManager.loadedACL(userID)
if not os.path.exists('/home/cyberpanel/powerdns'):
data = {"status": 0}
else:
data = {"status": 1}
if currentACL['admin'] == 1:
data['domainsList'] = ACLManager.findAllDomains(currentACL, userID)
if os.path.exists(DNSManager.defaultNameServersPath):
nsData = open(DNSManager.defaultNameServersPath, 'r').readlines()
try:
data['firstNS'] = nsData[0].rstrip('\n')
except:
pass
try:
data['secondNS'] = nsData[1].rstrip('\n')
except:
pass
try:
data['thirdNS'] = nsData[2].rstrip('\n')
except:
pass
try:
data['forthNS'] = nsData[3].rstrip('\n')
except:
pass
else:
return ACLManager.loadError()
if not os.path.exists('/home/cyberpanel/powerdns'):
return render(request, 'dns/addDeleteDNSRecords.html', {"status": 0})
data = {}
data['domainsList'] = ACLManager.findAllDomains(currentACL, userID)
data['status'] = 1
if os.path.exists(DNSManager.defaultNameServersPath):
nsData = open(DNSManager.defaultNameServersPath, 'r').readlines()
try:
data['firstNS'] = nsData[0].rstrip('\n')
except:
pass
try:
data['secondNS'] = nsData[1].rstrip('\n')
except:
pass
try:
data['thirdNS'] = nsData[2].rstrip('\n')
except:
pass
try:
data['forthNS'] = nsData[3].rstrip('\n')
except:
pass
return render(request, 'dns/configureDefaultNameServers.html', data)
except BaseException as msg:
return HttpResponse(str(msg))
template = 'dns/configureDefaultNameServers.html'
proc = httpProc(request, template, data, 'admin')
return proc.render()
def saveNSConfigurations(self, userID = None, data = None):
try:
@@ -615,7 +588,6 @@ class DNSManager:
except:
pass
writeToFile = open(DNSManager.defaultNameServersPath, 'w')
writeToFile.write(nsContent.rstrip('\n'))
writeToFile.close()
@@ -631,35 +603,30 @@ class DNSManager:
return HttpResponse(final_json)
def addDeleteDNSRecordsCloudFlare(self, request = None, userID = None):
try:
currentACL = ACLManager.loadedACL(userID)
if not os.path.exists('/home/cyberpanel/powerdns'):
status = 0
else:
status = 1
admin = Administrator.objects.get(pk=userID)
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'addDeleteRecords') == 0:
return ACLManager.loadError()
CloudFlare = 0
if not os.path.exists('/home/cyberpanel/powerdns'):
return render(request, 'dns/addDeleteDNSRecordsCloudFlare.html', {"status": 0})
cfPath = '%s%s' % (DNS.CFPath, admin.userName)
admin = Administrator.objects.get(pk=userID)
if os.path.exists(cfPath):
CloudFlare = 1
domainsList = ACLManager.findAllDomains(currentACL, userID)
self.admin = admin
self.loadCFKeys()
data = {"domainsList": domainsList, "status": status, 'CloudFlare': CloudFlare, 'cfEmail': self.email,
'cfToken': self.key}
else:
data = {"status": status, 'CloudFlare': CloudFlare}
CloudFlare = 0
cfPath = '%s%s' %(DNS.CFPath, admin.userName)
if os.path.exists(cfPath):
CloudFlare = 1
domainsList = ACLManager.findAllDomains(currentACL, userID)
self.admin = admin
self.loadCFKeys()
return render(request, 'dns/addDeleteDNSRecordsCloudFlare.html',
{"domainsList": domainsList, "status": 1, 'CloudFlare': CloudFlare, 'cfEmail': self.email, 'cfToken': self.key})
else:
return render(request, 'dns/addDeleteDNSRecordsCloudFlare.html', {"status": 1, 'CloudFlare': CloudFlare})
except BaseException as msg:
return HttpResponse(str(msg))
template = 'dns/addDeleteDNSRecordsCloudFlare.html'
proc = httpProc(request, template, data, 'addDeleteRecords')
return proc.render()
def saveCFConfigs(self, userID = None, data = None):
try:
@@ -882,7 +849,7 @@ class DNSManager:
if recordType == "A":
recordContentA = data['recordContentA'] ## IP or ponting value
recordContentA = data['recordContentA'] ## IP or pointing value
if recordName == "@":
value = zoneDomain
@@ -922,7 +889,7 @@ class DNSManager:
else:
value = recordName + "." + zoneDomain
recordContentAAAA = data['recordContentAAAA'] ## IP or ponting value
recordContentAAAA = data['recordContentAAAA'] ## IP or pointing value
DNS.createDNSRecordCloudFlare(cf, zone, value, recordType, recordContentAAAA, 0, ttl)
@@ -937,7 +904,7 @@ class DNSManager:
else:
value = recordName + "." + zoneDomain
recordContentCNAME = data['recordContentCNAME'] ## IP or ponting value
recordContentCNAME = data['recordContentCNAME'] ## IP or pointing value
DNS.createDNSRecordCloudFlare(cf, zone, value, recordType, recordContentCNAME, 0, ttl)
@@ -952,7 +919,7 @@ class DNSManager:
else:
value = recordName + "." + zoneDomain
recordContentSPF = data['recordContentSPF'] ## IP or ponting value
recordContentSPF = data['recordContentSPF'] ## IP or pointing value
DNS.createDNSRecordCloudFlare(cf, zone, value, recordType, recordContentSPF, 0, ttl)
@@ -967,7 +934,7 @@ class DNSManager:
else:
value = recordName + "." + zoneDomain
recordContentTXT = data['recordContentTXT'] ## IP or ponting value
recordContentTXT = data['recordContentTXT'] ## IP or pointing value
DNS.createDNSRecordCloudFlare(cf, zone, value, recordType, recordContentTXT, 0, ttl)
@@ -1017,7 +984,7 @@ class DNSManager:
value = recordName
else:
value = recordName + "." + zoneDomain
recordContentCAA = data['recordContentCAA'] ## IP or ponting value
recordContentCAA = data['recordContentCAA'] ## IP or pointing value
DNS.createDNSRecordCloudFlare(cf, zone, value, recordType, recordContentCAA, 0, ttl)
final_dic = {'status': 1, 'add_status': 1, 'error_message': "None"}

View File

@@ -1,11 +1,8 @@
#!/usr/local/CyberCP/bin/python
import os
import os.path
import sys
import django
import mimetypes
sys.path.append('/usr/local/CyberCP')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
django.setup()
@@ -25,7 +22,7 @@ import requests
from plogical.processUtilities import ProcessUtilities
from serverStatus.serverStatusUtil import ServerStatusUtil
import threading as multi
from plogical.httpProc import httpProc
# Use default socket to connect
class ContainerManager(multi.Thread):
@@ -39,16 +36,8 @@ class ContainerManager(multi.Thread):
self.data = data
def renderDM(self):
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
return render(self.request, self.templateName, self.data)
proc = httpProc(self.request, self.templateName, self.data, 'admin')
return proc.render()
def run(self):
try:
@@ -91,59 +80,54 @@ class ContainerManager(multi.Thread):
logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1)
def createContainer(self, request=None, userID=None, data=None):
client = docker.from_env()
dockerAPI = docker.APIClient()
adminNames = ACLManager.loadAllUsers(userID)
tag = request.GET.get('tag')
image = request.GET.get('image')
tag = tag.split(" (")[0]
if "/" in image:
name = image.split("/")[0] + "." + image.split("/")[1]
else:
name = image
try:
admin = Administrator.objects.get(pk=userID)
if admin.acl.adminStatus != 1:
return ACLManager.loadError()
inspectImage = dockerAPI.inspect_image(image + ":" + tag)
except docker.errors.ImageNotFound:
val = request.session['userID']
admin = Administrator.objects.get(pk=val)
proc = httpProc(request, 'dockerManager/images.html', {"type": admin.type,
'image': image,
'tag': tag})
return proc.render()
client = docker.from_env()
dockerAPI = docker.APIClient()
envList = {};
if 'Env' in inspectImage['Config']:
for item in inspectImage['Config']['Env']:
if '=' in item:
splitedItem = item.split('=', 1)
print(splitedItem)
envList[splitedItem[0]] = splitedItem[1]
else:
envList[item] = ""
adminNames = ACLManager.loadAllUsers(userID)
tag = request.GET.get('tag')
image = request.GET.get('image')
tag = tag.split(" (")[0]
portConfig = {};
if 'ExposedPorts' in inspectImage['Config']:
for item in inspectImage['Config']['ExposedPorts']:
portDef = item.split('/')
portConfig[portDef[0]] = portDef[1]
if "/" in image:
name = image.split("/")[0] + "." + image.split("/")[1]
else:
name = image
if image is None or image is '' or tag is None or tag is '':
return redirect(loadImages)
try:
inspectImage = dockerAPI.inspect_image(image + ":" + tag)
except docker.errors.ImageNotFound:
val = request.session['userID']
admin = Administrator.objects.get(pk=val)
return render(request, 'dockerManager/images.html', {"type": admin.type,
'image': image,
'tag': tag})
Data = {"ownerList": adminNames, "image": image, "name": name, "tag": tag, "portConfig": portConfig,
"envList": envList}
envList = {};
if 'Env' in inspectImage['Config']:
for item in inspectImage['Config']['Env']:
if '=' in item:
splitedItem = item.split('=', 1)
print(splitedItem)
envList[splitedItem[0]] = splitedItem[1]
else:
envList[item] = ""
portConfig = {};
if 'ExposedPorts' in inspectImage['Config']:
for item in inspectImage['Config']['ExposedPorts']:
portDef = item.split('/')
portConfig[portDef[0]] = portDef[1]
if image is None or image is '' or tag is None or tag is '':
return redirect(loadImages)
Data = {"ownerList": adminNames, "image": image, "name": name, "tag": tag, "portConfig": portConfig,
"envList": envList}
return render(request, 'dockerManager/runContainer.html', Data)
except BaseException as msg:
return HttpResponse(str(msg))
template = 'dockerManager/runContainer.html'
proc = httpProc(request, template, Data, 'admin')
return proc.render()
def loadContainerHome(self, request=None, userID=None, data=None):
name = self.name
@@ -196,51 +180,52 @@ class ContainerManager(multi.Thread):
data['memoryUsage'] = 0
data['cpuUsage'] = 0
return render(request, 'dockerManager/viewContainer.html', data)
template = 'dockerManager/viewContainer.html'
proc = httpProc(request, template, data, 'admin')
return proc.render()
def listContainers(self, request=None, userID=None, data=None):
try:
client = docker.from_env()
dockerAPI = docker.APIClient()
client = docker.from_env()
dockerAPI = docker.APIClient()
currentACL = ACLManager.loadedACL(userID)
containers = ACLManager.findAllContainers(currentACL, userID)
currentACL = ACLManager.loadedACL(userID)
containers = ACLManager.findAllContainers(currentACL, userID)
allContainers = client.containers.list()
containersList = []
showUnlistedContainer = True
allContainers = client.containers.list()
containersList = []
showUnlistedContainer = True
# TODO: Add condition to show unlisted Containers only if user has admin level access
# TODO: Add condition to show unlisted Containers only if user has admin level access
unlistedContainers = []
for container in allContainers:
if container.name not in containers:
unlistedContainers.append(container)
unlistedContainers = []
for container in allContainers:
if container.name not in containers:
unlistedContainers.append(container)
if not unlistedContainers:
showUnlistedContainer = False
if not unlistedContainers:
showUnlistedContainer = False
adminNames = ACLManager.loadAllUsers(userID)
adminNames = ACLManager.loadAllUsers(userID)
pages = float(len(containers)) / float(10)
pagination = []
pages = float(len(containers)) / float(10)
pagination = []
if pages <= 1.0:
pages = 1
pagination.append('<li><a href="\#"></a></li>')
else:
pages = ceil(pages)
finalPages = int(pages) + 1
if pages <= 1.0:
pages = 1
pagination.append('<li><a href="\#"></a></li>')
else:
pages = ceil(pages)
finalPages = int(pages) + 1
for i in range(1, finalPages):
pagination.append('<li><a href="\#">' + str(i) + '</a></li>')
for i in range(1, finalPages):
pagination.append('<li><a href="\#">' + str(i) + '</a></li>')
return render(request, 'dockerManager/listContainers.html', {"pagination": pagination,
"unlistedContainers": unlistedContainers,
"adminNames": adminNames,
"showUnlistedContainer": showUnlistedContainer})
except BaseException as msg:
return HttpResponse(str(msg))
template = 'dockerManager/listContainers.html'
proc = httpProc(request, template, {"pagination": pagination,
"unlistedContainers": unlistedContainers,
"adminNames": adminNames,
"showUnlistedContainer": showUnlistedContainer}, 'admin')
return proc.render()
def getContainerLogs(self, userID=None, data=None):
try:
@@ -734,8 +719,6 @@ class ContainerManager(multi.Thread):
def images(self, request=None, userID=None, data=None):
try:
admin = Administrator.objects.get(pk=userID)
if admin.acl.adminStatus != 1:
return ACLManager.loadError()
client = docker.from_env()
dockerAPI = docker.APIClient()
@@ -774,19 +757,15 @@ class ContainerManager(multi.Thread):
except:
continue
return render(request, 'dockerManager/images.html', {"images": images, "test": ''})
template = 'dockerManager/images.html'
proc = httpProc(request, template, {"images": images, "test": ''}, 'admin')
return proc.render()
except BaseException as msg:
return HttpResponse(str(msg))
def manageImages(self, request=None, userID=None, data=None):
try:
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
client = docker.from_env()
dockerAPI = docker.APIClient()
@@ -808,7 +787,9 @@ class ContainerManager(multi.Thread):
except:
continue
return render(request, 'dockerManager/manageImages.html', {"images": images})
template = 'dockerManager/manageImages.html'
proc = httpProc(request, template, {"images": images}, 'admin')
return proc.render()
except BaseException as msg:
return HttpResponse(str(msg))

View File

@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect, HttpResponse
from django.shortcuts import redirect, HttpResponse
from loginSystem.models import Administrator
from loginSystem.views import loadLoginPage
from plogical.httpProc import httpProc
from .container import ContainerManager
from .decorators import preDockerRun
from plogical.acl import ACLManager
@@ -12,7 +13,9 @@ import json
# Create your views here.
# This function checks if user has admin permissions
def dockerPermission(request, userID, context):
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] != 1:
@@ -25,21 +28,22 @@ def dockerPermission(request, userID, context):
@preDockerRun
def loadDockerHome(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
admin = Administrator.objects.get(pk=userID)
return render(request,'dockerManager/index.html',{"type":admin.type})
except KeyError:
return redirect(loadLoginPage)
userID = request.session['userID']
admin = Administrator.objects.get(pk=userID)
template = 'dockerManager/index.html'
proc = httpProc(request, template, {"type": admin.type}, 'admin')
return proc.render()
def installDocker(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager(userID, 'submitInstallDocker')
cm.start()
@@ -57,8 +61,12 @@ def installDocker(request):
def installImage(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.submitInstallImage(userID, json.loads(request.body))
@@ -76,8 +84,13 @@ def viewContainer(request, name):
request.GET['name'] = name
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager(name)
coreResult = cm.loadContainerHome(request, userID)
@@ -90,8 +103,12 @@ def viewContainer(request, name):
def getTags(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.getTags(userID, json.loads(request.body))
@@ -104,9 +121,14 @@ def getTags(request):
@preDockerRun
def delContainer(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.submitContainerDeletion(userID, json.loads(request.body))
@@ -120,8 +142,12 @@ def delContainer(request):
def recreateContainer(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.recreateContainer(userID, json.loads(request.body))
@@ -135,8 +161,12 @@ def recreateContainer(request):
def runContainer(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
return cm.createContainer(request, userID)
@@ -147,9 +177,6 @@ def runContainer(request):
def listContainers(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
cm = ContainerManager()
return cm.listContainers(request, userID)
except KeyError:
@@ -158,9 +185,14 @@ def listContainers(request):
@preDockerRun
def getContainerLogs(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.getContainerLogs(userID, json.loads(request.body))
@@ -172,9 +204,14 @@ def getContainerLogs(request):
@preDockerRun
def submitContainerCreation(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.submitContainerCreation(userID, json.loads(request.body))
@@ -188,8 +225,12 @@ def submitContainerCreation(request):
def getContainerList(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
return cm.getContainerList(userID, json.loads(request.body))
@@ -200,8 +241,12 @@ def getContainerList(request):
def doContainerAction(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.doContainerAction(userID, json.loads(request.body))
@@ -214,8 +259,12 @@ def doContainerAction(request):
def getContainerStatus(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.getContainerStatus(userID, json.loads(request.body))
@@ -228,8 +277,12 @@ def getContainerStatus(request):
def exportContainer(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.exportContainer(request, userID)
@@ -242,8 +295,12 @@ def exportContainer(request):
def saveContainerSettings(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.saveContainerSettings(userID, json.loads(request.body))
@@ -256,8 +313,12 @@ def saveContainerSettings(request):
def getContainerTop(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.getContainerTop(userID, json.loads(request.body))
@@ -270,8 +331,12 @@ def getContainerTop(request):
def assignContainer(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.assignContainer(userID, json.loads(request.body))
@@ -284,8 +349,12 @@ def assignContainer(request):
def searchImage(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.searchImage(userID, json.loads(request.body))
@@ -297,11 +366,8 @@ def searchImage(request):
@preDockerRun
def images(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'images')
if perm: return perm
cm = ContainerManager()
coreResult = cm.images(request, userID)
@@ -313,12 +379,8 @@ def images(request):
def manageImages(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
cm = ContainerManager()
coreResult = cm.manageImages(request, userID)
return coreResult
except KeyError:
return redirect(loadLoginPage)
@@ -327,9 +389,12 @@ def manageImages(request):
def getImageHistory(request):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.getImageHistory(userID, json.loads(request.body))
@@ -342,8 +407,12 @@ def getImageHistory(request):
def removeImage(request):
try:
userID = request.session['userID']
perm = dockerPermission(request, userID, 'loadDockerHome')
if perm: return perm
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson()
cm = ContainerManager()
coreResult = cm.removeImage(userID, json.loads(request.body))

View File

@@ -4,6 +4,7 @@ from loginSystem.views import loadLoginPage
import json
from random import randint
import time
from plogical.httpProc import httpProc
from .models import EmailMarketing, EmailLists, EmailsInList, EmailJobs
from websiteFunctions.models import Websites
from .emailMarketing import emailMarketing as EM
@@ -12,7 +13,6 @@ import smtplib
from .models import SMTPHosts, EmailTemplate
from loginSystem.models import Administrator
from .emACL import emACL
from plogical.CyberCPLogFileWriter import CyberCPLogFileWriter as logging
class EmailMarketingManager:
@@ -21,18 +21,8 @@ class EmailMarketingManager:
self.domain = domain
def emailMarketing(self):
try:
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
return render(self.request, 'emailMarketing/emailMarketing.html')
except KeyError as msg:
return redirect(loadLoginPage)
proc = httpProc(self.request, 'emailMarketing/emailMarketing.html', None, 'admin')
return proc.render()
def fetchUsers(self):
try:
@@ -123,7 +113,8 @@ class EmailMarketingManager:
if emACL.checkIfEMEnabled(admin.userName) == 0:
return ACLManager.loadError()
return render(self.request, 'emailMarketing/createEmailList.html', {'domain': self.domain})
proc = httpProc(self.request, 'emailMarketing/createEmailList.html', {'domain': self.domain})
return proc.render()
except KeyError as msg:
return redirect(loadLoginPage)
@@ -168,6 +159,7 @@ class EmailMarketingManager:
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
admin = Administrator.objects.get(pk=userID)
if ACLManager.checkOwnership(self.domain, admin, currentACL) == 1:
pass
else:
@@ -178,12 +170,15 @@ class EmailMarketingManager:
listNames = emACL.getEmailsLists(self.domain)
return render(self.request, 'emailMarketing/manageLists.html', {'listNames': listNames, 'domain': self.domain})
proc = httpProc(self.request, 'emailMarketing/manageLists.html', {'listNames': listNames, 'domain': self.domain})
return proc.render()
except KeyError as msg:
return redirect(loadLoginPage)
def configureVerify(self):
try:
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
admin = Administrator.objects.get(pk=userID)
@@ -196,7 +191,10 @@ class EmailMarketingManager:
if emACL.checkIfEMEnabled(admin.userName) == 0:
return ACLManager.loadError()
return render(self.request, 'emailMarketing/configureVerify.html', {'domain': self.domain})
proc = httpProc(self.request, 'emailMarketing/configureVerify.html',
{'domain': self.domain})
return proc.render()
except KeyError as msg:
return redirect(loadLoginPage)
@@ -490,7 +488,10 @@ class EmailMarketingManager:
for items in emailLists:
listNames.append(items.listName)
return render(self.request, 'emailMarketing/manageSMTPHosts.html', {'listNames': listNames, 'domain': self.domain})
proc = httpProc(self.request, 'emailMarketing/manageSMTPHosts.html',
{'listNames': listNames, 'domain': self.domain})
return proc.render()
except KeyError as msg:
return redirect(loadLoginPage)
@@ -657,7 +658,9 @@ class EmailMarketingManager:
if emACL.checkIfEMEnabled(admin.userName) == 0:
return ACLManager.loadErrorJson()
return render(self.request, 'emailMarketing/composeMessages.html')
proc = httpProc(self.request, 'emailMarketing/composeMessages.html',
None)
return proc.render()
except KeyError as msg:
return redirect(loadLoginPage)
@@ -709,7 +712,11 @@ class EmailMarketingManager:
Data['templateNames'] = templateNames
Data['hostNames'] = hostNames
Data['listNames'] = listNames
return render(self.request, 'emailMarketing/sendEmails.html', Data)
proc = httpProc(self.request, 'emailMarketing/sendEmails.html',
Data)
return proc.render()
except KeyError as msg:
return redirect(loadLoginPage)

View File

@@ -1,11 +1,8 @@
# -*- coding: utf-8 -*-
from django.shortcuts import render,redirect
from django.shortcuts import redirect
from django.http import HttpResponse
from mailServer.models import Domains, EUsers
# Create your views here.
from loginSystem.models import Administrator
from websiteFunctions.models import Websites
from loginSystem.views import loadLoginPage
import plogical.CyberCPLogFileWriter as logging
@@ -13,31 +10,19 @@ import json
from .models import DomainLimits, EmailLimits
from math import ceil
from postfixSenderPolicy.client import cacheClient
import _thread
from plogical.mailUtilities import mailUtilities
from plogical.virtualHostUtilities import virtualHostUtilities
from random import randint
from plogical.acl import ACLManager
from plogical.processUtilities import ProcessUtilities
# Create your views here.
from plogical.httpProc import httpProc
## Email Policy Server
def emailPolicyServer(request):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
return render(request, 'emailPremium/policyServer.html')
except KeyError:
return redirect(loadLoginPage)
proc = httpProc(request, 'emailPremium/policyServer.html',
None, 'admin')
return proc.render()
def fetchPolicyServerStatus(request):
try:
@@ -129,57 +114,43 @@ def savePolicyServerStatus(request):
## Email Policy Server configs
def listDomains(request):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
websites = DomainLimits.objects.all()
try:
websites = DomainLimits.objects.all()
## Check if Policy Server is installed.
## Check if Policy Server is installed.
command = 'sudo cat /etc/postfix/main.cf'
output = ProcessUtilities.outputExecutioner(command).split('\n')
command = 'sudo cat /etc/postfix/main.cf'
output = ProcessUtilities.outputExecutioner(command).split('\n')
installCheck = 0
installCheck = 0
for items in output:
if items.find('check_policy_service unix:/var/log/policyServerSocket') > -1:
installCheck = 1
break
for items in output:
if items.find('check_policy_service unix:/var/log/policyServerSocket') > -1:
installCheck = 1
break
if installCheck == 0:
proc = httpProc(request, 'emailPremium/listDomains.html', {"installCheck": installCheck}, 'admin')
return proc.render()
if installCheck == 0:
return render(request, 'emailPremium/listDomains.html', {"installCheck": installCheck})
###
###
pages = float(len(websites)) / float(10)
pagination = []
pages = float(len(websites)) / float(10)
pagination = []
if pages <= 1.0:
pages = 1
pagination.append('<li><a href="\#"></a></li>')
else:
pages = ceil(pages)
finalPages = int(pages) + 1
if pages <= 1.0:
pages = 1
pagination.append('<li><a href="\#"></a></li>')
else:
pages = ceil(pages)
finalPages = int(pages) + 1
for i in range(1, finalPages):
pagination.append('<li><a href="\#">' + str(i) + '</a></li>')
for i in range(1, finalPages):
pagination.append('<li><a href="\#">' + str(i) + '</a></li>')
return render(request,'emailPremium/listDomains.html',{"pagination":pagination, "installCheck": installCheck})
except BaseException as msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg))
return HttpResponse("See CyberCP main log file.")
except KeyError:
return redirect(loadLoginPage)
proc = httpProc(request, 'emailPremium/listDomains.html',
{"pagination": pagination, "installCheck": installCheck}, 'admin')
return proc.render()
def getFurtherDomains(request):
try:
@@ -304,57 +275,47 @@ def enableDisableEmailLimits(request):
return HttpResponse(json_data)
def emailLimits(request,domain):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if Websites.objects.filter(domain=domain).exists():
website = Websites.objects.get(domain=domain)
domainEmail = Domains.objects.get(domainOwner=website)
domainLimits = DomainLimits.objects.get(domain=domainEmail)
if currentACL['admin'] == 1:
pass
Data = {}
Data['domain'] = domain
Data['monthlyLimit'] = domainLimits.monthlyLimit
Data['monthlyUsed'] = domainLimits.monthlyUsed
Data['emailAccounts'] = domainEmail.eusers_set.count()
if domainLimits.limitStatus == 1:
Data['limitsOn'] = 1
Data['limitsOff'] = 0
else:
return ACLManager.loadError()
Data['limitsOn'] = 0
Data['limitsOff'] = 1
## Pagination for emails
if Websites.objects.filter(domain=domain).exists():
website = Websites.objects.get(domain=domain)
domainEmail = Domains.objects.get(domainOwner=website)
domainLimits = DomainLimits.objects.get(domain=domainEmail)
pages = float(Data['emailAccounts']) / float(10)
pagination = []
Data = {}
Data['domain'] = domain
Data['monthlyLimit'] = domainLimits.monthlyLimit
Data['monthlyUsed'] = domainLimits.monthlyUsed
Data['emailAccounts'] = domainEmail.eusers_set.count()
if domainLimits.limitStatus == 1:
Data['limitsOn'] = 1
Data['limitsOff'] = 0
else:
Data['limitsOn'] = 0
Data['limitsOff'] = 1
## Pagination for emails
pages = float(Data['emailAccounts']) / float(10)
pagination = []
if pages <= 1.0:
pages = 1
pagination.append('<li><a href="\#"></a></li>')
else:
pages = ceil(pages)
finalPages = int(pages) + 1
for i in range(1, finalPages):
pagination.append('<li><a href="\#">' + str(i) + '</a></li>')
Data['pagination'] = pagination
return render(request, 'emailPremium/emailLimits.html', Data)
if pages <= 1.0:
pages = 1
pagination.append('<li><a href="\#"></a></li>')
else:
return render(request, 'emailPremium/emailLimits.html', {"error":1,"domain": "This domain does not exists"})
except KeyError:
return redirect(loadLoginPage)
pages = ceil(pages)
finalPages = int(pages) + 1
for i in range(1, finalPages):
pagination.append('<li><a href="\#">' + str(i) + '</a></li>')
Data['pagination'] = pagination
proc = httpProc(request, 'emailPremium/emailLimits.html', Data, 'admin')
return proc.render()
else:
proc = httpProc(request, 'emailPremium/emailLimits.html', {"error": 1, "domain": "This domain does not exists"},
'admin')
return proc.render()
def changeDomainLimit(request):
try:
@@ -495,39 +456,29 @@ def enableDisableIndividualEmailLimits(request):
return HttpResponse(json_data)
def emailPage(request, emailAddress):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
Data = {}
Data['emailAddress'] = emailAddress
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
email = EUsers.objects.get(email=emailAddress)
logEntries = email.emaillogs_set.all().count()
Data = {}
Data['emailAddress'] = emailAddress
pages = float(logEntries) / float(10)
pagination = []
email = EUsers.objects.get(email=emailAddress)
logEntries = email.emaillogs_set.all().count()
if pages <= 1.0:
pages = 1
pagination.append('<li><a href="\#"></a></li>')
else:
pages = ceil(pages)
finalPages = int(pages) + 1
pages = float(logEntries) / float(10)
pagination = []
for i in range(1, finalPages):
pagination.append('<li><a href="\#">' + str(i) + '</a></li>')
if pages <= 1.0:
pages = 1
pagination.append('<li><a href="\#"></a></li>')
else:
pages = ceil(pages)
finalPages = int(pages) + 1
Data['pagination'] = pagination
for i in range(1, finalPages):
pagination.append('<li><a href="\#">' + str(i) + '</a></li>')
Data['pagination'] = pagination
return render(request, 'emailPremium/emailPage.html', Data)
except KeyError:
return redirect(loadLoginPage)
proc = httpProc(request, 'emailPremium/emailPage.html', Data, 'admin')
return proc.render()
def getEmailStats(request):
try:
@@ -771,24 +722,14 @@ def flushEmailLogs(request):
### SpamAssassin
def spamAssassinHome(request):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
checkIfSpamAssassinInstalled = 0
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
if mailUtilities.checkIfSpamAssassinInstalled() == 1:
checkIfSpamAssassinInstalled = 1
checkIfSpamAssassinInstalled = 0
if mailUtilities.checkIfSpamAssassinInstalled() == 1:
checkIfSpamAssassinInstalled = 1
return render(request, 'emailPremium/SpamAssassin.html',{'checkIfSpamAssassinInstalled': checkIfSpamAssassinInstalled})
except KeyError:
return redirect(loadLoginPage)
proc = httpProc(request, 'emailPremium/SpamAssassin.html',
{'checkIfSpamAssassinInstalled': checkIfSpamAssassinInstalled}, 'admin')
return proc.render()
def installSpamAssassin(request):
try:
@@ -951,9 +892,6 @@ def fetchSpamAssassinSettings(request):
final_dic = {'fetchStatus': 0, 'error_message': str(msg)}
final_json = json.dumps(final_dic)
return HttpResponse(final_json)
return render(request,'managePHP/editPHPConfig.html')
except KeyError:
return redirect(loadLoginPage)
@@ -1028,19 +966,9 @@ def saveSpamAssassinConfigurations(request):
return HttpResponse(json_data)
def mailQueue(request):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
return render(request, 'emailPremium/mailQueue.html')
except KeyError:
return redirect(loadLoginPage)
proc = httpProc(request, 'emailPremium/mailQueue.html',
None, 'admin')
return proc.render()
def fetchMailQueue(request):
try:
@@ -1176,29 +1104,19 @@ def delete(request):
## MailScanner
def MailScanner(request):
try:
userID = request.session['userID']
currentACL = ACLManager.loadedACL(userID)
checkIfMailScannerInstalled = 0
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
ipAddress = ipData.split('\n', 1)[0]
checkIfMailScannerInstalled = 0
if mailUtilities.checkIfMailScannerInstalled() == 1:
checkIfMailScannerInstalled = 1
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
ipAddress = ipData.split('\n', 1)[0]
if mailUtilities.checkIfMailScannerInstalled() == 1:
checkIfMailScannerInstalled = 1
return render(request, 'emailPremium/MailScanner.html',{'checkIfMailScannerInstalled': checkIfMailScannerInstalled, 'ipAddress': ipAddress})
except KeyError:
return redirect(loadLoginPage)
proc = httpProc(request, 'emailPremium/MailScanner.html',
{'checkIfMailScannerInstalled': checkIfMailScannerInstalled, 'ipAddress': ipAddress}, 'admin')
return proc.render()
def installMailScanner(request):
try:
@@ -1211,6 +1129,16 @@ def installMailScanner(request):
return ACLManager.loadErrorJson()
try:
### Check selinux
if ProcessUtilities.decideDistro() == ProcessUtilities.centos or ProcessUtilities.decideDistro() == ProcessUtilities.cent8:
command = 'sestatus'
result = ProcessUtilities.outputExecutioner(command)
if result.find('disabled') == -1:
final_json = json.dumps({'status': 0, 'error_message': "Disable selinux before installing MailScanner."})
return HttpResponse(final_json)
execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/mailUtilities.py"
execPath = execPath + " installMailScanner"
ProcessUtilities.popenExecutioner(execPath)

View File

@@ -318,6 +318,22 @@ class FileManager:
website = Websites.objects.get(domain=domainName)
self.homePath = '/home/%s' % (domainName)
RemoveOK = 1
command = 'touch %s/hello.txt' % (self.homePath)
result = ProcessUtilities.outputExecutioner(command)
if result.find('No such file or directory') > -1:
RemoveOK = 0
command = 'chattr -R -i %s' % (self.homePath)
ProcessUtilities.executioner(command)
else:
command = 'rm -f %s/hello.txt' % (self.homePath)
ProcessUtilities.executioner(command)
for item in self.data['fileAndFolders']:
if (self.data['path'] + '/' + item).find('..') > -1 or (self.data['path'] + '/' + item).find(
@@ -339,6 +355,10 @@ class FileManager:
command = 'mv %s %s' % (self.returnPathEnclosed(self.data['path'] + '/' + item), trashPath)
ProcessUtilities.executioner(command, website.externalApp)
if RemoveOK == 0:
command = 'chattr -R +i %s' % (self.homePath)
ProcessUtilities.executioner(command)
json_data = json.dumps(finalData)
return HttpResponse(json_data)
@@ -546,12 +566,18 @@ class FileManager:
if self.data['fileName'].find(self.data['home']) == -1 or self.data['fileName'].find('..') > -1:
return self.ajaxPre(0, 'Not allowed to move in this path, please choose location inside home!')
command = 'stat -c "%%a" %s' % (self.returnPathEnclosed(self.data['fileName']))
currentMode = ProcessUtilities.outputExecutioner(command).strip('\n')
command = 'mv ' + tempPath + ' ' + self.returnPathEnclosed(self.data['fileName'])
ProcessUtilities.executioner(command)
command = 'chown %s:%s %s' % (website.externalApp, website.externalApp, self.data['fileName'])
ProcessUtilities.executioner(command)
command = 'chmod %s %s' % (currentMode, self.returnPathEnclosed(self.data['fileName']))
ProcessUtilities.executioner(command)
self.changeOwner(self.data['fileName'])
json_data = json.dumps(finalData)
@@ -711,6 +737,9 @@ class FileManager:
else:
groupName = 'nogroup'
command = 'chown %s:%s /home/%s' % (website.externalApp, website.externalApp, domainName)
ProcessUtilities.popenExecutioner(command)
command = 'chown -R %s:%s /home/%s/public_html/*' % (externalApp, externalApp, domainName)
ProcessUtilities.popenExecutioner(command)

View File

@@ -87,12 +87,16 @@ fileManager.controller('editFileCtrl', function ($scope, $http, $window) {
cm.setValue(response.data.fileContents);
cm.setSize(null, 800);
cm.on("keyup", function (cm, event) {
if (!cm.state.completionActive &&
event.keyCode != 13) {
CodeMirror.commands.autocomplete(cm, null, {completeSingle: false});
}
});
// cm.on("keyup", function (cm, event) {
// if(event.keyCode === 9){
// event.preventDefault();
// event.stopPropagation();
// }
// if (!cm.state.completionActive && event.keyCode === 9) {
// CodeMirror.commands.autocomplete(cm, null, {completeSingle: false});
// }
// });
} else {
$scope.errorMessageEditor = false;

View File

@@ -41,7 +41,7 @@
<nav id="navBar" class="navbar navbar-expand-lg navbar-light bg-light">
<div class="header-logo">
<a href="#"><img src="{% static 'filemanager/images/fileManager.png' %}"> <span style="display: none" id="domainNameInitial">{{ domainName }}</span></a>
<a href="/websites/{{ domainName }}"><img src="{% static 'filemanager/images/fileManager.png' %}"> <span style="display: none" id="domainNameInitial">{{ domainName }}</span></a>
</div>
<!--- second bar ---->

View File

@@ -3,6 +3,9 @@ import os
import os.path
import sys
import django
from plogical.httpProc import httpProc
sys.path.append('/usr/local/CyberCP')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
django.setup()
@@ -11,7 +14,7 @@ from plogical.acl import ACLManager
import plogical.CyberCPLogFileWriter as logging
from plogical.virtualHostUtilities import virtualHostUtilities
import subprocess
from django.shortcuts import HttpResponse, render
from django.shortcuts import HttpResponse, render, redirect
from random import randint
import time
from plogical.firewallUtilities import FirewallUtilities
@@ -31,30 +34,19 @@ class FirewallManager:
self.request = request
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 as msg:
return HttpResponse(str(msg))
proc = httpProc(request, 'firewall/index.html',
None, 'admin')
return proc.render()
def firewallHome(self, request = None, userID = None):
try:
currentACL = ACLManager.loadedACL(userID)
csfPath = '/etc/csf'
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
return render(request, 'firewall/firewall.html')
except BaseException as msg:
return HttpResponse(str(msg))
if os.path.exists(csfPath):
return redirect('/configservercsf/')
else:
proc = httpProc(request, 'firewall/firewall.html',
None, 'admin')
return proc.render()
def getCurrentRules(self, userID = None):
try:
@@ -265,17 +257,9 @@ class FirewallManager:
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 as msg:
return HttpResponse(str(msg))
proc = httpProc(request, 'firewall/secureSSH.html',
None, 'admin')
return proc.render()
def getSSHConfigs(self, userID = None, data = None):
try:
@@ -487,34 +471,26 @@ class FirewallManager:
return HttpResponse(final_json)
def loadModSecurityHome(self, request = None, userID = None):
try:
currentACL = ACLManager.loadedACL(userID)
if ProcessUtilities.decideServer() == ProcessUtilities.OLS:
OLS = 1
confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf")
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
command = "sudo cat " + confPath
httpdConfig = ProcessUtilities.outputExecutioner(command).splitlines()
if ProcessUtilities.decideServer() == ProcessUtilities.OLS:
OLS = 1
confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf")
modSecInstalled = 0
command = "sudo cat " + confPath
httpdConfig = ProcessUtilities.outputExecutioner(command).splitlines()
for items in httpdConfig:
if items.find('module mod_security') > -1:
modSecInstalled = 1
break
else:
OLS = 0
modSecInstalled = 1
modSecInstalled = 0
for items in httpdConfig:
if items.find('module mod_security') > -1:
modSecInstalled = 1
break
else:
OLS = 0
modSecInstalled = 1
return render(request, 'firewall/modSecurity.html', {'modSecInstalled': modSecInstalled, 'OLS': OLS})
except BaseException as msg:
return HttpResponse(str(msg))
proc = httpProc(request, 'firewall/modSecurity.html',
{'modSecInstalled': modSecInstalled, 'OLS': OLS}, 'admin')
return proc.render()
def installModSec(self, userID = None, data = None):
try:
@@ -549,7 +525,6 @@ class FirewallManager:
if installStatus.find("[200]") > -1:
execPath = "/usr/local/CyberCP/bin/python " + virtualHostUtilities.cyberPanel + "/plogical/modSec.py"
execPath = execPath + " installModSecConfigs"
output = ProcessUtilities.outputExecutioner(execPath)
@@ -870,34 +845,24 @@ class FirewallManager:
return HttpResponse(json_data)
def modSecRules(self, request = None, userID = None):
try:
if ProcessUtilities.decideServer() == ProcessUtilities.OLS:
confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf")
currentACL = ACLManager.loadedACL(userID)
command = "sudo cat " + confPath
httpdConfig = ProcessUtilities.outputExecutioner(command).split('\n')
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
modSecInstalled = 0
if ProcessUtilities.decideServer() == ProcessUtilities.OLS:
confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf")
for items in httpdConfig:
if items.find('module mod_security') > -1:
modSecInstalled = 1
break
else:
modSecInstalled = 1
command = "sudo cat " + confPath
httpdConfig = ProcessUtilities.outputExecutioner(command).split('\n')
modSecInstalled = 0
for items in httpdConfig:
if items.find('module mod_security') > -1:
modSecInstalled = 1
break
else:
modSecInstalled = 1
return render(request, 'firewall/modSecurityRules.html', {'modSecInstalled': modSecInstalled})
except BaseException as msg:
return HttpResponse(str(msg))
proc = httpProc(request, 'firewall/modSecurityRules.html',
{'modSecInstalled': modSecInstalled}, 'admin')
return proc.render()
def fetchModSecRules(self, userID = None, data = None):
try:
@@ -994,35 +959,25 @@ class FirewallManager:
return HttpResponse(json_data)
def modSecRulesPacks(self, request = None, userID = None):
try:
if ProcessUtilities.decideServer() == ProcessUtilities.OLS:
currentACL = ACLManager.loadedACL(userID)
confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf")
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
command = "sudo cat " + confPath
httpdConfig = ProcessUtilities.outputExecutioner(command).split('\n')
if ProcessUtilities.decideServer() == ProcessUtilities.OLS:
modSecInstalled = 0
confPath = os.path.join(virtualHostUtilities.Server_root, "conf/httpd_config.conf")
for items in httpdConfig:
if items.find('module mod_security') > -1:
modSecInstalled = 1
break
else:
modSecInstalled = 1
command = "sudo cat " + confPath
httpdConfig = ProcessUtilities.outputExecutioner(command).split('\n')
modSecInstalled = 0
for items in httpdConfig:
if items.find('module mod_security') > -1:
modSecInstalled = 1
break
else:
modSecInstalled = 1
return render(request, 'firewall/modSecurityRulesPacks.html', {'modSecInstalled': modSecInstalled})
except BaseException as msg:
return HttpResponse(msg)
proc = httpProc(request, 'firewall/modSecurityRulesPacks.html',
{'modSecInstalled': modSecInstalled}, 'admin')
return proc.render()
def getOWASPAndComodoStatus(self, userID = None, data = None):
try:
@@ -1299,26 +1254,18 @@ class FirewallManager:
return HttpResponse(json_data)
def csf(self):
csfInstalled = 1
try:
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
csfInstalled = 1
try:
command = 'csf -h'
output = ProcessUtilities.outputExecutioner(command)
if output.find("command not found") > -1:
csfInstalled = 0
except subprocess.CalledProcessError:
command = 'csf -h'
output = ProcessUtilities.outputExecutioner(command)
if output.find("command not found") > -1:
csfInstalled = 0
return render(self.request,'firewall/csf.html', {'csfInstalled' : csfInstalled})
except BaseException as msg:
return HttpResponse(str(msg))
except subprocess.CalledProcessError:
csfInstalled = 0
proc = httpProc(self.request, 'firewall/csf.html',
{'csfInstalled': csfInstalled}, 'admin')
return proc.render()
def installCSF(self):
try:
@@ -1349,7 +1296,6 @@ class FirewallManager:
def installStatusCSF(self):
try:
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
installStatus = ProcessUtilities.outputExecutioner("sudo cat " + CSF.installLogPath)
@@ -1548,45 +1494,35 @@ class FirewallManager:
return HttpResponse(final_json)
def imunify(self):
try:
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
ipAddress = ipData.split('\n', 1)[0]
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
fullAddress = '%s:%s' % (ipAddress, ProcessUtilities.fetchCurrentPort())
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
ipAddress = ipData.split('\n', 1)[0]
data = {}
data['ipAddress'] = fullAddress
fullAddress = '%s:%s' % (ipAddress, ProcessUtilities.fetchCurrentPort())
data['CL'] = 1
data = {}
data['ipAddress'] = fullAddress
if os.path.exists(FirewallManager.imunifyPath):
data['imunify'] = 1
else:
data['imunify'] = 0
if os.path.exists(FirewallManager.CLPath):
data['CL'] = 1
else:
data['CL'] = 0
if os.path.exists(FirewallManager.imunifyPath):
data['imunify'] = 1
else:
data['imunify'] = 0
if data['CL'] == 0:
return render(self.request, 'firewall/notAvailable.html', data)
elif data['imunify'] == 0:
return render(self.request, 'firewall/notAvailable.html', data)
else:
return render(self.request, 'firewall/imunify.html', data)
except BaseException as msg:
return HttpResponse(str(msg))
if data['CL'] == 0:
proc = httpProc(self.request, 'firewall/notAvailable.html',
data, 'admin')
return proc.render()
elif data['imunify'] == 0:
proc = httpProc(self.request, 'firewall/notAvailable.html',
data, 'admin')
return proc.render()
else:
proc = httpProc(self.request, 'firewall/imunify.html',
data, 'admin')
return proc.render()
def submitinstallImunify(self):
try:
@@ -1615,40 +1551,29 @@ class FirewallManager:
logging.CyberCPLogFileWriter.statusWriter(ServerStatusUtil.lswsInstallStatusPath, str(msg) + ' [404].', 1)
def imunifyAV(self):
try:
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
ipAddress = ipData.split('\n', 1)[0]
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadError()
fullAddress = '%s:%s' % (ipAddress, ProcessUtilities.fetchCurrentPort())
ipFile = "/etc/cyberpanel/machineIP"
f = open(ipFile)
ipData = f.read()
ipAddress = ipData.split('\n', 1)[0]
data = {}
data['ipAddress'] = fullAddress
fullAddress = '%s:%s' % (ipAddress, ProcessUtilities.fetchCurrentPort())
if os.path.exists(FirewallManager.imunifyAVPath):
data['imunify'] = 1
else:
data['imunify'] = 0
data = {}
data['ipAddress'] = fullAddress
if os.path.exists(FirewallManager.imunifyAVPath):
data['imunify'] = 1
else:
data['imunify'] = 0
if data['imunify'] == 0:
return render(self.request, 'firewall/notAvailableAV.html', data)
else:
return render(self.request, 'firewall/imunifyAV.html', data)
except BaseException as msg:
return HttpResponse(str(msg))
if data['imunify'] == 0:
proc = httpProc(self.request, 'firewall/notAvailableAV.html',
data, 'admin')
return proc.render()
else:
proc = httpProc(self.request, 'firewall/imunifyAV.html',
data, 'admin')
return proc.render()
def submitinstallImunifyAV(self):
try:

View File

@@ -27,7 +27,7 @@
<p>{% trans "Imunify is now integrated via their new API. You can manage Imunify by clicking below. You can use your server root credentials to access Imunify." %}</p>
<br>
<a target="_blank" href="http://{{ ipAddress }}:8090/imunify">
<a target="_blank" href="/imunify">
<button class="btn btn-primary">Access Now
</button>
</a>

View File

@@ -443,7 +443,6 @@ def enableDisableRuleFile(request):
def csf(request):
try:
userID = request.session['userID']
result = pluginManager.preCSF(request)
if result != 200:
@@ -462,7 +461,6 @@ def csf(request):
def installCSF(request):
try:
userID = request.session['userID']
fm = FirewallManager(request)
return fm.installCSF()
except KeyError:
@@ -470,7 +468,6 @@ def installCSF(request):
def installStatusCSF(request):
try:
userID = request.session['userID']
fm = FirewallManager(request)
return fm.installStatusCSF()
except KeyError:
@@ -478,7 +475,6 @@ def installStatusCSF(request):
def removeCSF(request):
try:
userID = request.session['userID']
fm = FirewallManager(request)
return fm.removeCSF()
except KeyError:
@@ -486,7 +482,6 @@ def removeCSF(request):
def fetchCSFSettings(request):
try:
userID = request.session['userID']
fm = FirewallManager(request)
return fm.fetchCSFSettings()
except KeyError:
@@ -494,7 +489,6 @@ def fetchCSFSettings(request):
def changeStatus(request):
try:
userID = request.session['userID']
result = pluginManager.preChangeStatus(request)
if result != 200:
@@ -513,7 +507,6 @@ def changeStatus(request):
def modifyPorts(request):
try:
userID = request.session['userID']
result = pluginManager.preModifyPorts(request)
if result != 200:
@@ -532,7 +525,6 @@ def modifyPorts(request):
def modifyIPs(request):
try:
userID = request.session['userID']
result = pluginManager.preModifyIPs(request)
if result != 200:

View File

@@ -2,11 +2,14 @@
import os.path
import sys
import django
from plogical.httpProc import httpProc
sys.path.append('/usr/local/CyberCP')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
django.setup()
import json
from django.shortcuts import render,redirect
from django.shortcuts import redirect
from django.http import HttpResponse
try:
from .models import Users
@@ -32,32 +35,26 @@ class FTPManager:
self.extraArgs = extraArgs
def loadFTPHome(self):
try:
val = self.request.session['userID']
return render(self.request, 'ftp/index.html')
except KeyError:
return redirect(loadLoginPage)
proc = httpProc(self.request, 'ftp/index.html',
None, 'createFTPAccount')
return proc.render()
def createFTPAccount(self):
try:
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'createFTPAccount') == 0:
return ACLManager.loadError()
admin = Administrator.objects.get(pk=userID)
admin = Administrator.objects.get(pk=userID)
if not os.path.exists('/home/cyberpanel/pureftpd'):
proc = httpProc(self.request, 'ftp/createFTPAccount.html',
{"status": 0}, 'createFTPAccount')
return proc.render()
if not os.path.exists('/home/cyberpanel/pureftpd'):
return render(self.request, "ftp/createFTPAccount.html", {"status": 0})
websitesName = ACLManager.findAllSites(currentACL, userID)
websitesName = ACLManager.findAllSites(currentACL, userID)
return render(self.request, 'ftp/createFTPAccount.html',
{'websiteList': websitesName, 'admin': admin.userName, "status": 1})
except BaseException as msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg))
return HttpResponse(str(msg))
proc = httpProc(self.request, 'ftp/createFTPAccount.html',
{'websiteList': websitesName, 'OwnerFTP': admin.userName, "status": 1}, 'createFTPAccount')
return proc.render()
def submitFTPCreation(self):
try:
@@ -114,23 +111,19 @@ class FTPManager:
return HttpResponse(json_data)
def deleteFTPAccount(self):
try:
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if not os.path.exists('/home/cyberpanel/pureftpd'):
proc = httpProc(self.request, 'ftp/deleteFTPAccount.html',
{"status": 0}, 'deleteFTPAccount')
return proc.render()
if ACLManager.currentContextPermission(currentACL, 'deleteFTPAccount') == 0:
return ACLManager.loadError()
websitesName = ACLManager.findAllSites(currentACL, userID)
if not os.path.exists('/home/cyberpanel/pureftpd'):
return render(self.request, "ftp/deleteFTPAccount.html", {"status": 0})
websitesName = ACLManager.findAllSites(currentACL, userID)
return render(self.request, 'ftp/deleteFTPAccount.html', {'websiteList': websitesName, "status": 1})
except BaseException as msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg))
return HttpResponse(str(msg))
proc = httpProc(self.request, 'ftp/deleteFTPAccount.html',
{'websiteList': websitesName, "status": 1}, 'deleteFTPAccount')
return proc.render()
def fetchFTPAccounts(self):
try:
@@ -204,22 +197,18 @@ class FTPManager:
return HttpResponse(json_data)
def listFTPAccounts(self):
try:
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
userID = self.request.session['userID']
currentACL = ACLManager.loadedACL(userID)
if ACLManager.currentContextPermission(currentACL, 'listFTPAccounts') == 0:
return ACLManager.loadError()
if not os.path.exists('/home/cyberpanel/pureftpd'):
proc = httpProc(self.request, 'ftp/listFTPAccounts.html',
{"status": 0}, 'listFTPAccounts')
return proc.render()
if not os.path.exists('/home/cyberpanel/pureftpd'):
return render(self.request, "ftp/listFTPAccounts.html", {"status": 0})
websitesName = ACLManager.findAllSites(currentACL, userID)
return render(self.request, 'ftp/listFTPAccounts.html', {'websiteList': websitesName, "status": 1})
except BaseException as msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg))
return HttpResponse(str(msg))
websitesName = ACLManager.findAllSites(currentACL, userID)
proc = httpProc(self.request, 'ftp/listFTPAccounts.html',
{'websiteList': websitesName, "status": 1}, 'listFTPAccounts')
return proc.render()
def getAllFTPAccounts(self):
try:

View File

@@ -6,22 +6,22 @@
/* Java script code to create account */
app.controller('createFTPAccount', function ($scope, $http) {
$(document).ready(function () {
$( ".ftpDetails" ).hide();
$( ".ftpPasswordView" ).hide();
$('.create-ftp-acct-select').select2();
});
$('.create-ftp-acct-select').on('select2:select', function (e) {
var data = e.params.data;
$scope.ftpDomain = data.text;
$( ".ftpDetails" ).show();
});
$scope.ftpLoading = true;
$scope.ftpDetails = true;
$scope.canNotCreate = true;
$scope.successfullyCreated = true;
$scope.couldNotConnect = true;
$scope.showFTPDetails = function () {
$scope.ftpLoading = true;
$scope.ftpDetails = false;
$scope.canNotCreate = true;
$scope.successfullyCreated = true;
$scope.couldNotConnect = true;
};
$scope.createFTPAccount = function () {
@@ -62,37 +62,35 @@ app.controller('createFTPAccount', function ($scope, $http) {
function ListInitialDatas(response) {
if (response.data.creatFTPStatus == 1) {
if (response.data.creatFTPStatus === 1) {
$scope.ftpLoading = true;
$scope.ftpDetails = false;
$scope.canNotCreate = true;
$scope.successfullyCreated = false;
$scope.couldNotConnect = true;
new PNotify({
title: 'Success!',
text: 'FTP account successfully created.',
type: 'success'
});
} else {
$scope.ftpLoading = true;
$scope.ftpDetails = false;
$scope.canNotCreate = false;
$scope.successfullyCreated = true;
$scope.couldNotConnect = true;
$scope.errorMessage = response.data.error_message;
new PNotify({
title: 'Operation Failed!',
text: response.data.error_message,
type: 'error'
});
}
}
function cantLoadInitialDatas(response) {
$scope.ftpLoading = true;
$scope.ftpDetails = false;
$scope.canNotCreate = true;
$scope.successfullyCreated = true;
$scope.couldNotConnect = false;
new PNotify({
title: 'Operation Failed!',
text: 'Could not connect to server, please refresh this page',
type: 'error'
});
}
@@ -109,15 +107,13 @@ app.controller('createFTPAccount', function ($scope, $http) {
///
$scope.generatedPasswordView = true;
$scope.generatePassword = function () {
$scope.generatedPasswordView = false;
$( ".ftpPasswordView" ).show();
$scope.ftpPassword = randomPassword(16);
};
$scope.usePassword = function () {
$scope.generatedPasswordView = true;
$(".ftpPasswordView" ).hide();
};
});

View File

@@ -41,7 +41,7 @@
<div class="form-group">
<label class="col-sm-3 control-label">{% trans "Select Website" %} </label>
<div class="col-sm-6">
<select ng-change="showFTPDetails()" ng-model="ftpDomain" class="form-control">
<select class="create-ftp-acct-select" ng-model="ftpDomain" class="form-control">
{% for items in websiteList %}
<option>{{ items }}</option>
{% endfor %}
@@ -53,17 +53,17 @@
<!------ Modification form that appears after a click --------------->
<div ng-hide="ftpDetails" class="form-group">
<div class="form-group ftpDetails">
<label class="col-sm-3 control-label">{% trans "User Name" %}</label>
<div class="col-sm-6">
<input ng-change="hideFewDetails()" type="text" class="form-control"
ng-model="ftpUserName" required>
</div>
<div class="current-pack">{{ admin }}_{$ ftpUserName $}</div>
<div class="current-pack">{{ OwnerFTP }}_{$ ftpUserName $}</div>
</div>
<div ng-hide="ftpDetails" class="form-group">
<div class="form-group ftpDetails">
<label class="col-sm-3 control-label">{% trans "FTP Password" %}</label>
<div class="col-sm-6">
<input type="password" class="form-control" ng-model="ftpPassword" required>
@@ -74,7 +74,7 @@
</div>
</div>
<div ng-hide="generatedPasswordView" class="form-group">
<div class="form-group ftpPasswordView">
<label class="col-sm-3 control-label">{% trans "Generated Password" %}</label>
<div class="col-sm-6">
<input type="text" name="email" class="form-control" ng-model="ftpPassword"
@@ -86,7 +86,7 @@
</div>
</div>
<div ng-hide="ftpDetails" class="form-group">
<div ng-hide="ftpDetails" class="form-group ftpDetails">
<label class="col-sm-3 control-label">{% trans "Path (Relative)" %}</label>
<div class="col-sm-6">
<input placeholder="{% trans 'Leave empty to select default home directory.' %}"
@@ -98,7 +98,7 @@
<!------ Modification form that appears after a click --------------->
<div ng-hide="ftpDetails" class="form-group">
<div class="form-group dbDetails">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-4">
<button type="button" ng-click="createFTPAccount()"
@@ -106,29 +106,6 @@
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label"></label>
<div class="col-sm-6">
<div ng-hide="canNotCreate" class="alert alert-danger">
<p>{% trans "Cannot create FTP account. Error message:" %} {$ errorMessage
$}</p>
</div>
<div ng-hide="successfullyCreated" class="alert alert-success">
<p>{% trans "FTP Account with username:" %} {$ ftpUserName
$} {% trans "is successfully created." %}</p>
</div>
<div ng-hide="couldNotConnect" class="alert alert-success">
<p>{% trans "FTP Account with username:" %} {$ ftpUserName
$} {% trans "is successfully created." %}</p>
</div>
</div>
</div>
</form>
{% endif %}

0
install/cyberpanel.repo Executable file → Normal file
View File

1
install/cyberso.pub Normal file
View File

@@ -0,0 +1 @@
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDCR0LGYoTUe8ZBhH1D9q/QxbmKzKLQS7TMEyPMCv3NidL+LHy60B5upmflIfIf7oRtyDXWGlH564CFQB8YDnXJBrUgCxpRWtT7MYLWMu9WA8OTtJnGi6r10maLp4RJi7yzuOZ36n+IW/ZdxxVgKgfVeUAtaYXZjrsOLepD4YfXjw4D0MYD7VPcYUdPjRf3m5vClaawvmMtNXh2d2a2BFDJCzX3YgAJdbNe9rJeVrigSWUahU6fPVKxbqEdb7E+l8YIUzNtnpjaxcaaBtLKbc4GiAzLmNOdG01F09/y3GTnHcZJSORLGowioZMpB+T8Q9pvW9lJDSw3k7GbUitpfMHT cloud

View File

@@ -0,0 +1,190 @@
import os
import shutil
import pathlib
import stat
def mkdir_p(path, exist_ok=True):
"""
Creates the directory and paths leading up to it like unix mkdir -p .
Defaults to exist_ok so if it exists were not throwing fatal errors
https://docs.python.org/3.7/library/os.html#os.makedirs
"""
if not os.path.exists(path):
print('creating directory: ' + path)
os.makedirs(path, exist_ok)
def chmod_digit(file_path, perms):
"""
Helper function to chmod like you would in unix without having to preface 0o or converting to octal yourself.
Credits: https://stackoverflow.com/a/60052847/1621381
"""
try:
os.chmod(file_path, int(str(perms), base=8))
except:
print(f'Could not chmod : {file_path} to {perms}')
pass
def touch(filepath: str, exist_ok=True):
"""
Touches a file like unix `touch somefile` would.
"""
try:
pathlib.Path(filepath).touch(exist_ok)
except FileExistsError:
print('Could touch : ' + filepath)
pass
def symlink(src, dst):
"""
Symlink a path to another if the src exists.
"""
try:
if os.access(src, os.R_OK):
os.symlink(src, dst)
except:
print(f'Could not symlink Source: {src} > Destination: {dst}')
pass
def chown(path, user, group=-1):
"""
Chown file/path to user/group provided. Passing -1 to user or group will leave it unchanged.
Useful if just changing user or group vs both.
"""
try:
shutil.chown(path, user, group)
except PermissionError:
print(f'Could not change permissions for: {path} to {user}:{group}')
pass
def recursive_chown(path, owner, group=-1):
"""
Recursively chown a path and contents to owner.
https://docs.python.org/3/library/shutil.html
"""
for dirpath, dirnames, filenames in os.walk(path):
try:
shutil.chown(dirpath, owner, group)
except PermissionError:
print('Could not change permissions for: ' + dirpath + ' to: ' + owner)
pass
for filename in filenames:
try:
shutil.chown(os.path.join(dirpath, filename), owner, group)
except PermissionError:
print('Could not change permissions for: ' + os.path.join(dirpath, filename) + ' to: ' + owner)
pass
def recursive_permissions(path, dir_mode=755, file_mode=644, topdir=True):
"""
Recursively chmod a path and contents to mode.
Defaults to chmod top level directory but can be optionally
toggled off when you want to chmod only contents of like a user's homedir vs homedir itself
https://docs.python.org/3.6/library/os.html#os.walk
"""
# Here we are converting the integers to string and then to octal.
# so this function doesn't need to be called with 0o prefixed for the file and dir mode
dir_mode = int(str(dir_mode), base=8)
file_mode = int(str(file_mode), base=8)
if topdir:
# Set chmod on top level path
try:
os.chmod(path, dir_mode)
except:
print('Could not chmod :' + path + ' to ' + str(dir_mode))
for root, dirs, files in os.walk(path):
for d in dirs:
try:
os.chmod(os.path.join(root, d), dir_mode)
except:
print('Could not chmod :' + os.path.join(root, d) + ' to ' + str(dir_mode))
pass
for f in files:
try:
os.chmod(os.path.join(root, f), file_mode)
except:
print('Could not chmod :' + path + ' to ' + str(file_mode))
pass
# Left intentionally here for reference.
# Set recursive chown for a path
# recursive_chown(my_path, 'root', 'root')
# for changing group recursively without affecting user
# recursive_chown('/usr/local/lscp/cyberpanel/rainloop/data', -1, 'lscpd')
# explicitly set permissions for directories/folders to 0755 and files to 0644
# recursive_permissions(my_path, 755, 644)
# Fix permissions and use default values
# recursive_permissions(my_path)
# =========================================================
# Below is a helper class for getting and working with permissions
# Original credits to : https://github.com/keysemble/perfm
def perm_octal_digit(rwx):
digit = 0
if rwx[0] == 'r':
digit += 4
if rwx[1] == 'w':
digit += 2
if rwx[2] == 'x':
digit += 1
return digit
class FilePerm:
def __init__(self, filepath):
filemode = stat.filemode(os.stat(filepath).st_mode)
permissions = [filemode[-9:][i:i + 3] for i in range(0, len(filemode[-9:]), 3)]
self.filepath = filepath
self.access_dict = dict(zip(['user', 'group', 'other'], [list(perm) for perm in permissions]))
def mode(self):
mode = 0
for shift, digit in enumerate(self.octal()[::-1]):
mode += digit << (shift * 3)
return mode
def digits(self):
"""Get the octal chmod equivalent value 755 in single string"""
return "".join(map(str, self.octal()))
def octal(self):
"""Get the octal value in a list [7, 5, 5]"""
return [perm_octal_digit(p) for p in self.access_dict.values()]
def access_bits(self, access):
if access in self.access_dict.keys():
r, w, x = self.access_dict[access]
return [r == 'r', w == 'w', x == 'x']
def update_bitwise(self, settings):
def perm_list(read=False, write=False, execute=False):
pl = ['-', '-', '-']
if read:
pl[0] = 'r'
if write:
pl[1] = 'w'
if execute:
pl[2] = 'x'
return pl
self.access_dict = dict(
[(access, perm_list(read=r, write=w, execute=x)) for access, [r, w, x] in settings.items()])
os.chmod(self.filepath, self.mode())
# project_directory = os.path.abspath(os.path.dirname(sys.argv[0]))
# home_directory = os.path.expanduser('~')
# print(f'Path: {home_directory} Mode: {FilePerm(home_directory).mode()} Octal: {FilePerm(home_directory).octal()} '
# f'Digits: {FilePerm(home_directory).digits()}')
# Example: Output
# Path: /home/cooluser Mode: 493 Octal: [7, 5, 5] Digits: 755

View File

@@ -14,19 +14,16 @@ from os.path import *
from stat import *
import stat
VERSION = '2.0'
BUILD = 3
VERSION = '2.1'
BUILD = 1
char_set = {'small': 'abcdefghijklmnopqrstuvwxyz',
'nums': '0123456789',
'big': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
}
char_set = {'small': 'abcdefghijklmnopqrstuvwxyz','nums': '0123456789','big': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
def generate_pass(length=14):
chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
size = length
return ''.join(random.choice(chars) for x in range(size))
chars = string.ascii_uppercase + string.ascii_lowercase + string.digits
size = length
return ''.join(random.choice(chars) for x in range(size))
# There can not be peace without first a great suffering.
@@ -56,6 +53,10 @@ def get_distro():
if data.find('CentOS Linux release 8') > -1:
return cent8
if data.find('AlmaLinux release 8') > -1:
return cent8
if data.find('Rocky Linux release 8') > -1:
return cent8
else:
logging.InstallLog.writeToFile("Can't find linux release file - fatal error")
@@ -96,7 +97,8 @@ class preFlightsChecks:
cyberPanelMirror = "mirror.cyberpanel.net/pip"
cdn = 'cyberpanel.sh'
def __init__(self, rootPath, ip, path, cwd, cyberPanelPath, distro, remotemysql = None , mysqlhost = None, mysqldb = None, mysqluser = None, mysqlpassword = None, mysqlport = None):
def __init__(self, rootPath, ip, path, cwd, cyberPanelPath, distro, remotemysql=None, mysqlhost=None, mysqldb=None,
mysqluser=None, mysqlpassword=None, mysqlport=None):
self.ipAddr = ip
self.path = path
self.cwd = cwd
@@ -276,12 +278,11 @@ class preFlightsChecks:
if self.distro == ubuntu:
self.stdOut("Add Cyberpanel user")
command = 'adduser --disabled-login --gecos "" cyberpanel'
preFlightsChecks.call(command, self.distro, command,command,1, 1, os.EX_OSERR)
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
else:
command = "useradd -s /bin/false cyberpanel"
preFlightsChecks.call(command, self.distro, command,command,1, 1, os.EX_OSERR)
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
###############################
@@ -292,21 +293,21 @@ class preFlightsChecks:
else:
command = "adduser docker"
preFlightsChecks.call(command, self.distro, command,command,1, 0, os.EX_OSERR)
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
command = 'groupadd docker'
preFlightsChecks.call(command, self.distro, command,command,1, 0, os.EX_OSERR)
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
command = 'usermod -aG docker docker'
preFlightsChecks.call(command, self.distro, command,command,1, 0, os.EX_OSERR)
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
command = 'usermod -aG docker cyberpanel'
preFlightsChecks.call(command, self.distro, command,command,1, 0, os.EX_OSERR)
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
###
command = "mkdir -p /etc/letsencrypt/live/"
preFlightsChecks.call(command, self.distro, command,command,1, 0, os.EX_OSERR)
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
except BaseException as msg:
logging.InstallLog.writeToFile("[ERROR] setup_account_cyberpanel. " + str(msg))
@@ -391,6 +392,24 @@ class preFlightsChecks:
### Put correct mysql passwords in settings file!
# This allows root/sudo users to be able to work with MySQL/MariaDB without hunting down the password like
# all the other control panels allow
# reference: https://oracle-base.com/articles/mysql/mysql-password-less-logins-using-option-files
mysql_my_root_cnf = '/root/.my.cnf'
mysql_root_cnf_content = """
[client]
user=root
password="%s"
""" % password
with open(mysql_my_root_cnf, 'w') as f:
f.write(mysql_root_cnf_content)
os.chmod(mysql_my_root_cnf, 0o600)
command = 'chown root:root %s' % mysql_my_root_cnf
subprocess.call(shlex.split(command))
logging.InstallLog.writeToFile("Updating /root/.my.cnf!")
logging.InstallLog.writeToFile("Updating settings.py!")
path = self.cyberPanelPath + "/CyberCP/settings.py"
@@ -446,12 +465,12 @@ class preFlightsChecks:
command = "sed -i 's|root|%s|g' %s" % (self.mysqluser, path)
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
command = "sed -i 's|'PORT':''|'PORT':'%s'|g' %s" % (self.mysqlport, path)
command = "sed -i \"s|'PORT': ''|'PORT':'%s'|g\" %s" % (self.mysqlport, path)
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
logging.InstallLog.writeToFile("settings.py updated!")
#self.setupVirtualEnv(self.distro)
# self.setupVirtualEnv(self.distro)
### Applying migrations
@@ -645,7 +664,7 @@ class preFlightsChecks:
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
except BaseException as msg:
logging.InstallLog.writeToFile('[ERROR] '+ str(msg) + " [install_unzip]")
logging.InstallLog.writeToFile('[ERROR] ' + str(msg) + " [install_unzip]")
def install_zip(self):
self.stdOut("Install zip")
@@ -665,7 +684,8 @@ class preFlightsChecks:
if not os.path.exists("/usr/local/CyberCP/public"):
os.mkdir("/usr/local/CyberCP/public")
command = 'wget -O /usr/local/CyberCP/public/phpmyadmin.zip https://%s/misc/phpmyadmin.zip' % (preFlightsChecks.cdn)
command = 'wget -O /usr/local/CyberCP/public/phpmyadmin.zip https://%s/misc/phpmyadmin.zip' % (
preFlightsChecks.cdn)
preFlightsChecks.call(command, self.distro, '[download_install_phpmyadmin]',
command, 1, 0, os.EX_OSERR)
@@ -681,7 +701,6 @@ class preFlightsChecks:
preFlightsChecks.call(command, self.distro, '[download_install_phpmyadmin]',
command, 1, 0, os.EX_OSERR)
## Write secret phrase
rString = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(32)])
@@ -725,15 +744,16 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
'chown -R lscpd:lscpd /usr/local/CyberCP/public/phpmyadmin', 1, 0, os.EX_OSERR)
if self.remotemysql == 'ON':
command = "sed -i 's|'localhost'|'%s'|g' %s" % (self.mysqlhost, '/usr/local/CyberCP/public/phpmyadmin/config.inc.php')
command = "sed -i 's|'localhost'|'%s'|g' %s" % (
self.mysqlhost, '/usr/local/CyberCP/public/phpmyadmin/config.inc.php')
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
command = 'cp /usr/local/CyberCP/plogical/phpmyadminsignin.php /usr/local/CyberCP/public/phpmyadmin/phpmyadminsignin.php'
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
if self.remotemysql == 'ON':
command = "sed -i 's|localhost|%s|g' /usr/local/CyberCP/public/phpmyadmin/phpmyadminsignin.php" % (self.mysqlhost)
command = "sed -i 's|localhost|%s|g' /usr/local/CyberCP/public/phpmyadmin/phpmyadminsignin.php" % (
self.mysqlhost)
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
@@ -743,7 +763,7 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
###################################################### Email setup
def install_postfix_davecot(self):
def install_postfix_dovecot(self):
self.stdOut("Install dovecot - first remove postfix")
try:
@@ -754,19 +774,21 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
command = 'apt-get -y remove postfix'
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
self.stdOut("Install dovecot - do the install")
if self.distro == centos:
command = 'yum install --enablerepo=gf-plus -y postfix3 postfix3-ldap postfix3-mysql postfix3-pcre'
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
elif self.distro == cent8:
command = 'dnf --nogpg install -y https://mirror.ghettoforge.org/distributions/gf/el/8/gf/x86_64/gf-release-8-11.gf.el8.noarch.rpm'
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
command = 'dnf install --enablerepo=gf-plus postfix3 postfix3-mysql -y'
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
else:
command = 'apt-get -y debconf-utils'
command = 'apt-get -y install debconf-utils'
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
file_name = self.cwd + '/pf.unattend.text'
pf = open(file_name, 'w')
@@ -776,18 +798,11 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
command = 'debconf-set-selections ' + file_name
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
command = 'apt-get -y install postfix'
command = 'apt-get -y install postfix postfix-mysql'
# os.remove(file_name)
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
if self.distro == centos or self.distro == cent8:
pass
else:
command = 'apt-get -y install dovecot-imapd dovecot-pop3d postfix-mysql'
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
##
if self.distro == centos:
@@ -795,45 +810,12 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
elif self.distro == cent8:
command = 'dnf install --enablerepo=gf-plus dovecot23 dovecot23-mysql -y'
else:
command = 'apt-get -y install dovecot-mysql'
command = 'apt-get -y install dovecot-mysql dovecot-imapd dovecot-pop3d'
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
if self.distro != centos:
command = 'curl https://repo.dovecot.org/DOVECOT-REPO-GPG | gpg --import'
subprocess.call(command, shell=True)
command = 'gpg --export ED409DA1 > /etc/apt/trusted.gpg.d/dovecot.gpg'
subprocess.call(command, shell=True)
debPath = '/etc/apt/sources.list.d/dovecot.list'
writeToFile = open(debPath, 'w')
writeToFile.write('deb https://repo.dovecot.org/ce-2.3-latest/ubuntu/bionic bionic main\n')
writeToFile.close()
try:
command = 'apt update -y'
subprocess.call(command, shell=True)
except:
pass
try:
command = 'DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical sudo apt-get -q -y -o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold" --only-upgrade install dovecot-mysql -y'
subprocess.call(command, shell=True)
command = 'dpkg --configure -a'
subprocess.call(command, shell=True)
command = 'apt --fix-broken install -y'
subprocess.call(command, shell=True)
command = 'DEBIAN_FRONTEND=noninteractive DEBIAN_PRIORITY=critical sudo apt-get -q -y -o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold" --only-upgrade install dovecot-mysql -y'
subprocess.call(command, shell=True)
except:
pass
except BaseException as msg:
logging.InstallLog.writeToFile('[ERROR] ' + str(msg) + " [install_postfix_davecot]")
logging.InstallLog.writeToFile('[ERROR] ' + str(msg) + " [install_postfix_dovecot]")
return 0
return 1
@@ -845,24 +827,17 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
os.chdir(self.cwd)
if mysql == 'Two':
mysql_virtual_domains = "email-configs/mysql-virtual_domains.cf"
mysql_virtual_forwardings = "email-configs/mysql-virtual_forwardings.cf"
mysql_virtual_mailboxes = "email-configs/mysql-virtual_mailboxes.cf"
mysql_virtual_email2email = "email-configs/mysql-virtual_email2email.cf"
davecotmysql = "email-configs/dovecot-sql.conf.ext"
else:
mysql_virtual_domains = "email-configs-one/mysql-virtual_domains.cf"
mysql_virtual_forwardings = "email-configs-one/mysql-virtual_forwardings.cf"
mysql_virtual_mailboxes = "email-configs-one/mysql-virtual_mailboxes.cf"
mysql_virtual_email2email = "email-configs-one/mysql-virtual_email2email.cf"
davecotmysql = "email-configs-one/dovecot-sql.conf.ext"
mysql_virtual_domains = "email-configs-one/mysql-virtual_domains.cf"
mysql_virtual_forwardings = "email-configs-one/mysql-virtual_forwardings.cf"
mysql_virtual_mailboxes = "email-configs-one/mysql-virtual_mailboxes.cf"
mysql_virtual_email2email = "email-configs-one/mysql-virtual_email2email.cf"
dovecotmysql = "email-configs-one/dovecot-sql.conf.ext"
### update password:
### update password:
data = open(davecotmysql, "r").readlines()
data = open(dovecotmysql, "r").readlines()
writeDataToFile = open(davecotmysql, "w")
writeDataToFile = open(dovecotmysql, "w")
if mysql == 'Two':
dataWritten = "connect = host=127.0.0.1 dbname=cyberpanel user=cyberpanel password=" + mysqlPassword + " port=3307\n"
@@ -875,9 +850,6 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
else:
writeDataToFile.writelines(items)
# if self.distro == ubuntu:
# os.fchmod(writeDataToFile.fileno(), stat.S_IRUSR | stat.S_IWUSR)
writeDataToFile.close()
### update password:
@@ -894,9 +866,6 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
else:
writeDataToFile.writelines(items)
# if self.distro == ubuntu:
# os.fchmod(writeDataToFile.fileno(), stat.S_IRUSR | stat.S_IWUSR)
writeDataToFile.close()
### update password:
@@ -913,9 +882,6 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
else:
writeDataToFile.writelines(items)
# if self.distro == ubuntu:
# os.fchmod(writeDataToFile.fileno(), stat.S_IRUSR | stat.S_IWUSR)
writeDataToFile.close()
### update password:
@@ -932,9 +898,6 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
else:
writeDataToFile.writelines(items)
# if self.distro == ubuntu:
# os.fchmod(writeDataToFile.fileno(), stat.S_IRUSR | stat.S_IWUSR)
writeDataToFile.close()
### update password:
@@ -951,18 +914,13 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
else:
writeDataToFile.writelines(items)
# if self.distro == ubuntu:
# os.fchmod(writeDataToFile.fileno(), stat.S_IRUSR | stat.S_IWUSR)
writeDataToFile.close()
if self.remotemysql == 'ON':
command = "sed -i 's|host=localhost|host=%s|g' %s" % (self.mysqlhost, davecotmysql)
command = "sed -i 's|host=localhost|host=%s|g' %s" % (self.mysqlhost, dovecotmysql)
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
command = "sed -i 's|port=3306|port=%s|g' %s" % (self.mysqlport, davecotmysql)
command = "sed -i 's|port=3306|port=%s|g' %s" % (self.mysqlport, dovecotmysql)
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
##
@@ -971,7 +929,7 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
command = "sed -i 's|localhost|%s:%s|g' %s" % (
self.mysqlhost, self.mysqlport, mysql_virtual_forwardings)
self.mysqlhost, self.mysqlport, mysql_virtual_forwardings)
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
command = "sed -i 's|localhost|%s:%s|g' %s" % (
@@ -1005,10 +963,11 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
fd.write(line)
fd.close()
except IOError as err:
self.stdOut("[ERROR] Error converting: " + filename + " from centos defaults to ubuntu defaults: " + str(err), 1,
1, os.EX_OSERR)
self.stdOut(
"[ERROR] Error converting: " + filename + " from centos defaults to ubuntu defaults: " + str(err), 1,
1, os.EX_OSERR)
def setup_postfix_davecot_config(self, mysql):
def setup_postfix_dovecot_config(self, mysql):
try:
logging.InstallLog.writeToFile("Configuring postfix and dovecot...")
@@ -1020,8 +979,8 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
mysql_virtual_email2email = "/etc/postfix/mysql-virtual_email2email.cf"
main = "/etc/postfix/main.cf"
master = "/etc/postfix/master.cf"
davecot = "/etc/dovecot/dovecot.conf"
davecotmysql = "/etc/dovecot/dovecot-sql.conf.ext"
dovecot = "/etc/dovecot/dovecot.conf"
dovecotmysql = "/etc/dovecot/dovecot-sql.conf.ext"
if os.path.exists(mysql_virtual_domains):
os.remove(mysql_virtual_domains)
@@ -1041,11 +1000,11 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
if os.path.exists(master):
os.remove(master)
if os.path.exists(davecot):
os.remove(davecot)
if os.path.exists(dovecot):
os.remove(dovecot)
if os.path.exists(davecotmysql):
os.remove(davecotmysql)
if os.path.exists(dovecotmysql):
os.remove(dovecotmysql)
###############Getting SSL
@@ -1060,37 +1019,34 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
# Cleanup config files for ubuntu
if self.distro == ubuntu:
preFlightsChecks.stdOut("Cleanup postfix/dovecot config files", 1)
if mysql == 'Two':
self.centos_lib_dir_to_ubuntu("email-configs/master.cf", "/usr/libexec/", "/usr/lib/")
self.centos_lib_dir_to_ubuntu("email-configs/main.cf", "/usr/libexec/postfix",
"/usr/lib/postfix/sbin")
else:
self.centos_lib_dir_to_ubuntu("email-configs-one/master.cf", "/usr/libexec/", "/usr/lib/")
self.centos_lib_dir_to_ubuntu("email-configs-one/main.cf", "/usr/libexec/postfix",
"/usr/lib/postfix/sbin")
self.centos_lib_dir_to_ubuntu("email-configs-one/master.cf", "/usr/libexec/", "/usr/lib/")
self.centos_lib_dir_to_ubuntu("email-configs-one/main.cf", "/usr/libexec/postfix",
"/usr/lib/postfix/sbin")
########### Copy config files
if mysql == 'Two':
shutil.copy("email-configs/mysql-virtual_domains.cf", "/etc/postfix/mysql-virtual_domains.cf")
shutil.copy("email-configs/mysql-virtual_forwardings.cf", "/etc/postfix/mysql-virtual_forwardings.cf")
shutil.copy("email-configs/mysql-virtual_mailboxes.cf", "/etc/postfix/mysql-virtual_mailboxes.cf")
shutil.copy("email-configs/mysql-virtual_email2email.cf", "/etc/postfix/mysql-virtual_email2email.cf")
shutil.copy("email-configs/main.cf", main)
shutil.copy("email-configs/master.cf", master)
shutil.copy("email-configs/dovecot.conf", davecot)
shutil.copy("email-configs/dovecot-sql.conf.ext", davecotmysql)
else:
shutil.copy("email-configs-one/mysql-virtual_domains.cf", "/etc/postfix/mysql-virtual_domains.cf")
shutil.copy("email-configs-one/mysql-virtual_forwardings.cf",
"/etc/postfix/mysql-virtual_forwardings.cf")
shutil.copy("email-configs-one/mysql-virtual_mailboxes.cf", "/etc/postfix/mysql-virtual_mailboxes.cf")
shutil.copy("email-configs-one/mysql-virtual_email2email.cf",
"/etc/postfix/mysql-virtual_email2email.cf")
shutil.copy("email-configs-one/main.cf", main)
shutil.copy("email-configs-one/master.cf", master)
shutil.copy("email-configs-one/dovecot.conf", davecot)
shutil.copy("email-configs-one/dovecot-sql.conf.ext", davecotmysql)
shutil.copy("email-configs-one/mysql-virtual_domains.cf", "/etc/postfix/mysql-virtual_domains.cf")
shutil.copy("email-configs-one/mysql-virtual_forwardings.cf",
"/etc/postfix/mysql-virtual_forwardings.cf")
shutil.copy("email-configs-one/mysql-virtual_mailboxes.cf", "/etc/postfix/mysql-virtual_mailboxes.cf")
shutil.copy("email-configs-one/mysql-virtual_email2email.cf",
"/etc/postfix/mysql-virtual_email2email.cf")
shutil.copy("email-configs-one/main.cf", main)
shutil.copy("email-configs-one/master.cf", master)
shutil.copy("email-configs-one/dovecot.conf", dovecot)
shutil.copy("email-configs-one/dovecot-sql.conf.ext", dovecotmysql)
########### Set custom settings
# We are going to leverage postconfig -e to edit the settings for hostname
command = "postconf -e 'myhostname = %s'" % (str(socket.getfqdn()))
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
# We are explicitly going to use sed to set the hostname default from "myhostname = server.example.com"
# to the fqdn from socket if the default is still found
command = "sed -i 's|server.example.com|%s|g' %s" % (str(socket.getfqdn()), main)
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
######################################## Permissions
@@ -1186,7 +1142,7 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
command = 'chmod o= /etc/dovecot/dovecot-sql.conf.ext'
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
################################### Restart davecot
################################### Restart dovecot
command = 'systemctl enable dovecot.service'
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
@@ -1239,7 +1195,7 @@ $cfg['Servers'][$i]['LogoutURL'] = 'phpmyadminsignin.php?logout';
logging.InstallLog.writeToFile("Postfix and Dovecot configured")
except BaseException as msg:
logging.InstallLog.writeToFile('[ERROR] ' + str(msg) + " [setup_postfix_davecot_config]")
logging.InstallLog.writeToFile('[ERROR] ' + str(msg) + " [setup_postfix_dovecot_config]")
return 0
return 1
@@ -1374,6 +1330,7 @@ imap_folder_list_limit = 0
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
FirewallUtilities.addRule("tcp", "8090")
FirewallUtilities.addRule("tcp", "7080")
FirewallUtilities.addRule("tcp", "80")
FirewallUtilities.addRule("tcp", "443")
FirewallUtilities.addRule("tcp", "21")
@@ -1433,13 +1390,13 @@ imap_folder_list_limit = 0
lscpdPath = '/usr/local/lscp/bin/lscpd'
command = 'cp -f /usr/local/CyberCP/lscpd-0.2.7 /usr/local/lscp/bin/lscpd-0.2.7'
command = 'cp -f /usr/local/CyberCP/lscpd-0.3.1 /usr/local/lscp/bin/lscpd-0.3.1'
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
command = 'rm -f /usr/local/lscp/bin/lscpd'
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
command = 'mv /usr/local/lscp/bin/lscpd-0.2.7 /usr/local/lscp/bin/lscpd'
command = 'mv /usr/local/lscp/bin/lscpd-0.3.1 /usr/local/lscp/bin/lscpd'
preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
command = 'chmod 755 %s' % (lscpdPath)
@@ -1666,7 +1623,7 @@ imap_folder_list_limit = 0
##
command = 'systemctl start lscpd'
#preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
# preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
preFlightsChecks.stdOut("LSCPD Daemon Set!")
@@ -1716,7 +1673,6 @@ imap_folder_list_limit = 0
cronFile = open(cronPath, "w")
content = """
0 * * * * /usr/local/CyberCP/bin/python /usr/local/CyberCP/plogical/findBWUsage.py >/dev/null 2>&1
0 * * * * /usr/local/CyberCP/bin/python /usr/local/CyberCP/postfixSenderPolicy/client.py hourlyCleanup >/dev/null 2>&1
@@ -1724,18 +1680,34 @@ imap_folder_list_limit = 0
0 2 * * * /usr/local/CyberCP/bin/python /usr/local/CyberCP/plogical/upgradeCritical.py >/dev/null 2>&1
0 2 * * * /usr/local/CyberCP/bin/python /usr/local/CyberCP/plogical/renew.py >/dev/null 2>&1
7 0 * * * "/root/.acme.sh"/acme.sh --cron --home "/root/.acme.sh" > /dev/null
0 12 * * * /usr/local/CyberCP/bin/python /usr/local/CyberCP/IncBackups/IncScheduler.py Daily
0 0 * * * /usr/local/CyberCP/bin/python /usr/local/CyberCP/IncBackups/IncScheduler.py Daily
0 0 * * 0 /usr/local/CyberCP/bin/python /usr/local/CyberCP/IncBackups/IncScheduler.py Weekly
*/3 * * * * if ! find /home/*/public_html/ -maxdepth 2 -type f -newer /usr/local/lsws/cgid -name '.htaccess' -exec false {} +; then /usr/local/lsws/bin/lswsctrl restart; fi
"""
cronFile.write(content)
cronFile.close()
### Check and remove OLS restart if lsws ent detected
if not os.path.exists('/usr/local/lsws/bin/openlitespeed'):
data = open(cronPath, 'r').readlines()
writeToFile = open(cronPath, 'w')
for items in data:
if items.find('-maxdepth 2 -type f -newer') > -1:
pass
else:
writeToFile.writelines(items)
writeToFile.close()
if not os.path.exists(CentOSPath):
command = 'chmod 600 %s' % (cronPath)
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
if self.distro == centos or self.distro == cent8:
command = 'systemctl restart crond.service'
else:
@@ -2043,25 +2015,11 @@ milter_default_action = accept
CentOSPath = '/etc/redhat-release'
if os.path.exists(CentOSPath):
if self.distro == centos:
command = 'yum install restic -y'
command = 'yum install -y yum-plugin-copr'
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
elif self.distro == cent8:
command = 'cat /proc/cpuinfo'
result = subprocess.check_output(shlex.split(command)).decode("utf-8")
if result.find('ARM') > -1 or result.find('arm') > -1:
command = 'wget -O /usr/bin/restic https://rep.cyberpanel.net/restic_0.9.6_linux_arm64'
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
else:
command = 'wget -O /usr/bin/restic https://rep.cyberpanel.net/restic_0.9.6_linux_amd64'
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
command = 'chmod +x /usr/bin/restic'
command = 'yum copr enable -y copart/restic'
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
command = 'yum install -y restic'
preFlightsChecks.call(command, self.distro, command, command, 1, 0, os.EX_OSERR)
else:
@@ -2168,7 +2126,6 @@ vmail
def disablePackegeUpdates(self):
if self.distro == centos:
mainConfFile = '/etc/yum.conf'
content = 'exclude=MariaDB-client MariaDB-common MariaDB-devel MariaDB-server MariaDB-shared ' \
'pdns pdns-backend-mysql dovecot dovecot-mysql postfix3 postfix3-ldap postfix3-mysql ' \
@@ -2178,6 +2135,7 @@ vmail
writeToFile.write(content)
writeToFile.close()
def main():
parser = argparse.ArgumentParser(description='CyberPanel Installer')
parser.add_argument('publicip', help='Please enter public IP for your VPS or dedicated server.')
@@ -2195,9 +2153,11 @@ def main():
parser.add_argument('--mysqluser', help='MySQL user if remote is chosen.')
parser.add_argument('--mysqlpassword', help='MySQL password if remote is chosen.')
parser.add_argument('--mysqlport', help='MySQL port if remote is chosen.')
args = parser.parse_args()
logging.InstallLog.writeToFile("Starting CyberPanel installation..")
logging.InstallLog.ServerIP = args.publicip
logging.InstallLog.writeToFile("Starting CyberPanel installation..,10")
preFlightsChecks.stdOut("Starting CyberPanel installation..")
if args.ent == None:
@@ -2239,7 +2199,8 @@ def main():
mysqldb = args.mysqldb
if preFlightsChecks.debug:
print('mysqlhost: %s, mysqldb: %s, mysqluser: %s, mysqlpassword: %s, mysqlport: %s' % (mysqlhost, mysqldb, mysqluser, mysqlpassword, mysqlport))
print('mysqlhost: %s, mysqldb: %s, mysqluser: %s, mysqlpassword: %s, mysqlport: %s' % (
mysqlhost, mysqldb, mysqluser, mysqlpassword, mysqlport))
time.sleep(10)
else:
@@ -2251,7 +2212,8 @@ def main():
mysqldb = ''
distro = get_distro()
checks = preFlightsChecks("/usr/local/lsws/", args.publicip, "/usr/local", cwd, "/usr/local/CyberCP", distro, remotemysql, mysqlhost, mysqldb, mysqluser, mysqlpassword, mysqlport)
checks = preFlightsChecks("/usr/local/lsws/", args.publicip, "/usr/local", cwd, "/usr/local/CyberCP", distro,
remotemysql, mysqlhost, mysqldb, mysqluser, mysqlpassword, mysqlport)
checks.mountTemp()
if args.port == None:
@@ -2272,25 +2234,26 @@ def main():
import installCyberPanel
if ent == 0:
installCyberPanel.Main(cwd, mysql, distro, ent, None, port, args.ftp, args.powerdns, args.publicip, remotemysql, mysqlhost, mysqldb, mysqluser, mysqlpassword, mysqlport)
installCyberPanel.Main(cwd, mysql, distro, ent, None, port, args.ftp, args.powerdns, args.publicip, remotemysql,
mysqlhost, mysqldb, mysqluser, mysqlpassword, mysqlport)
else:
installCyberPanel.Main(cwd, mysql, distro, ent, serial, port, args.ftp, args.powerdns, args.publicip, remotemysql, mysqlhost, mysqldb, mysqluser, mysqlpassword, mysqlport)
installCyberPanel.Main(cwd, mysql, distro, ent, serial, port, args.ftp, args.powerdns, args.publicip,
remotemysql, mysqlhost, mysqldb, mysqluser, mysqlpassword, mysqlport)
checks.setupPHPAndComposer()
checks.fix_selinux_issue()
checks.install_psmisc()
if args.postfix == None:
checks.install_postfix_davecot()
checks.install_postfix_dovecot()
checks.setup_email_Passwords(installCyberPanel.InstallCyberPanel.mysqlPassword, mysql)
checks.setup_postfix_davecot_config(mysql)
checks.setup_postfix_dovecot_config(mysql)
else:
if args.postfix == 'ON':
checks.install_postfix_davecot()
checks.install_postfix_dovecot()
checks.setup_email_Passwords(installCyberPanel.InstallCyberPanel.mysqlPassword, mysql)
checks.setup_postfix_davecot_config(mysql)
checks.setup_postfix_dovecot_config(mysql)
checks.install_unzip()
checks.install_zip()
@@ -2347,7 +2310,7 @@ def main():
checks.enableDisableFTP('on', distro)
checks.installCLScripts()
#checks.disablePackegeUpdates()
# checks.disablePackegeUpdates()
try:
# command = 'mkdir -p /usr/local/lscp/cyberpanel/rainloop/data/data/default/configs/'
@@ -2379,16 +2342,15 @@ echo $oConfig->Save() ? 'Done' : 'Error';
writeToFile.write(content)
writeToFile.close()
command = '/usr/local/lsws/lsphp72/bin/php /usr/local/CyberCP/public/rainloop.php'
subprocess.call(shlex.split(command))
command = "chown -R lscpd:lscpd /usr/local/lscp/cyberpanel/rainloop/data"
subprocess.call(shlex.split(command))
except:
pass
logging.InstallLog.writeToFile("CyberPanel installation successfully completed!")
logging.InstallLog.writeToFile("CyberPanel installation successfully completed!,80")
if __name__ == "__main__":

View File

@@ -87,20 +87,26 @@ class InstallCyberPanel:
except:
pass
command = 'wget https://www.litespeedtech.com/packages/5.0/lsws-5.4.2-ent-x86_64-linux.tar.gz'
command = 'wget https://www.litespeedtech.com/packages/6.0/lsws-6.0-ent-x86_64-linux.tar.gz'
install.preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
command = 'tar zxf lsws-5.4.2-ent-x86_64-linux.tar.gz'
command = 'tar zxf lsws-6.0-ent-x86_64-linux.tar.gz'
install.preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
writeSerial = open('lsws-5.4.2/serial.no', 'w')
writeSerial.writelines(self.serial)
writeSerial.close()
if str.lower(self.serial) == 'trial':
command = 'wget -q --output-document=lsws-6.0/trial.key http://license.litespeedtech.com/reseller/trial.key'
if self.serial == '1111-2222-3333-4444':
command = 'wget -q --output-document=/root/cyberpanel/install/lsws-6.0/trial.key http://license.litespeedtech.com/reseller/trial.key'
install.preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
else:
writeSerial = open('lsws-6.0/serial.no', 'w')
writeSerial.writelines(self.serial)
writeSerial.close()
shutil.copy('litespeed/install.sh', 'lsws-5.3.5/')
shutil.copy('litespeed/functions.sh', 'lsws-5.3.5/')
shutil.copy('litespeed/install.sh', 'lsws-6.0/')
shutil.copy('litespeed/functions.sh', 'lsws-6.0/')
os.chdir('lsws-5.3.5')
os.chdir('lsws-6.0')
command = 'chmod +x install.sh'
install.preFlightsChecks.call(command, self.distro, command, command, 1, 1, os.EX_OSERR)
@@ -274,7 +280,6 @@ class InstallCyberPanel:
def changeMYSQLRootPassword(self):
if self.remotemysql == 'OFF':
if self.distro == ubuntu:
passwordCMD = "use mysql;DROP DATABASE IF EXISTS test;DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%%';GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '%s';UPDATE user SET plugin='' WHERE User='root';flush privileges;" % (InstallCyberPanel.mysql_Root_password)
else:
@@ -656,13 +661,16 @@ def Main(cwd, mysql, distro, ent, serial = None, port = "8090", ftp = None, dns
installer = InstallCyberPanel("/usr/local/lsws/",cwd, distro, ent, serial, port, ftp, dns, publicip, remotemysql, mysqlhost, mysqldb, mysqluser, mysqlpassword, mysqlport)
logging.InstallLog.writeToFile('Installing LiteSpeed Web server,40')
installer.installLiteSpeed()
if ent == 0:
installer.changePortTo80()
logging.InstallLog.writeToFile('Installing Optimized PHPs..,50')
installer.installAllPHPVersions()
if ent == 0:
installer.fix_ols_configs()
logging.InstallLog.writeToFile('Installing MySQL,60')
installer.installMySQL(mysql)
installer.changeMYSQLRootPassword()

View File

@@ -1,11 +1,35 @@
import json
import time
import requests
class InstallLog:
fileName = "/var/log/installLogs.txt"
currentPercent = '10'
LogURL = 'https://cloud.cyberpanel.net/servers/RecvData'
ServerIP = ''
@staticmethod
def writeToFile(message):
if message.find(',') == -1:
message = '%s,%s' % (message, InstallLog.currentPercent)
elif message.find('mount -o') > -1 or message.find('usermod -G lscpd,') > -1:
message = '%s,%s' % (message.replace(',', '-'), InstallLog.currentPercent)
else:
try:
InstallLog.currentPercent = message.split(',')[1]
except:
pass
file = open(InstallLog.fileName,'a')
file.writelines("[" + time.strftime(
"%m.%d.%Y_%H-%M-%S") + "] "+message + "\n")
"%m.%d.%Y_%H-%M-%S") + "] " + message + "\n")
file.close()
try:
finalData = json.dumps({'ipAddress': InstallLog.ServerIP, "InstallCyberPanelStatus": message})
requests.post(InstallLog.LogURL, data=finalData, timeout=10)
except:
pass

View File

@@ -32,6 +32,7 @@ expires {
enableExpires 1
expiresByType image/*=A604800, text/css=A604800, application/x-javascript=A604800
}
autoLoadHtaccess 1
tuning {
eventDispatcher best
@@ -199,4 +200,7 @@ include phpconfigs/php55.conf
include phpconfigs/php56.conf
include phpconfigs/php70.conf
include phpconfigs/php71.conf
include phpconfigs/php72.conf
include phpconfigs/php73.conf
include phpconfigs/php74.conf
include phpconfigs/php80.conf

View File

@@ -63,7 +63,10 @@ SSLCipherSuite ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-A
CacheRoot /home/lscache/
</IfModule>
<VirtualHost *>
<VirtualHost *:80>
DocumentRoot /usr/local/lsws/DEFAULT/html
</VirtualHost>
<VirtualHost *:443>
DocumentRoot /usr/local/lsws/DEFAULT/html
</VirtualHost>
Include /usr/local/lsws/conf/modsec.conf

View File

@@ -139,6 +139,8 @@ SecFilterSelective ARGS &quot;or.+1[[:space:]]*=[[:space:]]1|or 1=1--'|'.+--&quo
SecFilterSelective ARGS &quot;into[[:space:]]+outfile|load[[:space:]]+data|/\*.+\*/&quot;</ruleSet>
</censorshipRuleSet>
<bubbleWrap>1</bubbleWrap>
<bubbleWrapCmd>/bin/bwrap --ro-bind /usr /usr --ro-bind /lib /lib --ro-bind-try /lib64 /lib64 --ro-bind /bin /bin --ro-bind /sbin /sbin --dir /var --ro-bind-try /var/www /var/www --dir /tmp --proc /proc --symlink../tmp var/tmp --dev /dev --ro-bind-try /etc/localtime /etc/localtime --ro-bind-try /etc/ld.so.cache /etc/ld.so.cache --ro-bind-try /etc/resolv.conf /etc/resolv.conf --ro-bind-try /etc/ssl /etc/ssl --ro-bind-try /etc/pki /etc/pki --ro-bind-try /etc/man_db.conf /etc/man_db.conf --ro-bind-try /usr/local/bin/msmtp /etc/alternatives/mta --ro-bind-try /usr/local/bin/msmtp /usr/sbin/exim --bind-try $HOMEDIR $HOMEDIR --bind-try /var/lib/mysql/mysql.sock /var/lib/mysql/mysql.sock --bind-try /home/mysql/mysql.sock /home/mysql/mysql.sock --bind-try /tmp/mysql.sock /tmp/mysql.sock --bind-try /run/mysqld/mysqld.sock /run/mysqld/mysqld.sock --bind-try /var/run/mysqld/mysqld.sock /var/run/mysqld/mysqld.sock '$COPY-TRY /etc/exim.jail/$USER.conf $HOMEDIR/.msmtprc' --unshare-all --share-net --die-with-parent --dir /run/user/$UID $PASSWD 65534 $GROUP 65534</bubbleWrapCmd>
<accessDenyDir>
<dir>/</dir>
<dir>/etc/*</dir>
@@ -147,7 +149,7 @@ SecFilterSelective ARGS &quot;into[[:space:]]+outfile|load[[:space:]]+data|/\*.+
<dir>$SERVER_ROOT/admin/conf/*</dir>
</accessDenyDir>
<accessControl>
<allow>ALL, 127.0.0.1T, 103.21.244.0/22T, 103.22.200.0/22T, 103.31.4.0/22T, 104.16.0.0/12T, 108.162.192.0/18T, 131.0.72.0/22T, 141.101.64.0/18T, 162.158.0.0/15T, 172.64.0.0/13T, 173.245.48.0/20T, 188.114.96.0/20T, 190.93.240.0/20T, 197.234.240.0/22T, 198.41.128.0/17T, 2400:cb00::/32T, 2405:8100::/32T, 2405:b500::/32T, 2606:4700::/32T, 2803:f800::/32T, 2a06:98c0::/29T, 2c0f:f248::/32T, 192.88.134.0/23T, 185.93.228.0/22, 66.248.200.0/22T, 208.109.0.0/22T, 2a02:fe80::/29T</allow>
<allow>ALL, 127.0.0.1T, 103.21.244.0/22T, 103.22.200.0/22T, 103.31.4.0/22T, 104.16.0.0/13T, 104.24.0.0/14T, 108.162.192.0/18T, 131.0.72.0/22T, 141.101.64.0/18T, 162.158.0.0/15T, 172.64.0.0/13T, 173.245.48.0/20T, 188.114.96.0/20T, 190.93.240.0/20T, 197.234.240.0/22T, 198.41.128.0/17T, 2400:cb00::/32T, 2405:8100::/32T, 2405:b500::/32T, 2606:4700::/32T, 2803:f800::/32T, 2a06:98c0::/29T, 2c0f:f248::/32T, 192.88.134.0/23T, 185.93.228.0/22, 66.248.200.0/22T, 208.109.0.0/22T, 2a02:fe80::/29T</allow>
</accessControl>
</security>
<extProcessorList>
@@ -351,6 +353,26 @@ SecFilterSelective ARGS &quot;into[[:space:]]+outfile|load[[:space:]]+data|/\*.+
<procSoftLimit>400</procSoftLimit>
<procHardLimit>500</procHardLimit>
</extProcessor>
<extProcessor>
<type>lsapi</type>
<name>lsphp80</name>
<address>uds://tmp/lshttpd/lsphp80.sock</address>
<maxConns>35</maxConns>
<env>PHP_LSAPI_CHILDREN=35</env>
<initTimeout>60</initTimeout>
<retryTimeout>0</retryTimeout>
<persistConn>1</persistConn>
<respBuffer>0</respBuffer>
<autoStart>3</autoStart>
<path>$SERVER_ROOT/lsphp80/bin/lsphp</path>
<backlog>100</backlog>
<instances>1</instances>
<priority>0</priority>
<memSoftLimit>2047M</memSoftLimit>
<memHardLimit>2047M</memHardLimit>
<procSoftLimit>400</procSoftLimit>
<procHardLimit>500</procHardLimit>
</extProcessor>
</extProcessorList>
<scriptHandlerList>
<scriptHandler>
@@ -408,6 +430,11 @@ SecFilterSelective ARGS &quot;into[[:space:]]+outfile|load[[:space:]]+data|/\*.+
<type>lsapi</type>
<handler>lsphp74</handler>
</scriptHandler>
<scriptHandler>
<suffix>php80</suffix>
<type>lsapi</type>
<handler>lsphp80</handler>
</scriptHandler>
</scriptHandlerList>
<phpConfig>
</phpConfig>
@@ -427,4 +454,4 @@ SecFilterSelective ARGS &quot;into[[:space:]]+outfile|load[[:space:]]+data|/\*.+
<procSoftLimit>400</procSoftLimit>
<procHardLimit>500</procHardLimit>
</railsDefaults>
</httpServerConfig>
</httpServerConfig>

View File

@@ -14,7 +14,6 @@ class mysqlUtilities:
from json import loads
mysqlData = loads(open("/etc/cyberpanel/mysqlPassword", 'r').read())
initCommand = 'mysql -h %s --port %s -u %s -p%s -e "' % (mysqlData['mysqlhost'], mysqlData['mysqlport'], mysqlData['mysqluser'], mysqlData['mysqlpassword'])
remote = 1
except:
@@ -56,7 +55,26 @@ class mysqlUtilities:
if res == 1:
return 0
else:
if remote:
### DO Check
if mysqlData['mysqlhost'].find('ondigitalocean') > -1:
alterUserPassword = "ALTER USER 'cyberpanel'@'%s' IDENTIFIED WITH mysql_native_password BY '%s'" % (
publicip, dbpassword)
command = initCommand + alterUserPassword + '"'
if install.preFlightsChecks.debug:
print(command)
time.sleep(10)
cmd = shlex.split(command)
subprocess.call(cmd)
## RDS Check
if mysqlData['mysqlhost'].find('rds.amazon') == -1:
dropDB = "GRANT ALL PRIVILEGES ON " + dbname + ".* TO '" + dbuser + "'@'%s'" % (publicip)
else:

View File

@@ -393,7 +393,7 @@ max_input_time = 60
; Maximum amount of memory a script may consume (128MB)
; http://php.net/memory-limit
memory_limit = 128M
memory_limit = 256M
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Error handling and logging ;
@@ -660,7 +660,7 @@ auto_globals_jit = On
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size = 8M
post_max_size = 20M
; Automatically add files before PHP document.
; http://php.net/auto-prepend-file
@@ -808,7 +808,7 @@ file_uploads = On
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2M
upload_max_filesize = 20M
; Maximum number of files that can be uploaded via a single request
max_file_uploads = 20

View File

@@ -1,4 +1,4 @@
extprocessor php71 {
php71.confextprocessor php71 {
type lsapi
address uds://tmp/lshttpd/lsphp71.sock
maxConns 50

16
install/phpconfigs/php72.conf Executable file
View File

@@ -0,0 +1,16 @@
php72.confextprocessor php72 {
type lsapi
address uds://tmp/lshttpd/lsphp72.sock
maxConns 50
initTimeout 60
retryTimeout 0
persistConn 1
respBuffer 0
autoStart 1
path /usr/local/lsws/lsphp72/bin/lsphp
memSoftLimit 2047M
memHardLimit 2047M
procSoftLimit 400
procHardLimit 500
}

16
install/phpconfigs/php73.conf Executable file
View File

@@ -0,0 +1,16 @@
php73.confextprocessor php73 {
type lsapi
address uds://tmp/lshttpd/lsphp73.sock
maxConns 50
initTimeout 60
retryTimeout 0
persistConn 1
respBuffer 0
autoStart 1
path /usr/local/lsws/lsphp73/bin/lsphp
memSoftLimit 2047M
memHardLimit 2047M
procSoftLimit 400
procHardLimit 500
}

16
install/phpconfigs/php74.conf Executable file
View File

@@ -0,0 +1,16 @@
php80.confextprocessor php80 {
type lsapi
address uds://tmp/lshttpd/lsphp80.sock
maxConns 50
initTimeout 60
retryTimeout 0
persistConn 1
respBuffer 0
autoStart 1
path /usr/local/lsws/lsphp80/bin/lsphp
memSoftLimit 2047M
memHardLimit 2047M
procSoftLimit 400
procHardLimit 500
}

16
install/phpconfigs/php80.conf Executable file
View File

@@ -0,0 +1,16 @@
php74.confextprocessor php74 {
type lsapi
address uds://tmp/lshttpd/lsphp74.sock
maxConns 50
initTimeout 60
retryTimeout 0
persistConn 1
respBuffer 0
autoStart 1
path /usr/local/lsws/lsphp74/bin/lsphp
memSoftLimit 2047M
memHardLimit 2047M
procSoftLimit 400
procHardLimit 500
}

Binary file not shown.

File diff suppressed because it is too large Load Diff

BIN
locale/cn/LC_MESSAGES/django.mo Executable file → Normal file

Binary file not shown.

14139
locale/cn/LC_MESSAGES/django.po Executable file → Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@@ -1934,6 +1934,7 @@ msgstr "Gestisci FTP"
msgid "Plugins"
msgstr "Componenti aggiuntivi"
#: baseTemplate/templates/baseTemplate/index.html:898
msgid "Installed Plugins"
msgstr "Componenti aggiuntivi installati"

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@@ -65,7 +65,7 @@ msgstr "Создать пакет"
#: websiteFunctions/templates/websiteFunctions/createWebsite.html:29
#: websiteFunctions/templates/websiteFunctions/modifyWebsite.html:45
msgid "Select Package"
msgstr "Вибрать пакет"
msgstr "Выбрать пакет"
#: CLManager/templates/CLManager/createPackage.html:40
#: packages/templates/packages/createPackage.html:27

View File

@@ -64,7 +64,7 @@ class ACL(models.Model):
createBackup = models.IntegerField(default=1)
restoreBackup = models.IntegerField(default=0)
addDeleteDestinations = models.IntegerField(default=0)
scheDuleBackups = models.IntegerField(default=0)
scheduleBackups = models.IntegerField(default=0)
remoteBackups = models.IntegerField(default=0)
## SSL Management
@@ -72,6 +72,9 @@ class ACL(models.Model):
manageSSL = models.IntegerField(default=1)
hostnameSSL = models.IntegerField(default=0)
mailServerSSL = models.IntegerField(default=0)
config = models.TextField(default='{}')
class Administrator(models.Model):
userName = models.CharField(unique=True,max_length = 50)
@@ -93,6 +96,7 @@ class Administrator(models.Model):
acl = models.ForeignKey(ACL, default=1, on_delete=models.PROTECT)
twoFA = models.IntegerField(default=0)
secretKey = models.CharField(max_length=50, default='None')
config = models.TextField(default='{}')

View File

@@ -1,249 +1,361 @@
<!DOCTYPE html>
<html lang="en">
<head>
<style>
/* Loading Spinner */
.spinner {
margin: 0;
width: 70px;
height: 18px;
margin: -35px 0 0 -9px;
position: absolute;
top: 50%;
left: 50%;
text-align: center
}
<style>
.d-flex {
display: flex;
}
.spinner > div {
width: 18px;
height: 18px;
background-color: #333;
border-radius: 100%;
display: inline-block;
-webkit-animation: bouncedelay 1.4s infinite ease-in-out;
animation: bouncedelay 1.4s infinite ease-in-out;
-webkit-animation-fill-mode: both;
animation-fill-mode: both
}
.flex-column {
flex-direction: column;
}
.spinner .bounce1 {
-webkit-animation-delay: -.32s;
animation-delay: -.32s
}
.justify-content-between {
justify-content: space-between;
}
.spinner .bounce2 {
-webkit-animation-delay: -.16s;
animation-delay: -.16s
}
.col-login {
height: 100vh;
display: flex;
flex-direction: column;
@-webkit-keyframes bouncedelay {
0%, 80%, 100% {
-webkit-transform: scale(0.0)
}
40% {
-webkit-transform: scale(1.0)
}
}
}
@keyframes bouncedelay {
0%, 80%, 100% {
transform: scale(0.0);
-webkit-transform: scale(0.0)
}
40% {
transform: scale(1.0);
-webkit-transform: scale(1.0)
}
}
</style>
<meta charset="UTF-8">
<!--[if IE]><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><![endif]-->
<title> Login - CyberPanel </title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
.col-login-left {
background: rgb(51, 204, 204);
background: -moz-linear-gradient(0deg, rgba(51, 204, 204, 1) 0%, rgba(0, 0, 122, 1) 100%);
background: -webkit-linear-gradient(0deg, rgba(51, 204, 204, 1) 0%, rgba(0, 0, 122, 1) 100%);
background: linear-gradient(0deg, rgba(51, 204, 204, 1) 0%, rgba(0, 0, 122, 1) 100%);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#33cccc", endColorstr="#00007a", GradientType=1);
justify-content: space-between;
}
<!-- Favicons -->
{% load static %}
.form-group .input-group select.form-control,
.form-group .input-group input.form-control,
button.btn.btn-login {
height: 45px;
<link rel="stylesheet" type="text/css" href="{% static 'baseTemplate/assets/finalLoginPageCSS/allCss.css' %}">
}
button.btn.btn-login {
background-color: rgb(51, 204, 204);
box-shadow: 0 0 px 0px rgba(0, 0, 0, 0), 0 1px 2px rgba(0, 0, 0, 0);
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
}
button.btn.btn-login:hover {
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
}
<!-- HELPERS -->
.form-group .input-group select.form-control:focus,
.form-group .input-group input.form-control:focus,
button.btn.btn-login {
border: 1px solid rgb(51, 204, 204);
}
<!-- ELEMENTS -->
.col-login-right {
background: #ffffff;
justify-content: center;
}
<!-- ICONS -->
.col-login-right .login-wrapper {
display: flex;
flex-direction: column;
justify-content: space-around;
}
a.login-changelogs {
border-top: 1px solid #fff;
}
<!-- Admin theme -->
.login-changelogs .card {
padding: 1em;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
}
<!-- Components theme -->
.login-changelogs .card:hover {
color: rgb(51, 204, 204);
box-shadow: 0 12px 24px rgba(0, 0, 0, 0.16), 0 10px 10px rgba(0, 0, 0, 0.18);
}
.card-body {
padding-left: 15px;
}
<!-- JS Core -->
.object-fit {
height: 100%;
width: 100%;
object-fit: cover;
border-radius: 6px;
}
<script type="text/javascript" src="{% static 'baseTemplate/assets/js-core/jquery-core.min.js' %}"></script>
h4.card-learnmore {
margin-top: 15px;
position: relative;
color: rgb(51, 204, 204);
font-weight: 500;
font-size: 1.2em;
<script type="text/javascript">
$(window).load(function () {
setTimeout(function () {
$('#loading').fadeOut(400, "linear");
}, 300);
});
</script>
}
<!-- JS Ends -->
h4.card-learnmore span {
display: inline;
padding-bottom: 4px;
border-bottom: 1px solid rgb(51, 204, 204);
}
.alert.alert-danger {
text-align: center;
margin: 1em 2em 1em 2em;
padding-top: 1em;
padding-bottom: 1em;
border: 1px solid red;
}
<style type="text/css">
html, body {
height: 100%;
background: #ffffff;
}
/* Loading Spinner */
.spinner {
margin: 0;
width: 70px;
height: 18px;
margin: -35px 0 0 -9px;
position: absolute;
top: 50%;
left: 50%;
text-align: center
}
</style>
.spinner>div {
width: 18px;
height: 18px;
background-color: #333;
border-radius: 100%;
display: inline-block;
-webkit-animation: bouncedelay 1.4s infinite ease-in-out;
animation: bouncedelay 1.4s infinite ease-in-out;
-webkit-animation-fill-mode: both;
animation-fill-mode: both
}
.spinner .bounce1 {
-webkit-animation-delay: -.32s;
animation-delay: -.32s
}
.spinner .bounce2 {
-webkit-animation-delay: -.16s;
animation-delay: -.16s
}
@-webkit-keyframes bouncedelay {
0%,
80%,
100% {
-webkit-transform: scale(0.0)
}
40% {
-webkit-transform: scale(1.0)
}
}
@keyframes bouncedelay {
0%,
80%,
100% {
transform: scale(0.0);
-webkit-transform: scale(0.0)
}
40% {
transform: scale(1.0);
-webkit-transform: scale(1.0)
}
}
</style>
<meta charset="UTF-8">
<!--[if IE]><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><![endif]-->
<title> Login - CyberPanel </title>
<meta name="description" content="Login to your CypberPanel account">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- Favicons -->
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'baseTemplate/assets/finalLoginPageCSS/allCss.css' %}">
<!-- HELPERS -->
<!-- ELEMENTS -->
<!-- ICONS -->
<!-- Admin theme -->
<!-- Components theme -->
<!-- JS Core -->
<script type="text/javascript" src="{% static 'baseTemplate/assets/js-core/jquery-core.min.js' %}"></script>
<script type="text/javascript">
$(window).load(function() {
setTimeout(function() {
$('#loading').fadeOut(400, "linear");
}, 300);
});
</script>
<!-- JS Ends -->
<style type="text/css">
html,
body {
height: 100%;
background: #ffffff;
}
</style>
</head>
<body>
<div id="loading">
<div id="loading">
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
</div>
<div class>
<div class="col-md-6 col-sm-12 hidden-md" style="background: #00007A;">
<div class="row panel-body style=" padding-bottom: 0px;>
<div class>
<div class="col-md-6 col-sm-12 hidden-md col-login col-login-left">
<div class="row panel-body my-30" style="padding-bottom: 0px;">
<div class="col-lg-6 col-md-12 panel-body">
<h2 class="text-transform-upr text-white my-30 text-bold">WEB HOSTING CONTROL PANEL
</br/>FOR EVERYONE
<h2 class="text-transform-upr text-white my-30 text-bold">WEB HOSTING CONTROL PANEL
</br />FOR EVERYONE
</h2>
<h4 class="text-white">Powered By OpenLiteSpeed/LiteSpeed Enterprise. Built For Speed, Security and
Reliability.</h4>
</h2>
<h4 class="text-white">Powered By OpenLiteSpeed/LiteSpeed Enterprise. Built For Speed, Security and
Reliability.</h4>
</div>
<div class="col-lg-6 col-md-12 text-center panel-body">
<img class="" src="/static/images/cyberpanel-banner-graphics.png" alt="" width="96%">
<img class="" src="/static/images/cyberpanel-banner-graphics.png" alt="" width="96%">
</div>
</div>
<div class="row panel-body">
</div>
<div class="row panel-body">
<div class="row panel-body">
<ul class="reset-ul">
<li class="row my-30">
<div class="col-lg-3 col-md-12 text-center">
<img class="img-thumbnail mb-20" src="/static/images/new-design-list-websites-square.png" alt=""
width="150">
</div>
<div class="col-lg-6 col-md-12 mb-20">
<h3 class="text-white mb-5">
Change Logs
</h3>
<p class="text-white mt-10">
Learn about new releases and features.
</p>
</div>
<div class="col-lg-3 col-md-12 text-center">
<a href="https://go.cyberpanel.net/updates"
target='_blank'>
<button type="button" class="btn btn-outline-light mb-30 rounded mt-5">
Learn More
</button>
</a>
</div>
</li>
</ul>
</div>
</div>
</div>
<div ng-app="loginSystem" ng-controller="loginSystem" class="col-md-6 col-sm-12" style="background: #ffffff;">
<br/>
<div>
<form id="loginForm" action="/" class="col-md-8 col-md-offset-2">
<h1 class="text-transform-upr text-center panel-body text-bold"
style="padding-bottom: 0px; color: #33CCCC;">
<img class="center-block text-center my-20" src="{% static 'images/cyber-panel-logo.svg' %}">
CyberPanel
<span class="opacity-80">v 2.0</span>
</h1>
<h4 class="text-muted text-center mb-10">Web Hosting Control Panel</h4>
<div class="">
<div class="mx-30">
<div class="content-box-wrapper panel-body my-10 mx-30">
<div class="form-group">
<div class="input-group">
<input ng-model="username" type="text" class="form-control" name="username"
placeholder="Enter username" required style="height: 45px;">
<span class="input-group-addon bg-blue">
<i class="glyph-icon icon-envelope-o"></i>
</span>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input ng-keypress="initiateLogin($event)" ng-model="password" type="password"
class="form-control" id="password" placeholder="Password" required
name="password">
<span class="input-group-addon bg-blue">
<i class="glyph-icon icon-unlock-alt"></i>
</span>
</div>
<img id="verifyingLogin" class="center-block"
src="{% static 'images/loading.gif' %}">
</div>
<div ng-hide="verifyCode" class="form-group">
<div class="input-group">
<input ng-model="twofa" type="text" class="form-control" name="twofa"
placeholder="Enter code from Google Authenticator" required style="height: 45px;">
<span class="input-group-addon bg-blue">
<i class="glyph-icon icon-unlock-alt"></i>
</span>
</div>
</div>
<div class="form-group">
<div class="input-group">
<select ng-model="languageSelection" ng-init="languageSelection='english'"
class="form-control">
<option value="english">English</option>
<option>Bangla</option>
<option>Bosnian</option>
<option>Bulgarian</option>
<option>Chinese</option>
<option>French</option>
<option>German</option>
<option>Greek</option>
<option>Italian</option>
<option>Indonesian</option>
<option>Japanese</option>
<option>Polish</option>
<option>Portuguese</option>
<option>Russian</option>
<option>Spanish</option>
<option>Turkish</option>
<option>Vietnamese</option>
</select>
</div>
</div>
<button type="button" ng-click="verifyLoginCredentials()"
class="btn btn-success btn-block">Sign In
</button>
</div>
<a class=" login-changelogs" href="https://go.cyberpanel.net/updates" target='_blank'>
<div class="card mb-3" style="max-width: 540px;">
<div class="row g-0">
<div class="col-md-3">
<img src="/static/images/new-design-list-websites-square.png" alt="..." class="object-fit">
</div>
<div class="col-md-8 ml-5">
<div class="card-body d-flex flex-column justify-content-around">
<h3 class="card-title mb-5 font-weight-bold">Change Logs</h3>
<p class="card-text mt-10">Stay up to date about new releases and features.</p>
<h4 class="card-learnmore">
<span>
Learn More
<i>
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" aria-hidden="true" focusable="false" data-icon="external-link-alt" role="img" viewBox="0 0 512 512">
<path fill="currentColor"
d="M432,320H400a16,16,0,0,0-16,16V448H64V128H208a16,16,0,0,0,16-16V80a16,16,0,0,0-16-16H48A48,48,0,0,0,0,112V464a48,48,0,0,0,48,48H400a48,48,0,0,0,48-48V336A16,16,0,0,0,432,320ZM488,0h-128c-21.37,0-32.05,25.91-17,41l35.73,35.73L135,320.37a24,24,0,0,0,0,34L157.67,377a24,24,0,0,0,34,0L435.28,133.32,471,169c15,15,41,4.5,41-17V24A24,24,0,0,0,488,0Z" />
</svg>
</i>
</span>
</h4>
</div>
</div>
</div>
</div>
</a>
</div>
</div>
</div>
<div ng-app="loginSystem" ng-controller="loginSystem" class="col-md-6 col-sm-12 col-login col-login-right" style="">
<div class="login-wrapper">
<form id="loginForm" action="/" class="col-md-8 col-md-offset-2">
<h1 class="text-transform-upr text-center panel-body text-bold" style="padding-bottom: 0px; color: #33CCCC;">
<img class="center-block text-center my-20" src="{% static 'images/cyber-panel-logo.svg' %}">
CyberPanel
<span class="opacity-80">v 2.1</span>
</h1>
<h4 class="text-muted text-center mb-10">Web Hosting Control Panel</h4>
<div class="">
<div class="mx-30">
<div class="content-box-wrapper panel-body my-10 mx-30">
<div class="form-group">
<div class="input-group">
<input ng-model="username" type="text" class="form-control" name="username" placeholder="Enter username" required style="height: 45px;">
<span class="input-group-addon bg-blue">
<i class="glyph-icon icon-envelope-o"></i>
</span>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input ng-keypress="initiateLogin($event)" ng-model="password" type="password" class="form-control" id="password" placeholder="Password" required name="password" style="height: 45px;">
<span class="input-group-addon bg-blue">
<i class="glyph-icon icon-unlock-alt"></i>
</span>
</div>
<img id="verifyingLogin" class="center-block" src="{% static 'images/loading.gif' %}">
</div>
<div ng-hide="verifyCode" class="form-group">
<div class="input-group">
<input ng-model="twofa" type="text" class="form-control" name="twofa" placeholder="Enter code from Google Authenticator" required style="height: 45px;">
<span class="input-group-addon bg-blue">
<i class="glyph-icon icon-unlock-alt"></i>
</span>
</div>
</div>
<div class="form-group">
<div class="input-group">
<select ng-model="languageSelection" ng-init="languageSelection='english'" class="form-control">
<option value="english">English</option>
<option>Bangla</option>
<option>Bosnian</option>
<option>Bulgarian</option>
<option>Chinese</option>
<option>French</option>
<option>German</option>
<option>Greek</option>
<option>Italian</option>
<option>Indonesian</option>
<option>Japanese</option>
<option>Polish</option>
<option>Portuguese</option>
<option>Russian</option>
<option>Spanish</option>
<option>Turkish</option>
<option>Vietnamese</option>
</select>
</div>
</div>
<button type="button" style="background-color: #33CCCC;" ng-click="verifyLoginCredentials()" class="btn btn-success btn-block btn-login">Sign In
</button>
</div>
</div>
</div>
</form>
<div id="loginFailed" class="alert alert-danger">
<p>Could Not Login, Error message: {$ errorMessage $}</p>
<p>Could Not Login, Error message: {$ errorMessage $}</p>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.angularjs.org/1.6.5/angular.min.js"></script>
<script src="https://code.angularjs.org/1.6.5/angular-route.min.js"></script>
<script src="{% static 'loginSystem/login-systen.js' %}"></script>
</div>
<script src="https://code.angularjs.org/1.6.5/angular.min.js"></script>
<script src="https://code.angularjs.org/1.6.5/angular-route.min.js"></script>
<script src="{% static 'loginSystem/login-system.js' %}"></script>
</body>
</html>
</html>

View File

@@ -279,7 +279,7 @@
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="{% static 'loginSystem/login-systen.js' %}"></script>
<script src="{% static 'loginSystem/login-system.js' %}"></script>
@@ -356,4 +356,4 @@
<script type="text/javascript" src="{% static 'baseTemplate/assets/widgets/theme-switcher/themeswitcher.js' %}"></script>
</body>
</html>
</html>

Some files were not shown because too many files have changed in this diff Show More