HEX
Server: Apache
System: Linux vpshost0650.publiccloud.com.br 4.4.79-grsec-1.lc.x86_64 #1 SMP Wed Aug 2 14:18:21 -03 2017 x86_64
User: bandeirantesbomb3 (10068)
PHP: 8.0.7
Disabled: apache_child_terminate,dl,escapeshellarg,escapeshellcmd,exec,link,mail,openlog,passthru,pcntl_alarm,pcntl_exec,pcntl_fork,pcntl_get_last_error,pcntl_getpriority,pcntl_setpriority,pcntl_signal,pcntl_signal_dispatch,pcntl_sigprocmask,pcntl_sigtimedwait,pcntl_sigwaitinfo,pcntl_strerror,pcntl_wait,pcntl_waitpid,pcntl_wexitstatus,pcntl_wifexited,pcntl_wifsignaled,pcntl_wifstopped,pcntl_wstopsig,pcntl_wtermsig,php_check_syntax,php_strip_whitespace,popen,proc_close,proc_open,shell_exec,symlink,system
Upload Files
File: //usr/bin/lwmysrvadm
#!/usr/bin/python
from __future__ import print_function
import argparse
import subprocess
import os.path
import time

# bootstrap imports
import string
import random
import MySQLdb

# service imports
from lwdbadmin.mysql.lwmysrvadm import *

import sys


# getvalue imports
import ConfigParser

devnull = open("/dev/null", 'w')

def partitioning():
    comm = ["lvcreate", "-Wy", "-Zy", "-y", "--name", "lv_mysql", "--size", "50G", "vg_system"]

    subprocess.check_call(comm,  stdout=devnull, stderr=devnull)
    
    comm = ["mkfs.xfs", "/dev/mapper/vg_system-lv_mysql"]
    subprocess.check_call(comm,  stdout=devnull, stderr=devnull)
    
    with open("/etc/fstab", "a") as f:
        f.write("\n/dev/mapper/vg_system-lv_mysql /var/lib/mysql   xfs     defaults,noatime 0 0\n")
    
    comm = ["mount", "/var/lib/mysql"]
    subprocess.check_call(comm,  stdout=devnull, stderr=devnull)
    os.mkdir("/var/lib/mysql/data")
    os.chown("/var/lib/mysql/data", 27, 27)


def createuser():
    # doesnt matter if it fail
    comm = ["groupadd", "-g", "27", "-o", "-r", "mysql"]
    _ = subprocess.call(comm,  stdout=devnull, stderr=devnull)
    
    comm = ["useradd", "-M", "-r",
            "-d", "/var/lib/mysql",
            "-s", "/sbin/nologin",
            "-c", "MySQL server",
            "-g", "mysql", "mysql"]
    _ = subprocess.call(comm,  stdout=devnull, stderr=devnull)


