• Posts tagged "Tomcat"

Blog Archives

Java现实WebSocket

无所不能的Java系列文章,涵盖了Java的思想,应用开发,设计模式,程序架构等,通过我的经验去诠释Java的强大。

说起Java,真的有点不知道从何说起。Java是一门全领域发展的语言,从基础的来讲有4大块,Java语法,JDK,JVM,第三方类库。官方又以面向不同应用的角度,又把JDK分为JavaME,JavaSE,JavaEE三个部分。Java可以做客户端界面,可以做中间件,可以做手机系统,可以做应用,可以做工具,可以做游戏,可以做算法…,Java几乎无所不能。

在Java的世界里,Java就是一切。

关于作者

  • 张丹(Conan), 程序员Java,R,PHP,Javascript
  • weibo:@Conan_Z
  • blog: http://blog.fens.me
  • email: bsspirit@gmail.com

转载请注明出处:
http://blog.fens.me/java-websocket-intro/

java-websocket

前言

伴随着HTML5技术的新起,WebSocket 作为一种浏览器与服务器的核心通信技术,被嵌入到了浏览器的内核中。WebSocket 的出现使得浏览器提供对 Socket 的支持成为可能,从而在浏览器和服务器之间提供了一个基于 TCP 连接的双向通道。

所有新的技术都会第一时间在Java社区,出现对应的开源项目!WebSocket也被实现在多种Java的开源库中。WebSocket实现列表:https://java.net/projects/websocket-spec/pages/WebSocketAPIs/text。

今天就让我们用Java来解密一下WebSocket的服务器端和客户端 实现。

目录

  1. 服务器端实现(Tomcat)
  2. 客户端实现(Java-WebSocket)
  3. 客户端实现(Javascript原生API)

1. 服务器端实现(Tomcat)

用Java实现的websocket,在Server端是通过Tomcat内嵌支持的,我们需要开发一个继承WebSocketServlet 的servlet就可以了,与普通的HttpServlet没有太大区别。

1). JAVA环境:

  • Java: jdk 1.6.0_45, Server VM 64bit
  • Maven: 3.0.5
  • Tomcat: 7.0.39.0

~ D:\workspace\java>java -version
java version "1.6.0_45"
Java(TM) SE Runtime Environment (build 1.6.0_45-b06)
Java HotSpot(TM) 64-Bit Server VM (build 20.45-b01, mixed mode)

~ D:\workspace\java>mvn -version
Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 21:51:28+0800)
Maven home: D:\toolkit\maven3\bin\..
Java version: 1.6.0_45, vendor: Sun Microsystems Inc.
Java home: D:\toolkit\java\jdk6\jre
Default locale: zh_CN, platform encoding: GBK
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"

~ D:\toolkit\tomcat7\bin>catalina.bat version
Using CATALINA_BASE:   "D:\toolkit\tomcat7"
Using CATALINA_HOME:   "D:\toolkit\tomcat7"
Using CATALINA_TMPDIR: "D:\toolkit\tomcat7\temp"
Using JRE_HOME:        "D:\toolkit\java\jdk6"
Using CLASSPATH:       "D:\toolkit\tomcat7\bin\bootstrap.jar;D:\toolkit\tomcat7\bin\tomcat-juli.jar"
Server version: Apache Tomcat/7.0.39
Server built:   Mar 22 2013 12:37:24
Server number:  7.0.39.0
OS Name:        Windows 7
OS Version:     6.1
Architecture:   amd64
JVM Version:    1.6.0_45-b06
JVM Vendor:     Sun Microsystems Inc.

2). maven构建一个简单的webapp项目。


~ D:\workspace\java>mvn archetype:generate -DgroupId=org.conan.websocket -DartifactId=websocketServer -DarchetypeArtifactId=maven-archetype-webapp

[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-webapp:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: groupId, Value: org.conan.websocket
[INFO] Parameter: packageName, Value: org.conan.websocket
[INFO] Parameter: package, Value: org.conan.websocket
[INFO] Parameter: artifactId, Value: websocketServer
[INFO] Parameter: basedir, Value: D:\workspace\java
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: D:\workspace\java\websocketServer
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:42.200s
[INFO] Finished at: Tue Aug 20 13:57:05 CST 2013
[INFO] Final Memory: 9M/179M
[INFO] ------------------------------------------------------------------------

3). 配置项目目录


~ D:\workspace\java>cd websocketServer
~ D:\workspace\java\websocketServer>mkdir src\main\java
~ D:\workspace\java\websocketServer>rm src\main\webapp\index.jsp

导入到Eclipse的项目截图

ws1

4). 编辑pom.xml配置文件,增加tomcat的依赖


