Skip to content

Commit

Permalink
phpmyadmin autologin: access keys generation
Browse files Browse the repository at this point in the history
  • Loading branch information
usmannasir committed Aug 8, 2020
1 parent bcd0716 commit 8c35727
Show file tree
Hide file tree
Showing 8 changed files with 114 additions and 85 deletions.
2 changes: 1 addition & 1 deletion baseTemplate/templates/baseTemplate/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@
<li class="listDatabases"><a href="{% url 'listDBs' %}"
title="{% trans 'List Databases' %}"><span>{% trans "List Databases" %}</span></a>
</li>
<li><a href="/phpmyadmin/index.php" title="{% trans 'PHPMYAdmin' %}"
<li><a href="{% url 'phpMyAdmin' %}" title="{% trans 'PHPMYAdmin' %}"
target="_blank"><span>{% trans "PHPMYAdmin" %}</span></a></li>
<!----<li><a href="{% url 'modifyPackage' %}" title="Change Password"><span>Change Password</span></a></li>--->
</ul>
Expand Down
6 changes: 5 additions & 1 deletion databases/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-


from django.db import models
from websiteFunctions.models import Websites

Expand All @@ -15,3 +14,8 @@ class DBMeta(models.Model):
database = models.ForeignKey(Databases, on_delete=models.CASCADE)
key = models.CharField(max_length=200)
value = models.TextField()