def bootstrap():
    def r(choices, n):
        return ''.join(random.SystemRandom().choice(choices) for _ in range(n))

    user_list = string.ascii_lowercase + string.digits
    pwd_list = string.ascii_letters + string.digits + "!@%*-_+.,"

    user = r(user_list, 15)
    password = r(pwd_list, 18)

	# Load version variable with MySQL version.	
    stdout = subprocess.Popen('mysql --version', shell=True, stdout=subprocess.PIPE).stdout
    output = stdout.read()
    out = output[output.find("Distrib") + len("Distrib"):output.find(",")].replace(" ", "").replace(".", "").replace("-", "")[0:2]
    version = int(out)

    if version >= 57:
        script_create_root = """CREATE USER '{user}'@'localhost' IDENTIFIED BY '{password}'; GRANT ALL PRIVILEGES ON *.* TO '{user}'@'localhost' WITH GRANT OPTION;
CREATE USER '{user}'@'127.0.0.1' IDENTIFIED BY '{password}'; GRANT ALL PRIVILEGES ON *.* TO '{user}'@'127.0.0.1' WITH GRANT OPTION;
CREATE USER '{user}'@'::1' IDENTIFIED BY '{password}'; GRANT ALL PRIVILEGES ON *.* TO '{user}'@'::1' WITH GRANT OPTION;""".format(**locals())
    else:	
        script_create_root = """INSERT INTO mysql.user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Create_user_priv, Event_priv, Trigger_priv, Create_tablespace_priv) VALUES ('localhost','{user}',PASSWORD('{password}'), 'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
INSERT INTO mysql.user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Create_user_priv, Event_priv, Trigger_priv, Create_tablespace_priv) VALUES ('127.0.0.1','{user}',PASSWORD('{password}'), 'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
INSERT INTO mysql.user (Host, User, Password, Select_priv, Insert_priv, Update_priv, Delete_priv, Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv, File_priv, Grant_priv, References_priv, Index_priv, Alter_priv, Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv, Execute_priv, Repl_slave_priv, Repl_client_priv, Create_view_priv, Show_view_priv, Create_routine_priv, Alter_routine_priv, Create_user_priv, Event_priv, Trigger_priv, Create_tablespace_priv) VALUES ('::1','{user}',PASSWORD('{password}'), 'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');""".format(**locals())
	
    script = """FLUSH PRIVILEGES;
DROP DATABASE IF EXISTS test;
TRUNCATE TABLE mysql.user;
TRUNCATE TABLE mysql.db;
TRUNCATE TABLE mysql.proxies_priv;
{script_create_root}
CREATE DATABASE IF NOT EXISTS teste;
CREATE TABLE IF NOT EXISTS teste.teste(teste VARCHAR(50) NOT NULL);
TRUNCATE TABLE teste.teste;
INSERT INTO teste.teste values ('Locaweb');
CREATE USER 'teste'@'%' IDENTIFIED BY '*1A2FA58B8ADDA83A100686FB4FACC2AFF1316FEA';
INSERT INTO mysql.db VALUES ('%', 'teste', 'teste', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'N', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y', 'Y');
FLUSH PRIVILEGES;
""".format(**locals())

    if version >= 57:
        subprocess.Popen('mysqld --initialize-insecure --user=mysql', shell=True)
        time.sleep(30)
        subprocess.Popen('systemctl start mysql', shell=True)
        time.sleep(30)
        comm = ["mysql", "--user=root", "--skip-password"]
        p = subprocess.Popen(comm, stdin=subprocess.PIPE, stdout=devnull, stderr=devnull)
        _ = p.communicate(script)
    else:
        comm = ["mysqld", "--bootstrap", "--user=mysql"]
        p = subprocess.Popen(comm, stdin=subprocess.PIPE, stdout=devnull, stderr=devnull)
        _ = p.communicate(script)
	
    with open("/root/.my.cnf", "w") as f:
        f.write("[client]\n")
        f.write("user={}\n".format(user))
        f.write('password="{}"\n'.format(password))

    with open("/etc/locaweb/lwdbadmin/mysql.cnf", "w") as f:
        f.write("[MySQL]\n")
        f.write("host: localhost\n")
        f.write("user: {}\n".format(user))
        f.write('pass: {}\n'.format(password))

    subprocess.Popen('/usr/bin/lwmyauth', shell=True)