~ vi pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.conan.websocket</groupId>
<artifactId>websocketServer</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>websocketServer Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>7.0.27</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-coyote</artifactId>
<version>7.0.39</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>websocketServer</finalName>
</build>
</project>

下载并安装类库

~ D:\workspace\java\websocketServer>mvn clean install

5). 创建DemoServlet,服务器端运行类


~ vi src/main/java/org/conan/websocket/DemoServlet.java

package org.conan.websocket;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;

public class DemoServlet extends WebSocketServlet {

    private static final long serialVersionUID = -4853540828121130946L;
    private static ArrayList mmiList = new ArrayList();

    @Override
    protected StreamInbound createWebSocketInbound(String str, HttpServletRequest request) {
        return new MyMessageInbound();
    }

    private class MyMessageInbound extends MessageInbound {
        WsOutbound myoutbound;

        @Override
        public void onOpen(WsOutbound outbound) {
            try {
                System.out.println("Open Client.");
                this.myoutbound = outbound;
                mmiList.add(this);
                outbound.writeTextMessage(CharBuffer.wrap("Hello!"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onClose(int status) {
            System.out.println("Close Client.");
            mmiList.remove(this);
        }

        @Override
        public void onTextMessage(CharBuffer cb) throws IOException {
            System.out.println("Accept Message : " + cb);
            for (MyMessageInbound mmib : mmiList) {
                CharBuffer buffer = CharBuffer.wrap(cb);
                mmib.myoutbound.writeTextMessage(buffer);
                mmib.myoutbound.flush();
            }
        }

        @Override
        public void onBinaryMessage(ByteBuffer bb) throws IOException {
        }
    }

}

6). 修改web.xml文件


~ vi src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>wsServlet</servlet-name>
<servlet-class>org.conan.websocket.DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>wsServlet</servlet-name>
<url-pattern>/wsServlet</url-pattern>
</servlet-mapping>
</web-app>

7). 编译,打包,部署到tomcat


~ D:\workspace\java\websocketServer>mvn clean install
~ D:\workspace\java\websocketServer>cp target\websocketServer.war D:\toolkit\tomcat7\webapps

启动tomcat


~ D:\toolkit\tomcat7>bin\catalina.bat run
Using CATALINA_BASE:   "D:\toolkit\tomcat7"
Using CATALINA_HOME:   "D:\toolkit\tomcat7"
Using CATALINA_TMPDIR: "D:\toolkit\tomcat7\temp"
Using JRE_HOME:        "D:\toolkit\java\jdk6"
Using CLASSPATH:       "D:\toolkit\tomcat7\bin\bootstrap.jar;D:\toolkit\tomcat7\bin\tomcat-juli.jar"
2013-8-20 14:43:29 org.apache.catalina.core.AprLifecycleListener init
信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not fou
nd on the java.library.path: D:\toolkit\java\jdk6\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;D:\toolkit\
Rtools\bin;D:\toolkit\Rtools\gcc-4.6.3\bin;C:\Program Files (x86)\Common Files\NetSarang;C:\Windows\system32;C:\Windows;
C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;D:\toolkit\Git\cmd;D:\toolkit\Git\bin;C:\Program Fi
les (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Mi
crosoft SQL Server\100\DTS\Binn\;c:\Program Files (x86)\Common Files\Ulead Systems\MPEG;C:\Program Files (x86)\QuickTime
\QTSystem\;D:\toolkit\MiKTex\miktex\bin\x64\;D:\toolkit\sshclient;D:\toolkit\ant19\bin;D:\toolkit\eclipse;D:\toolkit\gra
dle15\bin;D:\toolkit\java\jdk6\bin;D:\toolkit\maven3\bin;D:\toolkit\mysql56\bin;D:\toolkit\python27;D:\toolkit\putty;C:\
Program Files\R\R-3.0.1\bin\x64;D:\toolkit\mongodb243\bin;D:\toolkit\php54;D:\toolkit\nginx140;D:\toolkit\nodejs;D:\tool
kit\npm12\bin;D:\toolkit\java\jdk6\jre\bin\server;.
2013-8-20 14:43:30 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-bio-8080"]
2013-8-20 14:43:30 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["ajp-bio-8009"]
2013-8-20 14:43:30 org.apache.catalina.startup.Catalina load
信息: Initialization processed in 1409 ms
2013-8-20 14:43:30 org.apache.catalina.core.StandardService startInternal
信息: Starting service Catalina
2013-8-20 14:43:30 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/7.0.39
2013-8-20 14:43:30 org.apache.catalina.startup.HostConfig deployWAR
信息: Deploying web application archive D:\toolkit\tomcat7\webapps\websocketServer.war
2013-8-20 14:43:30 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deploying web application directory D:\toolkit\tomcat7\webapps\docs
2013-8-20 14:43:30 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deploying web application directory D:\toolkit\tomcat7\webapps\examples
2013-8-20 14:43:31 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deploying web application directory D:\toolkit\tomcat7\webapps\host-manager
2013-8-20 14:43:31 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deploying web application directory D:\toolkit\tomcat7\webapps\manager
2013-8-20 14:43:31 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deploying web application directory D:\toolkit\tomcat7\webapps\ROOT
2013-8-20 14:43:31 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-bio-8080"]
2013-8-20 14:43:31 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["ajp-bio-8009"]
2013-8-20 14:43:31 org.apache.catalina.startup.Catalina start
信息: Server startup in 996 ms

websocket的服务地址:
ws://localhost:8080/websocketServer/wsServlet

2. 客户端实现(Java-WebSocket)

通过Java实现websocket的客户端,这里将介绍的是”Java-WebSocket”。另外,我发现Java7已经原生支持了websocket, “JSR 365, Java API for WebSocket” (看来要开始学学java7和java8了,我在java6的时代停滞3-4年了。)

现在我们使用“Java-WebSocket”

1). 修改pom.xml文件,增加jetty websocket依赖库


~ vi pom.xml
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.0</version>
</dependency>

下载依赖库

~ D:\workspace\java\websocketServer>mvn clean install

2). 新建文件,ChatClient.java


~ vi src/main/java/org/conan/websocket/ChatClient.java

package org.conan.websocket;

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.java_websocket.WebSocketImpl;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.drafts.Draft_75;
import org.java_websocket.drafts.Draft_76;
import org.java_websocket.handshake.ServerHandshake;

public class ChatClient extends JFrame implements ActionListener {
    private static final long serialVersionUID = -6056260699202978657L;