class GlobalUserDB(models.Model):
username = models.CharField(max_length=200)
password = models.CharField(max_length=500)
token = models.CharField(max_length=20)
6 changes: 2 additions & 4 deletions databases/static/databases/databases.js
Original file line number Diff line number Diff line change
Expand Up @@ -569,9 +569,9 @@ app.controller('listDBs', function ($scope, $http) {

app.controller('phpMyAdmin', function ($scope, $http, $window) {

function setupPHPMYAdminSession() {
$scope.generateAccess = function() {

url = "/dataBases/setupPHPMYAdminSession";
url = "/dataBases/generateAccess";

var data = {};

Expand All @@ -587,7 +587,6 @@ app.controller('phpMyAdmin', function ($scope, $http, $window) {

function ListInitialDatas(response) {


if (response.data.status === 1) {
$window.location.href = '/phpmyadmin';
}
Expand All @@ -598,6 +597,5 @@ app.controller('phpMyAdmin', function ($scope, $http, $window) {
function cantLoadInitialDatas(response) {}

}
setupPHPMYAdminSession();

});
85 changes: 24 additions & 61 deletions databases/templates/databases/phpMyAdmin.html
Original file line number Diff line number Diff line change
@@ -1,73 +1,36 @@
{% extends "baseTemplate/index.html" %}
{% load i18n %}
{% block title %}{% trans "phpMyAdmin - CyberPanel" %}{% endblock %}
{% block title %}{% trans "PHPMYAdmin - CyberPanel" %}{% endblock %}
{% block content %}

{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
{% load static %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->

<div class="container">
<div id="page-title">
<h2>{% trans "Create Database" %}</h2>
<p>{% trans "Create a new database on this page." %}</p>
</div>

<div ng-controller="phpMyAdmin" class="panel">
<div class="panel-body">
<h3 class="content-box-header">
{% trans "Create Database" %} <img ng-hide="createDatabaseLoading" src="{% static 'images/loading.gif' %}">
</h3>
<div class="example-box-wrapper">

<form class="form-horizontal bordered-row panel-body">

<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">
{% for items in websitesList %}
<option>{{ items }}</option>
{% endfor %}
</select>
</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 ng-controller="phpMyAdmin" class="container">
<div id="page-title">
<h2>{% trans "PHPMYAdmin" %}</h2>
<p>{% trans "Access your databases via PHPMYAdmin" %}</p>
</div>

<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
{% trans "PHPMYAdmin" %}
</h3>
<div class="example-box-wrapper">

<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
</button>
</a>

</div>


</form>




</div>
</div>
</div>
</div>



</div>


{% endblock %}
</div>
{% endblock %}
2 changes: 1 addition & 1 deletion databases/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@
url(r'^remoteAccess$', views.remoteAccess, name='remoteAccess'),
url(r'^allowRemoteIP$', views.allowRemoteIP, name='allowRemoteIP'),
url(r'^phpMyAdmin$', views.phpMyAdmin, name='phpMyAdmin'),
url(r'^setupPHPMYAdminSession$', views.setupPHPMYAdminSession, name='setupPHPMYAdminSession'),
url(r'^generateAccess$', views.generateAccess, name='generateAccess'),
]
74 changes: 57 additions & 17 deletions databases/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@
import json
from plogical.processUtilities import ProcessUtilities
from loginSystem.models import Administrator
import CyberCP.settings as settings
from plogical.acl import ACLManager
from databases.models import GlobalUserDB
from plogical import randomPassword
from cryptography.fernet import Fernet
from plogical.mysqlUtilities import mysqlUtilities
# Create your views here.

def loadDatabaseHome(request):
Expand Down Expand Up @@ -150,27 +154,63 @@ def phpMyAdmin(request):
except KeyError:
return redirect(loadLoginPage)

def setupPHPMYAdminSession(request):
def generateAccess(request):
try:

userID = request.session['userID']
admin = Administrator.objects.get(id = userID)
currentACL = ACLManager.loadedACL(userID)

execPath = "/usr/local/CyberCP/bin/python /usr/local/CyberCP/databases/databaseManager.py"
execPath = execPath + " generatePHPMYAdminData --userID " + str(userID)

output = ProcessUtilities.outputExecutioner(execPath)

if output.find("1,") > -1:
request.session['PMA_single_signon_user'] = admin.userName
request.session['PMA_single_signon_password'] = output.split(',')[1]
data_ret = {'status': 1}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
else:
data_ret = {'status': 1}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)
try:
GlobalUserDB.objects.get(username=admin.userName)
except:

## Key generation

keySavePath = '/home/cyberpanel/phpmyadmin_%s' % (admin.userName)
key = Fernet.generate_key()

writeToFile = open(keySavePath, 'w')
writeToFile.write(key.decode())
writeToFile.close()

command = 'chown root:root %s' % (keySavePath)
ProcessUtilities.executioner(command)

command = 'chmod 600 %s' % (keySavePath)
ProcessUtilities.executioner(command)

##

password = randomPassword.generate_pass()
f = Fernet(key)
GlobalUserDB(username=admin, password=f.encrypt(password.encode('utf-8'))).save()

sites = ACLManager.findWebsiteObjects(currentACL, userID)

createUser = 1

for site in sites:
for db in site.databases_set.all():
mysqlUtilities.addUserToDB(db.dbName, admin.userName, password, createUser)
createUser = 0

# execPath = "/usr/local/CyberCP/bin/python /usr/local/CyberCP/databases/databaseManager.py"
# execPath = execPath + " generatePHPMYAdminData --userID " + str(userID)
#
# output = ProcessUtilities.outputExecutioner(execPath)
#
# if output.find("1,") > -1:
# request.session['PMA_single_signon_user'] = admin.userName
# request.session['PMA_single_signon_password'] = output.split(',')[1]
# data_ret = {'status': 1}
# json_data = json.dumps(data_ret)
# return HttpResponse(json_data)
# else:

data_ret = {'status': 1}
json_data = json.dumps(data_ret)
return HttpResponse(json_data)


except BaseException as msg:
Expand Down
1 change: 1 addition & 0 deletions plogical/acl.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,7 @@ def findAllSites(currentACL, userID, fetchChilds = 0):

@staticmethod
def searchWebsiteObjects(currentACL, userID, searchTerm):

if currentACL['admin'] == 1:
return Websites.objects.filter(domain__istartswith=searchTerm)
else:
Expand Down
23 changes: 23 additions & 0 deletions plogical/mysqlUtilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -902,6 +902,29 @@ def enableRemoteMYSQL():
print('0,%s "[mysqlUtilities.enableRemoteMYSQL]' % (str(msg)))
return 0

@staticmethod
def addUserToDB(database, user, password, createUser = 0):
try:

connection, cursor = mysqlUtilities.setupConnection()

if connection == 0:
return 0

if createUser:
cursor.execute(
"CREATE USER '" + user + "'@'%s' IDENTIFIED BY '" % (mysqlUtilities.LOCALHOST) + password + "'")

cursor.execute(
"GRANT ALL PRIVILEGES ON " + database + ".* TO '" + user + "'@'%s'" % (mysqlUtilities.LOCALHOST))
connection.close()

return 1

except BaseException as msg:
logging.CyberCPLogFileWriter.writeToFile(str(msg) + "[addUserToDB]")
return 0

def main():
parser = argparse.ArgumentParser(description='CyberPanel')
parser.add_argument('function', help='Specific a function to call!')
Expand Down

0 comments on commit 8c35727

Please sign in to comment.