<?php
/*
 * cmspass.php
 *
 * allows changing of cms passwords via cmd line
 *
 * Andrew D.
 *
 * Edit: 2/12/2016 - By Tom B.
 * - Added Drupal CMS to the list
 * - Added recursion to find and change all CMS password on the account
 *
 * Edit: 2/12/2016 - By Tom B.
 * - Security flaw found in using require
 *    - Updated script to no longer be recursive
 *    - Intended to be called directly by Cmscheck script on a installation directory
 * - Script currently checks to ensure it is not being run as root
 *    - Cmscheck script will run this as the user we are scanning
 * - Formatting of output also slightly changed for aesthetics
 *
 * Edit: 8/01/2017 - By Tom B.
 * - Updated deprecated mysql_ calls to mysqli_ calls
 *
 * Edit: 9/20/2017 - By Joe B.
 * - Updated scoping of adminQuery to prevent errors
 */

abstract class BaseCMS {

    protected $host;
    protected $user;
    protected $pass;
    protected $dbname;
    protected $location;
    protected $prefix;
    protected $cms;
    protected $uname;

    protected function randpass(){
        $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
            'abcdefghijklmnopqrstuvwxyz0123456789';

        $str = '';
        $count = strlen($charset);
        for ($i = 0; $i <= 9; $i++) {
            $str .= $charset[mt_rand(0, $count-1)];
        }

        return $str;
    }

    abstract protected function adminQuery(mysqli $con);
    abstract protected function chpassQuery($data, $password);

    public function run() {

        $con = mysqli_connect($this->host, $this->user, $this->pass, $this->dbname)
            or die(mysql_error());

        $result = mysqli_query($con, $this->adminQuery($con)) or die (mysql_error());

        print "Admin Passwords:\n";
        while ($data = mysqli_fetch_array($result)) {
            $password = $this->randpass();
            mysqli_query($con, $this->chpassQuery($data, $password)) or die (mysql_error());

            print "* ".$data[$this->uname]." : ".$password."\n";
        }

        mysqli_close($con);
    }
}


class WpCMS extends BaseCMS {

    function __construct($dir) {
        $this->location = dirname(realpath($dir."/wp-config.php"));
        $wpconfig = $this->wphack($dir."/wp-config.php");
        require($wpconfig);

        $this->host = DB_HOST;
        $this->user = DB_USER;
        $this->pass = DB_PASSWORD;
        $this->dbname = DB_NAME;
        $this->prefix = $table_prefix;
        $this->cms = "WordPress";
        $this->uname = "user_login";

        unlink('./wpresstmp.php');
    }

    protected function wphack($confFile) {
        $tmp = './wpresstmp.php';
        copy($confFile, $tmp);
        //$evil = "require_once(ABSPATH . 'wp-settings.php');";
        $evil = "/require_once\(\s*?ABSPATH.*?'wp-settings.php'\s*?\);/";
        $data = file_get_contents($tmp);
        //$data = str_replace($evil,"",$data);
        $data = preg_replace($evil,"",$data);
        file_put_contents($tmp, $data);

        return $tmp;
    }

    protected function adminQuery(mysqli $con) {
        return "SELECT um.user_id AS id, u.user_login FROM ".$this->prefix.
            "users u,".$this->prefix."usermeta um WHERE u.id = um.user_id ".
            "AND um.meta_key = '".$this->prefix."capabilities' AND ".
            "um.meta_value LIKE '%administrator%'";
    }

    protected function chpassQuery($data, $password) {
        return "UPDATE ".$this->prefix."users SET user_pass = MD5('".
            $password."') WHERE id=".$data['id'];
    }
}


class JoomlaCMS extends BaseCMS {

    function __construct($dir) {
        $this->location = dirname(realpath($dir."/configuration.php"));
        require($dir."/configuration.php");

        $joomla = new JConfig();
        $this->host = $joomla->host;
        $this->user = $joomla->user;
        $this->pass = $joomla->password;
        $this->dbname = $joomla->db;
        $this->prefix = $joomla->dbprefix;
        $this->cms = "Joomla";
        $this->uname = "username";
    }

    protected function adminQuery(mysqli $con) {

        if (mysqli_query($con, "DESCRIBE ".$this->prefix."core_acl_aro")) {
            return "SELECT id,username FROM ".$this->prefix."users WHERE usertype".
                " LIKE '%administrator%'";
        } else {
            return "SELECT id,username FROM ".$this->prefix."users LEFT JOIN ".
                $this->prefix."user_usergroup_map ON (id = user_id) WHERE ".
                "group_id = 8";
        }
    }

    protected function chpassQuery($data, $password) {

        return "UPDATE ".$this->prefix."users SET password=MD5('".$password.
            "') WHERE id=".$data['id'];

    }
}

class DrupalCMS extends BaseCMS {

    function __construct($dir) {
        require($dir."/sites/default/settings.php");
        require($dir."/includes/password.inc");
        require($dir."/includes/bootstrap.inc");

        $this->location = (realpath($dir));

        $this->host = $databases['default']['default']['host'];
        $this->user = $databases['default']['default']['username'];
        $this->pass = $databases['default']['default']['password'];
        $this->dbname = $databases['default']['default']['database'];
        $this->prefix = $databases['default']['default']['prefix'];
        $this->cms = "Drupal";
        $this->uname = "name";
    }

    protected function adminQuery(mysqli $con) {
        return "SELECT t1.uid, t1.name FROM ".$this->prefix."users AS t1
                    INNER JOIN ".$this->prefix."users_roles AS t2
                    ON t1.uid = t2.uid WHERE t2.rid = '3'";
    }

    protected function chpassQuery($data, $password) {
        $password = user_hash_password($password);

        return "UPDATE ".$this->prefix."users SET pass='".$password."' WHERE uid=".$data['uid'];
    }
}

class CMSFactory {

    public static function create($dir) {

        if (file_exists($dir.'/wp-config.php')) {
            return new WpCMS($dir);
        } elseif (file_exists($dir.'/configuration.php')) {
            return new JoomlaCMS($dir);
        } elseif (file_exists($dir.'/sites/default/settings.php')) {
            return new DrupalCMS($dir);
        } else {
            return null;
        }
    }
}

if (sizeof($argv) > 1) {
    $dir = $argv[1];
}
else {
    print "NO PATH PROVIDED!\n";
    exit();
}

if(function_exists('posix_getpwuid') && function_exists('posix_geteuid')) {
    $user = posix_getpwuid(posix_geteuid());

    if (strcmp(trim($user['name']), 'root') == 0) {
        print "Script executed as 'root' user.\n";
        print "Password option cannot be specified for this script when executed as 'root'.\n";
        print "Exiting script without making changes.\n\n";
        exit();
    }
}

$cms = CMSFactory::create($dir);

if($cms == null)
    print "NO CMS INSTALLATION FOUND!\n";
else
    $cms->run();