    private final JTextField uriField;
    private final JButton connect;
    private final JButton close;
    private final JTextArea ta;
    private final JTextField chatField;
    private final JComboBox draft;
    private WebSocketClient cc;

    public ChatClient( String defaultlocation ) {
        super( "WebSocket Chat Client" );
        Container c = getContentPane();
        GridLayout layout = new GridLayout();
        layout.setColumns( 1 );
        layout.setRows( 6 );
        c.setLayout( layout );

        Draft[] drafts = { new Draft_17(), new Draft_10(), new Draft_76(), new Draft_75() };
        draft = new JComboBox( drafts );
        c.add( draft );

        uriField = new JTextField();
        uriField.setText( defaultlocation );
        c.add( uriField );

        connect = new JButton( "Connect" );
        connect.addActionListener( this );
        c.add( connect );

        close = new JButton( "Close" );
        close.addActionListener( this );
        close.setEnabled( false );
        c.add( close );

        JScrollPane scroll = new JScrollPane();
        ta = new JTextArea();
        scroll.setViewportView( ta );
        c.add( scroll );

        chatField = new JTextField();
        chatField.setText( "" );
        chatField.addActionListener( this );
        c.add( chatField );

        java.awt.Dimension d = new java.awt.Dimension( 300, 400 );
        setPreferredSize( d );
        setSize( d );

        addWindowListener( new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing( WindowEvent e ) {
                if( cc != null ) {
                    cc.close();
                }
                dispose();
            }
        } );

        setLocationRelativeTo( null );
        setVisible( true );
    }