def bootstrap_proxysql():
    def r(choices, n):
        return ''.join(random.SystemRandom().choice(choices) for _ in range(n))

    user_list = string.ascii_lowercase + string.digits
    pwd_list = string.ascii_letters + string.digits + "%_."

    user = r(user_list, 15)
    password = r(pwd_list, 18)
    
    monitor_user = r(user_list, 15)
    monitor_password = r(pwd_list, 18)
    
    try:
        script = """SET admin-hash_passwords='true';
        SET admin-admin_credentials='{user}:{password}';
        LOAD ADMIN VARIABLES TO RUNTIME;
        SAVE ADMIN VARIABLES TO DISK;
        SET mysql-interfaces='0.0.0.0:3306';
        SET mysql-monitor_username='{monitor_user}';
        SET mysql-monitor_password='{monitor_password}';
        SAVE MYSQL VARIABLES TO DISK;
        """.format(**locals())
        
        # This below are the default admin credentials when proxysql is installed. We will change it now.
        comm = ["mysql", "-h127.0.0.1", "-P6032", "-uadmin", "-padmin"]
        p = subprocess.Popen(comm, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        _ = p.communicate(script)
        retcode = p.returncode
        stdout = _[0]
        stderr = _[1]
    
        if retcode != 0:
            raise RuntimeError("Failed to bootstrap proxysql, error message: %s" % stderr)
        
        else:
            with open("/etc/locaweb/lwdbadmin/proxysql.cnf", "w") as f:
                f.write("[proxysql]\n")
                f.write("host=127.0.0.1\n")
                f.write("port=6032\n")
                f.write("user={}\n".format(user))
                f.write("password={}\n".format(password))
                f.write("monitor_user={}\n".format(monitor_user))
                f.write("monitor_password={}\n".format(monitor_password))
            print("ProxySQL bootstrap finished sucessfully.")
    except Exception as e:
            print(e)
    finally:
        restart_proxysql()

def restart_proxysql():
    try:
        user = getvalue("user")
        password = getvalue("password")
        host = getvalue("host")
        port = int(getvalue("port"))
        
        script = """PROXYSQL RESTART;"""
        
        comm = ["mysql", "--host={}".format(host), "--port={}".format(port), "--user={}".format(user), "--password={}".format(password)]
        p = subprocess.Popen(comm, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        _ = p.communicate(script)
        retcode = p.returncode
        stdout = _[0]
        stderr = _[1]
    
        if retcode != 0:
            raise RuntimeError("Failed to bootstrap proxysql, error message: %s" % stderr)
        
        else:
            print("ProxySQL bootstrap finished sucessfully.")
    except Exception as e:
            print(e)

def getvalue(name):
    config = ConfigParser.ConfigParser()
    if os.path.exists("/etc/default/locaweb/description/reseller"):
        config.readfp(open("/etc/locaweb/lwdbadmin/proxysql.cnf"))
        ret = config.get("proxysql", name)
    else:                
        config.readfp(open("/root/.my.cnf"))
        ret = config.get("client", name)
    if ret[0] == '"':
        ret = ret[1:-1]
    return ret

# service program

def parse_args():
    parser = argparse.ArgumentParser(description="Manage MySQL Locaweb Service")
    parser.add_argument('--version', action='version', version='%(prog)s 2.3')

    # comandos
    subparsers = parser.add_subparsers(dest="command")

    create_parser = subparsers.add_parser('create', help='create a new service')
    create_parser.add_argument('dataset', type=str, help="Dataset to create the service")
    create_parser.add_argument('datasetbackup', type=str, help="Dataset Backup to create the service")
    create_parser.add_argument('name', type=str, help="Service name")
    create_parser.add_argument('serviceip', type=str, help="Service address")

    attach_parser = subparsers.add_parser('attach', help='attach an existing service to this host')
    attach_parser.add_argument('dataset', type=str, help="Dataset to create the service")
    attach_parser.add_argument('datasetbackup', type=str, help="Dataset to create the service")
    attach_parser.add_argument('name', type=str, help="Service name")
    attach_parser.add_argument('--force', action="store_true", help="Attach a service even if the service is hosted by another machine")

    detach_parser = subparsers.add_parser('detach', help='detach a service from this host')
    detach_parser.add_argument('name', type=str, help="Service name")

    getips_parser = subparsers.add_parser('list', help="list ips from machines")
    getips_parser.add_argument("--serviceip", action="store_true")
    getips_parser.add_argument("--names", action="store_true")
    getips_parser.add_argument("--service")

    testlock_parser = subparsers.add_parser('test-lock', help="Test if this service is supposed to run in this machine")
    testlock_parser.add_argument("name", type=str, help="Service name")

    # comandos fpm = g2 centos 7
    fpm_parser = subparsers.add_parser('fpm', help='Dedicated services')
    fpm_parser.add_argument('--bootstrap', action="store_true")
    fpm_parser.add_argument("--lvm", action="store_true")
    fpm_parser.add_argument("--user", action="store_true")
    fpm_parser.add_argument("--password", action="store_true")

    return parser.parse_args()


if __name__ == "__main__":
    args = parse_args()

    # FPM
    if args.command == "fpm":
        if args.lvm and not os.path.ismount("/var/lib/mysql"):
            partitioning()
            createuser()
        if args.bootstrap:
            # If reseller machine, bootstrap proxysql instead
            if os.path.exists("/etc/default/locaweb/description/reseller"):
                bootstrap_proxysql()
            else:
                bootstrap()
        if args.user:
            ret = getvalue("user")
            print(ret)
        if args.password:
            ret = getvalue("password")
            print(ret)
    else:
        # Shared Services
        if args.command == "detach":
            detach(args.name)
        elif args.command == 'list':
            for name, d in getservices():
                if args.serviceip:
                    serviceip = getsrvips(d)
                ret = []
                if args.names:
                    ret.append(name)
                if args.serviceip:
                    ret.append(serviceip.split('/')[0])

                print ("\t".join(ret))
        elif args.command == "test-lock":
            for name, d in getservices():
                if name == args.name:
                    fname = os.path.join(d, "config", "host")
                    try:
                        trylock(fname, False)
                        sys.exit(0)
                    except Exception, e:
                        print (e)
                        print ("If you want that this machine hosts this service, change de /var/lib/mysql/config/host file")
                        break
            sys.exit(0)

        else:
            dataset ="{0}.fs.locaweb.com.br:/storage/{1}".format(
                args.dataset.lower(),
                args.dataset.upper())
            datasetbackup ="{0}.fs.locaweb.com.br:/storage/{1}".format(
                args.datasetbackup.lower(),
                args.datasetbackup.upper())

            if ('BBFS' in dataset) or ('BDFS' in datasetbackup):
                print ("Verify the dataset order: lwmysrvadm attach dataset datasetbackup name")
                sys.exit(0)

            if args.command == "create":
                create(args.name, dataset, datasetbackup, args.serviceip)
                args.force = False
                created = True
                attach(args.name, dataset, datasetbackup, args.force, created)
            if args.command == "attach":
                attach(args.name, dataset, datasetbackup, args.force)