    public void actionPerformed( ActionEvent e ) {

        if( e.getSource() == chatField ) {
            if( cc != null ) {
                cc.send( chatField.getText() );
                chatField.setText( "" );
                chatField.requestFocus();
            }

        } else if( e.getSource() == connect ) {
            try {
                // cc = new ChatClient(new URI(uriField.getText()), area, ( Draft ) draft.getSelectedItem() );
                cc = new WebSocketClient( new URI( uriField.getText() ), (Draft) draft.getSelectedItem() ) {

                    @Override
                    public void onMessage( String message ) {
                        ta.append( "got: " + message + "\n" );
                        ta.setCaretPosition( ta.getDocument().getLength() );
                    }

                    @Override
                    public void onOpen( ServerHandshake handshake ) {
                        ta.append( "You are connected to ChatServer: " + getURI() + "\n" );
                        ta.setCaretPosition( ta.getDocument().getLength() );
                    }

                    @Override
                    public void onClose( int code, String reason, boolean remote ) {
                        ta.append( "You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason + "\n" );
                        ta.setCaretPosition( ta.getDocument().getLength() );
                        connect.setEnabled( true );
                        uriField.setEditable( true );
                        draft.setEditable( true );
                        close.setEnabled( false );
                    }

                    @Override
                    public void onError( Exception ex ) {
                        ta.append( "Exception occured ...\n" + ex + "\n" );
                        ta.setCaretPosition( ta.getDocument().getLength() );
                        ex.printStackTrace();
                        connect.setEnabled( true );
                        uriField.setEditable( true );
                        draft.setEditable( true );
                        close.setEnabled( false );
                    }
                };

                close.setEnabled( true );
                connect.setEnabled( false );
                uriField.setEditable( false );
                draft.setEditable( false );
                cc.connect();
            } catch ( URISyntaxException ex ) {
                ta.append( uriField.getText() + " is not a valid WebSocket URI\n" );
            }
        } else if( e.getSource() == close ) {
            cc.close();
        }
    }

    public static void main( String[] args ) {
        WebSocketImpl.DEBUG = true;
        String location;
        if( args.length != 0 ) {
            location = args[ 0 ];
            System.out.println( "Default server url specified: \'" + location + "\'" );
        } else {
            location = "ws://localhost:8887";
            System.out.println( "Default server url not specified: defaulting to \'" + location + "\'" );
        }
        new ChatClient( location );
    }
}

运行程序:
这里会启动一个Java的GUI界面。输入websocket服务的地址:ws://localhost:8080/websocketServer/wsServlet
ws6

查看Java客户端和HTML客户端的对话,在Java客户端中,输入”你好,小朋友”。
ws4

我们发现在html的客户端中,同样出现的”你好,小朋友”的消息记录。
ws5

这样,我们就在Java6的环境中,实现了Java WebSocket的客户端程序。

3. 客户端实现(Javascript原生API)

编写一个纯HTML的网页,通过浏览器原生的websocketAPI实现对websocket的服务的调用。

~ vi D:\workspace\javascript\tomcatClient.html

<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<title>Tomcat WebSocket Chat</title>
<script>
var ws = new WebSocket("ws://localhost:8080/websocketServer/wsServlet");
ws.onopen = function(){
};
ws.onmessage = function(message){
document.getElementById("chatlog").textContent += message.data + "\n";
};
function postToServer(){
ws.send(document.getElementById("msg").value);
document.getElementById("msg").value = "";
}
function closeConnect(){
ws.close();
}
</script>
</head>
<body>
<textarea id="chatlog" readonly></textarea><br/>
<input id="msg" type="text" />
<button type="submit" id="sendButton" onClick="postToServer()">Send!</button>
<button type="submit" id="sendButton" onClick="closeConnect()">End</button>
</body>
</html>

通过浏览器刚刚编写的文件:file:///D:/workspace/javascript/tomcatClient.html

打开两个窗口:
ws2

在右边窗口输入”我是BBB”,然后点击send。左边,右这,和后台日志,同时增加了”我是BBB”。
ws3

原来在浏览器上面,实现聊天功能是如此地简单!!

转载请注明出处:
http://blog.fens.me/nodejs-websocket-intro/

打赏作者

昨日终于找到攻击服务器的黑手了

近期服务器,总是收到IO,CPU的报警。

每天某一时刻,IO,CPU, 网络负载值非常高,并不是我的应用流量大。唯一的原因就是服务器被攻击了。

下面4幅图为服务器异常时的状态。

traffic

traffic IPV6

IO

CPU

 

应用软件设置:

  • Open-SSH:    SSH登陆
  • MySQL:         数据库服务器
  • Tomcat:        Java Web服务器
  • Nginx:           Http服务器
  • php-cgi:       PHP脚本解析服务

 

服务器的端口设置:

~# netstat -nlt

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:1723 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN
tcp6 0 0 :::22 :::* LISTEN
tcp6 0 0 127.0.0.1:8005 :::* LISTEN
tcp6 0 0 :::8009 :::* LISTEN
tcp6 0 0 :::8080 :::* LISTEN

 

找到攻击源:

发现在tomcat7/webapps下面,部署了一个我不认识的应用。

找到tomcat7/logs日志,查看是否有使用过Tomcat管理后台


~ tomcat7/logs# ls manager*

manager.2012-07-01.log  manager.2013-04-01.log  manager.2013-04-25.log
manager.2012-08-21.log  manager.2013-04-05.log  manager.2013-04-26.log
manager.2012-10-31.log  manager.2013-04-08.log  manager.2013-04-30.log
manager.2012-11-01.log  manager.2013-04-09.log  manager.2013-05-01.log
manager.2012-12-26.log  manager.2013-04-16.log  manager.2013-05-06.log
manager.2013-01-23.log  manager.2013-04-17.log  manager.2013-05-07.log
manager.2013-03-01.log  manager.2013-04-23.log

真被我发现了!!这么多文件操作,我自己并没有这么多的使用。

我们看一下黑客在管理后台干了什么。


~ /tomcat7/logs# vi manager.2013-05-06.log

May 6, 2013 2:20:48 PM org.apache.catalina.core.ApplicationContext log
INFO: HTMLManager: list: Listing contexts for virtual host 'localhost'
May 6, 2013 2:33:45 PM org.apache.catalina.core.ApplicationContext log
INFO: HTMLManager: list: Listing contexts for virtual host 'localhost'
May 6, 2013 2:34:00 PM org.apache.catalina.core.ApplicationContext log
SEVERE: HTMLManager: FAIL - Deploy Upload Failed, Exception: java.io.FileNotFoundException: /root/toolkit/tomcat7/webapps/51.war (Permission denied)
java.io.IOException: java.io.FileNotFoundException: /root/toolkit/tomcat7/webapps/51.war (Permission denied)
	at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:123)
	at org.apache.catalina.manager.HTMLManagerServlet.upload(HTMLManagerServlet.java:332)
	at org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:211)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:186)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
	at java.lang.Thread.run(Thread.java:662)
Caused by: java.io.FileNotFoundException: /root/toolkit/tomcat7/webapps/51.war (Permission denied)
	at java.io.FileOutputStream.open(Native Method)
	at java.io.FileOutputStream.(FileOutputStream.java:194)
	at java.io.FileOutputStream.(FileOutputStream.java:145)
	at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.write(DiskFileItem.java:457)
	at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:121)
	... 26 more
May 6, 2013 2:34:00 PM org.apache.catalina.core.ApplicationContext log
INFO: HTMLManager: list: Listing contexts for virtual host 'localhost'

上传名叫 51.war 的包程序在到tomcat/webapps目录。

再来找到黑客是如何获得后台访问权限的


~ vi localhost_access_log.2013-05-06.txt

218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - tomcat [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 200 19009
218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - - [06/May/2013:14:20:49 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - - [06/May/2013:14:33:39 +0000] "GET /manager/html HTTP/1.1" 401 2486
218.15.154.174 - tomcat [06/May/2013:14:33:45 +0000] "GET /manager/html HTTP/1.1" 200 17513
218.15.154.174 - tomcat [06/May/2013:14:33:46 +0000] "GET /manager/images/tomcat.gif HTTP/1.1" 200 2066
218.15.154.174 - tomcat [06/May/2013:14:33:46 +0000] "GET /manager/images/asf-logo.gif HTTP/1.1" 200 7279
218.15.154.174 - tomcat [06/May/2013:14:34:00 +0000] "POST /manager/html/upload?org.apache.catalina.filters.CSRF_NONCE=64E6C202103BF3113A72485F80F5133F HTTP/1.1" 200 17638
218.15.154.174 - - [06/May/2013:14:34:11 +0000] "GET /doc HTTP/1.1" 302 -
218.15.154.174 - - [06/May/2013:14:34:11 +0000] "GET /doc/ HTTP/1.1" 200 3309

黑客的扫描程序实验多次后,终于发现了管理后台的密码,并成功登陆
218.15.154.174 – tomcat [06/May/2013:14:20:49 +0000] “GET /manager/html HTTP/1.1” 200 19009

上传自己的程序包
218.15.154.174 – tomcat [06/May/2013:14:34:00 +0000] “POST /manager/html/upload?org.apache.catalina.filters.CSRF_NONCE=64E6C202103BF3113A72485F80F5133F HTTP/1.1” 200 17638

发现黑客的手段后,果断采取防御措施

1. 暂停tomcat的运行
2. 进入webapps目录,删除黑客上传的文件和文件包
3. 分析日志找到攻击者的IP
4. 把这些IP加到iptabls黑名单中
5. 关闭Tomcat管理控制台

分析日志找到攻击者的IP

183.191.4.235
58.180.70.160
113.30.74.125
113.30.106.92
124.160.217.200
218.15.154.174
61.187.94.66
180.179.206.10
187.188.175.49
65.126.238.4
61.167.33.222
54.228.209.57
95.211.121.136
77.79.125.2
218.15.154.174
222.184.121.15
182.140.241.19
121.199.27.236
116.55.226.215
124.129.18.178
109.186.134.160
61.187.94.66
101.226.33.208
101.226.51.226
112.64.235.89
14.63.196.181
113.30.106.90
109.186.134.160
58.180.70.160
49.156.145.2
61.191.31.27
14.17.18.152
113.30.106.95
61.187.94.66
61.187.94.66
101.226.65.106
180.153.163.191
110.4.89.42
61.187.94.66
109.186.134.160
80.241.209.155
85.17.156.16
218.15.154.174
121.199.27.236
61.187.94.66
113.30.74.125
61.191.31.27
121.189.59.207
82.80.248.188
203.174.60.2
182.140.241.19
124.129.18.178
14.63.196.181
49.156.145.2
199.254.238.207
206.172.16.30
61.167.33.222
203.174.60.2
65.126.238.4
59.188.29.254
118.180.7.60
221.12.174.123
46.32.254.6
59.188.29.254
223.16.9.122

把这些IP加到黑名单中


iptables -I INPUT -s 183.191.4.235 -j DROP
iptables -I INPUT -s 58.180.70.160 -j DROP
iptables -I INPUT -s 113.30.74.125 -j DROP
iptables -I INPUT -s 113.30.106.92 -j DROP
iptables -I INPUT -s 124.160.217.200 -j DROP
iptables -I INPUT -s 218.15.154.174 -j DROP
iptables -I INPUT -s 61.187.94.66 -j DROP
iptables -I INPUT -s 180.179.206.10 -j DROP
iptables -I INPUT -s 187.188.175.49 -j DROP
iptables -I INPUT -s 65.126.238.4 -j DROP
iptables -I INPUT -s 61.167.33.222 -j DROP
iptables -I INPUT -s 54.228.209.57 -j DROP
iptables -I INPUT -s 95.211.121.136 -j DROP
iptables -I INPUT -s 77.79.125.2 -j DROP
iptables -I INPUT -s 222.184.121.15 -j DROP
iptables -I INPUT -s 182.140.241.19 -j DROP
iptables -I INPUT -s 121.199.27.236 -j DROP
iptables -I INPUT -s 116.55.226.215 -j DROP
iptables -I INPUT -s 124.129.18.178 -j DROP
iptables -I INPUT -s 109.186.134.160 -j DROP
iptables -I INPUT -s 101.226.33.208 -j DROP
iptables -I INPUT -s 101.226.51.226 -j DROP
iptables -I INPUT -s 112.64.235.89 -j DROP
iptables -I INPUT -s 14.63.196.181 -j DROP
iptables -I INPUT -s 113.30.106.90 -j DROP
iptables -I INPUT -s 49.156.145.2 -j DROP
iptables -I INPUT -s 61.191.31.27 -j DROP
iptables -I INPUT -s 14.17.18.152 -j DROP
iptables -I INPUT -s 113.30.106.95 -j DROP
iptables -I INPUT -s 101.226.65.106 -j DROP
iptables -I INPUT -s 180.153.163.191 -j DROP
iptables -I INPUT -s 110.4.89.42 -j DROP
iptables -I INPUT -s 80.241.209.155 -j DROP
iptables -I INPUT -s 85.17.156.16 -j DROP
iptables -I INPUT -s 121.189.59.207 -j DROP
iptables -I INPUT -s 82.80.248.188 -j DROP
iptables -I INPUT -s 203.174.60.2 -j DROP
iptables -I INPUT -s 14.63.196.181 -j DROP
iptables -I INPUT -s 199.254.238.207 -j DROP
iptables -I INPUT -s 206.172.16.30 -j DROP
iptables -I INPUT -s 59.188.29.254 -j DROP
iptables -I INPUT -s 118.180.7.60 -j DROP
iptables -I INPUT -s 221.12.174.123 -j DROP
iptables -I INPUT -s 46.32.254.6 -j DROP
iptables -I INPUT -s 223.16.9.122 -j DROP

iptables -I INPUT -s 50.23.210.133 -j DROP
iptables -I INPUT -s 208.109.219.192 -j DROP
iptables -I INPUT -s 50.87.248.103 -j DROP
iptables -I INPUT -s 182.50.130.77 -j DROP
iptables -I INPUT -s 50.87.248.181 -j DROP
iptables -I INPUT -s 50.87.90.193 -j DROP
iptables -I INPUT -s 220.177.198.84 -j DROP
iptables -I INPUT -s 50.62.208.135 -j DROP
iptables -I INPUT -s 162.218.210.232 -j DROP
iptables -I INPUT -s 184.168.193.131 -j DROP
iptables -I INPUT -s 50.63.197.206 -j DROP
iptables -I INPUT -s 174.143.240.181 -j DROP
iptables -I INPUT -s 205.144.171.18 -j DROP
iptables -I INPUT -s 205.144.171.18 -j DROP
iptables -I INPUT -s 108.168.219.178 -j DROP
iptables -I INPUT -s 203.198.63.60 -j DROP
iptables -I INPUT -s 119.18.52.114 -j DROP
iptables -I INPUT -s 91.237.52.5 -j DROP
iptables -I INPUT -s 14.102.254.210 -j DROP
iptables -I INPUT -s 108.168.219.178 -j DROP
iptables -I INPUT -s 173.201.196.146 -j DROP
iptables -I INPUT -s 114.215.113.131 -j DROP
iptables -I INPUT -s 184.168.200.185 -j DROP
iptables -I INPUT -s 139.223.200.149 -j DROP
iptables -I INPUT -s 184.168.27.57 -j DROP
iptables -I INPUT -s 122.155.3.113 -j DROP
iptables -I INPUT -s 113.11.250.65 -j DROP
iptables -I INPUT -s 123.30.209.152 -j DROP
iptables -I INPUT -s 184.168.27.57 -j DROP
iptables -I INPUT -s 122.155.3.113 -j DROP
iptables -I INPUT -s 113.11.250.65 -j DROP
iptables -I INPUT -s 123.30.209.152 -j DROP
iptables -I INPUT -s 103.254.12.144 -j DROP
iptables -I INPUT -s 184.168.27.164 -j DROP
iptables -I INPUT -s 107.170.218.152 -j DROP
iptables -I INPUT -s 72.167.232.144 -j DROP
iptables -I INPUT -s 184.168.200.133 -j DROP
iptables -I INPUT -s 175.102.35.39 -j DROP
iptables -I INPUT -s 184.168.193.208 -j DROP

iptables -I INPUT -s 193.0.61.97 -j DROP
iptables -I INPUT -s 184.168.152.201 -j DROP
iptables -I INPUT -s 31.24.128.43 -j DROP
iptables -I INPUT -s 184.168.193.169 -j DROP
iptables -I INPUT -s 185.76.77.160 -j DROP
iptables -I INPUT -s 208.64.62.17 -j DROP
iptables -I INPUT -s 50.62.176.218 -j DROP
iptables -I INPUT -s 50.76.12.242 -j DROP
iptables -I INPUT -s 208.180.34.230  -j DROP
iptables -I INPUT -s 157.7.188.28 -j DROP
iptables -I INPUT -s 184.168.46.193  -j DROP
iptables -I INPUT -s 184.168.27.26 -j DROP
iptables -I INPUT -s 109.2.222.226 -j DROP
iptables -I INPUT -s 50.62.177.130 -j DROP
iptables -I INPUT -s 188.132.236.186 -j DROP
iptables -I INPUT -s 50.97.138.113 -j DROP
iptables -I INPUT -s 72.167.232.225  -j DROP
iptables -I INPUT -s 182.50.132.104  -j DROP
iptables -I INPUT -s 184.168.193.122 -j DROP
iptables -I INPUT -s 184.168.27.144  -j DROP
iptables -I INPUT -s 63.251.175.215  -j DROP
iptables -I INPUT -s 88.208.252.228  -j DROP
iptables -I INPUT -s 101.50.1.11 -j DROP
iptables -I INPUT -s 218.5.79.103 -j DROP
iptables -I INPUT -s 184.168.193.59  -j DROP
iptables -I INPUT -s 97.74.24.214 -j DROP
iptables -I INPUT -s 50.63.196.134 -j DROP
iptables -I INPUT -s 113.10.222.214  -j DROP
iptables -I INPUT -s 184.168.46.92 -j DROP
iptables -I INPUT -s 50.63.197.67 -j DROP
iptables -I INPUT -s 184.168.192.45  -j DROP
iptables -I INPUT -s 182.50.130.111  -j DROP
iptables -I INPUT -s 37.77.3.133 -j DROP
iptables -I INPUT -s 182.50.130.14 -j DROP
iptables -I INPUT -s 184.168.193.121 -j DROP
iptables -I INPUT -s 182.50.130.114  -j DROP
iptables -I INPUT -s 69.16.197.227 -j DROP
iptables -I INPUT -s 97.74.24.172 -j DROP
iptables -I INPUT -s 50.62.208.191 -j DROP
iptables -I INPUT -s 50.62.161.7 -j DROP
iptables -I INPUT -s 82.200.247.241  -j DROP
iptables -I INPUT -s 216.245.192.26  -j DROP
iptables -I INPUT -s 122.155.16.127  -j DROP
iptables -I INPUT -s 50.62.177.161 -j DROP
iptables -I INPUT -s 50.22.62.68 -j DROP
iptables -I INPUT -s 5.101.157.89 -j DROP
iptables -I INPUT -s 70.32.98.71 -j DROP
iptables -I INPUT -s 50.62.176.42 -j DROP
iptables -I INPUT -s 50.62.161.74 -j DROP
iptables -I INPUT -s 106.186.125.120 -j DROP
iptables -I INPUT -s 94.103.47.8 -j DROP
iptables -I INPUT -s 23.101.136.55 -j DROP
iptables -I INPUT -s 185.50.196.214  -j DROP
iptables -I INPUT -s 184.168.200.12  -j DROP
iptables -I INPUT -s 103.233.98.157  -j DROP
iptables -I INPUT -s 50.62.161.38 -j DROP
iptables -I INPUT -s 50.206.14.7 -j DROP
iptables -I INPUT -s 118.186.240.109 -j DROP
iptables -I INPUT -s 182.50.130.114 -j DROP
iptables -I INPUT -s 173.230.136.186 -j DROP
iptables -I INPUT -s 50.63.197.69 -j DROP
iptables -I INPUT -s 194.247.174.66 -j DROP


~ iptables-save > /etc/iptables.up.rules

~ iptables -L

Chain INPUT (policy ACCEPT)
target     prot opt source               destination
DROP       all  --  223.16.9.122         anywhere
DROP       all  --  327458.vps-10.com    anywhere
DROP       all  --  221.12.174.123       anywhere
DROP       all  --  118.180.7.60         anywhere
DROP       all  --  smtp.efaxonline.com  anywhere
DROP       all  --  van-router-01.boats.com  anywhere
DROP       all  --  seattle207.riseup.net  anywhere
DROP       all  --  14.63.196.181        anywhere
DROP       all  --  203.174.60.2         anywhere
DROP       all  --  bzq-82-80-248-188.static.dcenter.bezeqint.net  anywhere      
DROP       all  --  121.189.59.207       anywhere
DROP       all  --  hosted-by.leaseweb.com  anywhere
DROP       all  --  ip-155-209-241-80.static.contabo.net  anywhere
DROP       all  --  110.4.89.42          anywhere
DROP       all  --  180.153.163.191      anywhere
DROP       all  --  101.226.65.106       anywhere
DROP       all  --  113.30.106.95        anywhere
DROP       all  --  14.17.18.152         anywhere
DROP       all  --  61.191.31.27         anywhere
DROP       all  --  smtpmail8102.brixmail.com  anywhere
DROP       all  --  113.30.106.90        anywhere
DROP       all  --  14.63.196.181        anywhere
DROP       all  --  112.64.235.89        anywhere
DROP       all  --  101.226.51.226       anywhere
DROP       all  --  101.226.33.208       anywhere
DROP       all  --  109-186-134-160.bb.netvision.net.il  anywhere
DROP       all  --  124.129.18.178       anywhere
DROP       all  --  215.226.55.116.broad.km.yn.dynamic.163data.com.cn  anywhere  
DROP       all  --  121.199.27.236       anywhere
DROP       all  --  182.140.241.19       anywhere
DROP       all  --  222.184.121.15       anywhere
DROP       all  --  reverse-77-79-125-2.grid.com.tr  anywhere
DROP       all  --  95.211.121.136       anywhere
DROP       all  --  ec2-54-228-209-57.eu-west-1.compute.amazonaws.com  anywhere  
DROP       all  --  61.167.33.222        anywhere
DROP       all  --  wickedgoodcharcoal.com  anywhere
DROP       all  --  fixed-188-175-49.iusacell.net  anywhere
DROP       all  --  180.179.206.10       anywhere
DROP       all  --  61.187.94.66         anywhere
DROP       all  --  218.15.154.174       anywhere
DROP       all  --  124.160.217.200      anywhere
DROP       all  --  113.30.106.92        anywhere
DROP       all  --  113.30.74.125        anywhere
DROP       all  --  58.180.70.160        anywhere
DROP       all  --  235.4.191.183.adsl-pool.sx.cn  anywhere
DROP       all  --  124.115.0.199        anywhere
DROP       all  --  cust.static.62-202-18-26.swisscomdata.ch  anywhere           
DROP       all  --  60-199-223-196.static.tfn.net.tw  anywhere
DROP       all  --  148.208.222.7        anywhere
DROP       all  --  woman22.ru           anywhere

关闭Tomcat管理控制台

把tomcat-users.xml文件的内容都注释掉。

vi ~/tomcat7/conf/tomcat-users.xml

<tomcat-users>

<!–
<role rolename=”manager-gui”/>
<user username=”tomcat” password=”bsspirit” roles=”manager-gui”/>
<user username=”both” password=”tomcat” roles=”tomcat,role1″/>
<user username=”role1″ password=”tomcat” roles=”role1″/>
–>

</tomcat-users>

重启Tomcat服务器!完成Tomcat防御。

服务器的root账号,并没有被破解。为了安全还是换一个吧,攻击手段并不高明,只是我们疏于防范了。

再次给使用TOMCAT的用户提个醒,平时不要打开管理控制台,会被黑客当枪用的。

打赏作者