安泰信息

2008年12月16日

apache静态文件压缩,提高网络流量

归档在: apache, jboss — JACKEYJ @ 4:28 PM

    本文主要介绍如何通过对页面进行压缩从而节省网站的带宽以及提升用户的访问速度。

网站的访问速度是由多个因素所共同决定的,这些因素例如应用程序的响应速度、网络带宽、服务器性能、与客户端之间的网络传输速度等等。其中最重要的一个因素是应用程序本身的响应速度,因此当你为网站性能所苦恼时,你第一个需要着手进行处理的便是尽可能的提升应用程序的执行速度,你可以使用缓存或者是优化代码的执行效率来提升应用程序的速度。

但是,本文并不是介绍如何来提升应用程序的执行效率,前面提到的只不过是为了防止您病急乱投医。在确保您的应用程序的性能已经达到足够好,同时服务器的性能也完全满足的情况下,不妨来试试网页压缩来进一步提升网页的浏览速度,而且非常重要的是,它完全不需要任何的成本,只不过是会让您的服务器CPU 占用率稍微提升一两个百分点而已或者更少。

网页压缩是一项由 WEB 服务器和浏览器之间共同遵守的协议,也就是说 WEB 服务器和浏览器都必须支持该技术,所幸的是现在流行的浏览器都是支持的,包括 IE、FireFox、Opera 等;服务器有 Apache 和 IIS 等。双方的协商过程如下:

   1. 首先浏览器请求某个 URL 地址,并在请求的头 (head) 中设置属性 accept-encoding 值为 gzip, deflate,表明浏览器支持 gzip 和 deflate 这两种压缩方式(事实上 deflate 也是使用 gzip 压缩协议,下面我们会介绍二者之间的区别);
   2. WEB 服务器接收到请求后判断浏览器是否支持压缩,如果支持就传送压缩后的响应内容,否则传送不经过压缩的内容;
   3. 浏览器获取响应内容后,判断内容是否被压缩,如果是则解压缩,然后显示响应页面的内容。

在实际的应用中我们发现压缩的比率往往在 3 到 10 倍,也就是本来 50k 大小的页面,采用压缩后实际传输的内容大小只有 5 至 15k 大小,这可以大大节省服务器的网络带宽,同时如果应用程序的响应足够快时,网站的速度瓶颈就转到了网络的传输速度上,因此内容压缩后就可以大大的提升页面的浏览速度。

接下来我们介绍几种常用的环境下如何启用网页压缩功能。

纯 Tomcat 服务器

如果您的 WEB 应用程序是跑在 Tomcat 服务器下的,而且直接使用 Tomcat 所提供的 HTTP 服务,那建议你马上动手,因为实在是太简单了,你只需要在 server.xml 配置文件中给 HTTP Connector 增加一个 compression 的参数值为 on 并重启 Tomcat 服务器就立刻生效,配置如下:

    <Connector port=”8080″ protocol=”HTTP/1.1″
               maxThreads=”150″ connectionTimeout=”20000″
               redirectPort=”8443″ compression=”on”/>

Tomcat 采用的是 HTTP/1.1 的 GZIP 压缩协议,它会根据浏览器送过来的请求中的 accept-encoding 值是否包含 gzip 来判断浏览器是否支持 gzip 压缩协议,如果浏览器支持就启用 gzip 压缩,否则就不进行任何压缩处理。Tomcat 中还有另外一个参数 compressableMimeType,这个参数可以用来指定压缩哪种类型的内容,例如可以指定该配置值为:text/html,text /plain ,则只压缩 contentType 为 text/html 和 text/plain 的页面,不过您最好也将 css 和 javascript 文件也算在压缩的文件类型中,因为这两者的压缩效果也十分的明显。

    回页首

Apache 服务器

在 apache 1.3 版本,大家常用 mod_gzip 对输出内容进行压缩,现在主流的浏览器都支持 gzip 解压缩。在 apache2 下,这个模块换名为 mod_deflate,对应的模块文件名是 mod_deflate.so。mod_gzip 本文不做介绍,下面描述一下在 Apache 2 下如何启用并配置 mod_deflate 模块。默认安装的 Apache 不管是 Windows 还是 Linux/Unix,都是不启用该模块的, Linux/Unix 下甚至不带该模块,你需要手工编译这个模块。

下面我们分别介绍在 Windows 和 Linux 操作系统下如何启用并配置 mod_deflate 模块。

在 Windows 下采用安装程序安装的 Apache 服务器已经带有 deflate 所需要的模块 mod_deflate.so 和 mod_headers.so,我们只需要在 httpd.conf 配置文件中启用并进行相关的配置即可,配置如下:

LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
<Location />
# Insert filter
SetOutputFilter DEFLATE
# Netscape 4.x has some problems…
BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
BrowserMatch ^Mozilla/4\.0[678] no-gzip
# MSIE masquerades as Netscape, but it is fine
# BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# NOTE: Due to a bug in mod_setenvif up to Apache 2.0.48
# the above regex won’t work. You can use the following
# workaround to get the desired effect:
BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
# Don’t compress images
SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
# Make sure proxies don’t deliver the wrong content
Header append Vary User-Agent env=!dont-vary
</Location>

而如果是 Linux/Unix 操作系统,如果你没有在编译安装的过程中将所需要的两个模块 mod_deflate 和 mod_headers 编译进去的话,那就稍微有点麻烦,首先我们先看如何在编译安装 Apache 过程中也同时编译这两个模块,请在执行 configure 程序时增加两个参数分别是:

# ./configure –enable-deflate –enable-headers

这样在编译完 Apache 后就可以直接在 httpd.conf 中启用并配置 deflate 模块了,配置的方法跟 Windows 平台下是相同的。

如果说您的 Apache 已经在运行了,不想再重新编译一次,那也可以选择只编译 deflate 模块所需的文件 mod_deflate.c 和 mod_headers.c。这两个文件位于 {apache-src}/modules/filters/ 目录下(其中 {apache-src} 为 apache 源文件所在的目录)。使用如下命令来单独编译这两个源文件。

# {apache-bin}/apxs -i -a -c {apache-src}/modules/filters/mod_deflate.c
# {apache-bin}/apxs –i –a –c {apache-src}/modules/filters/mod_headers.c

其中 {apache-bin} 为 Apache 安装目录下的 bin 目录,接下来在 httpd.conf 直接配置该模块即可。

很多时候你在单独编译 deflate 模块的时候可能会碰到编译错误,提示是:

Cannot load /opt/apache/modules/mod_deflate.so into server: /opt/apache/modules/mod_deflate.so: undefined symbol: deflate

解决的方法如下:

编辑 /usr/local/apache2/bin/apr-config 文件修改其中的 LDFLAGS 值为 “-lz”,然后再重新编译 mod_deflate 模块,apxs -ica mod_deflate.c 即可。

为了省却不必要的麻烦,请尽量在编译安装时直接加上 –enable-deflate –enable-headers 参数。

我的实施内容:

#run cmd add mod to apache
/infowarelab/apache2/bin/apxs -i -a -c /infowarelab/src/httpd-2.2.3/modules/filters/mod_deflate.c
/infowarelab/apache2/bin/apxs -i -a -c /infowarelab/src/httpd-2.2.3/modules/metadata/mod_headers.c

#add conf in httpd.conf

<IfModule mod_deflate.c>
 DeflateCompressionLevel 7
 AddOutputFilterByType DEFLATE text/html text/plain text/xml text/javascript text/css application/x-httpd-php
 AddOutputFilter DEFLATE css js
</IfModule>

参考文档:
http://www.ibm.com/developerworks/cn/web/wa-lo-webcompress/
http://www.hbcms.org.cn/cms/9d/1322.html

2008年11月18日

Optimal mod_jk configuration

归档在: Linux, apache, jboss — JACKEYJ @ 9:03 AM

Optimal mod_jk configuration

 

There are many potential problems associated with the default configuration of mod_jk.  Let’s say it is perfectly adequate for a very low traffic website, but when pushing any moderate to high load to mod_jk, there will be connection problems.  This is not due to any bug in mod_jk whatsoever, however, it is because the default configuration makes no assumption about your existing hardware or potential load, so, therefore, it is not tuned accordingly.

 

Note that the configuration recommendations here are optimal as a base configuration to avoid many of the common problems users experience with mod_jk. There exist many other useful optimizations, but these depend on the environment and web application in use. See http://tomcat.apache.org/connectors-doc/reference/workers.html for details on all available mod_jk properties.

 

Let’s take a look at a typical default configuration for Apache/Tomcat/mod_jk:
workers.properties

worker.list=loadbalancer,status

worker.node1.port=8009
worker.node1.host=node1.mydomain.com
worker.node1.type=ajp13
worker.node1.lbfactor=1

worker.node2.port=8009
worker.node2.host= node2.mydomain.com
worker.node2.type=ajp13
worker.node2.lbfactor=1

worker.loadbalancer.type=lb
worker.loadbalancer.balance_workers=node1,node2

worker.status.type=status

 
JBoss Web’s (Tomcat) server.xml AJP snippet:

<Connector port=”8009″ address=”${jboss.bind.address}” protocol=”AJP/1.3″
         emptySessionPath=”true” enableLookups=”false” redirectPort=”8443″ ></Connector>

 
Apache’s httpd.conf:

<IfModule prefork.c>
StartServers       8
MinSpareServers    5
MaxSpareServers   20
ServerLimit      256
MaxClients       256
MaxRequestsPerChild  4000
</IfModule>

 

 

The above configuration, under load, may cause mod_jk to be very slow and unresponsive, cause http errors, and cause half-closed connections.   These problems can arise because there are no connection timeouts specified to take care of orphaned connections, no error handling properties defined in workers.properties, and no connection limits set in Apache and Tomcat.

 

 

First off, lets take care of Tomcat:

 
Configuring server.xml:

 

The main concern with server.xml is setting the connectionTimeout which

sets the SO_TIMEOUT of the underlying socket.  So when a connection in

Tomcat hasn’t had a request in the amount of time specified by

connectionTimeout, then the connection dies off.  This is necessary because if the connection hasn’t been used for a certain period of

time then there is the chance that it is half-close on the mod_jk end.

If the connection isn’t closed there will be an inflation of threads

which can over time hit the maxThreads count in Tomcat then Tomcat will

not be able to accept any new connections.  A connectionTimeout of 600000 (10 minutes) is a good number to start out with.  There may be a situation where the connections are not being recycled fast enough, in this instance the connectionTimeout could be lowered to 60000 or 1 minute.

 

When setting connectionTimeout in Tomcat, mod_jk should also have

connect_timeout/prepost_timeout set, which allows detection that the

Tomcat connection has been closed and preventing a retry request.

 

The recommended value of maxThreads is 200 per CPU, so here we assume the server is a single core machine.  If it has been quad core, we could push that value to 800, and more depending on RAM and other machine specs.

 

<Connector port=”8009″
           address=”${jboss.bind.address}”
           emptySessionPath=”true”
           enableLookups=”false”
           redirectPort=”8443″
           protocol=”AJP/1.3″
           maxThreads=”200″
           connectionTimeout=”600000″></Connector>

 

 

 

 
Configuring workers.properties:

 

See comments inline.

 

worker.list=loadbalancer,status

worker.template.port=8009
worker.template.type=ajp13
worker.template.lbfactor=1
worker.template.ping_timeout=1000
#ping_mode was introduced in 1.2.27, if not using 1.2.27 please specify connect_timeout=10000 and prepost_timeout=10000 as an alternative

worker.template.ping_mode=A
worker.template.socket_timeout=10
#It is not necessary to specify connection_pool_timeout if you are running the worker mpm
worker.connection_pool_timeout=600

#Referencing the template worker properties makes the workers.properties shorter and more concise
worker.node1.reference=worker.template
worker.node1.host=192.168.1.2

worker.node2.reference=worker.template
worker.node2.host=192.168.1.3

worker.loadbalancer.type=lb
worker.loadbalancer.balance_workers=node1,node2

worker.status.type=status

 

The key points in the above workers.properties is we’ve added limits for the connections mod_jk makes.  With the base configuration, socket timeouts default to infinite. The other important properties are ping_mode and ping_timeout which handle probing a connection for errors and connection_pool_timeout which must be set to equal server.xml’s connectionTimeout when using the prefork mpm.  When these two values are the same, after a connection has been inactive for x amount of time, the connection in mod_jk and Tomcat will be closed at the same time, preventing a half-closed connection.

 

 

 
Configuring Apache

 

Make note that maxThreads for the AJP connection should coincide with

the MaxClients set in Apache’s httpd.conf.  MaxClients needs to be set

in the correct module in Apache.

 

 

This can be determined by running httpd -V:

 

# httpd -V

Server version: Apache/2.2.3
Server built:   Sep 11 2006 09:43:05
Server’s Module Magic Number: 20051115:3
Server loaded:  APR 1.2.7, APR-Util 1.2.8
Compiled using: APR 1.2.7, APR-Util 1.2.7
Architecture:   32-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with….
-D APACHE_MPM_DIR=”server/mpm/prefork”
-D APR_HAS_SENDFILE
-D APR_HAS_MMAP
-D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
-D APR_USE_SYSVSEM_SERIALIZE
-D APR_USE_PTHREAD_SERIALIZE
-D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
-D APR_HAS_OTHER_CHILD
-D AP_HAVE_RELIABLE_PIPED_LOGS
-D DYNAMIC_MODULE_LIMIT=128
-D HTTPD_ROOT=”/etc/httpd”
-D SUEXEC_BIN=”/usr/sbin/suexec”
-D DEFAULT_PIDLOG=”logs/httpd.pid”
-D DEFAULT_SCOREBOARD=”logs/apache_runtime_status”
-D DEFAULT_LOCKFILE=”logs/accept.lock”
-D DEFAULT_ERRORLOG=”logs/error_log”
-D AP_TYPES_CONFIG_FILE=”conf/mime.types”
-D SERVER_CONFIG_FILE=”conf/httpd.conf”

 

Which tells me the Server MPM is Prefork.  This is not always 100% accurate so you should also view the output of /etc/sysconfig/httpd to see if the following line is there: HTTPD=/usr/sbin/httpd.worker.  If it is commented out you are running prefork, otherwise if uncommented worker.

 

httpd.conf:

<IfModule prefork.c>
StartServers       8
MinSpareServers    5
MaxSpareServers   20
MaxClients       200
MaxRequestsPerChild  0
</IfModule>

 

Or if Apache is using worker, it is
<IfModule worker.c>
StartServers         2
MaxClients         200
MinSpareThreads     25
MaxSpareThreads     75
ThreadsPerChild     25
MaxRequestsPerChild  0
</IfModule>

 

MaxRequestsPerChild is 0, this is the recommended value when using

mod_jk as mod_jk keeps open persistent connections.  The key values in

the above configuration are MaxClients and MaxRequestsPerChild, the rest

of the values are left as default.  Note that MaxRequestsPerChild is

recommended to be 0 however the value may need to be greater than 0

depending on if Apache is used for other modules also, especially in the

case of resource leakage.

 

 
Advanced worker-mpm Configuration

 

To get the most out of your mod_jk setup you should be using Apache’s worker mpm which provides a definite performance improvement over the prefork mpm.  The following section will detail how to configure Apache/mod_jk/Tomcat with the worker mpm and the math behind the configuration.

 

Let’s start out with the worker mpm configuration

<IfModule mpm_worker_module>

ThreadLimit 100
StartServers 5
MaxClients 1000
MinSpareThreads 100
MaxSpareThreads 1000
ThreadsPerChild 100
MaxRequestsPerChild 0
</IfModule>

 

The optimal configuration completely depends on the hardware being used and the load requirements.  But a general rule of thumb, keep processes low and thread count high.  To determine the number of processes Apache will use simply divide MaxClients by ThreadPerChild.  So in this case MaxClients (1000) / ThreadsPerChild (100) = Processes (10), so Apache will allocate a maximum of 100 threads per each 10 child processes resulting in a total of 1000 possible clients.

 

Now to translate this to mod_jk, mod_jk maintains a connection pool for each worker defined in workers.properties.  By default with Apache mod_jk sets connection_pool_size to ThreadsPerChild, so in the above case that would translate to 100, giving 1000 possible connections to JBoss.  This may or may not be desired.

 

Let’s take a common example, there will be 3 JBoss servers that combined needed to be able to handle 900 concurrent connections

 

worker.list=loadbalancer,status
 

worker.template.type=ajp13
worker.template.port=8009
worker.template.ping_mode=A
worker.template.connection_pool_size=30
worker.template.socket_timeout=10
worker.template.retries=20
 

worker.node1.reference=worker.template
worker.node1.host=192.168.0.101

worker.node2.reference=worker.template
worker.node2.host=192.168.0.102

worker.node3.reference=worker.template
worker.node3.host=192.168.0.103
 

worker.loadbalancer.type=lb
worker.loadbalancer.balance_workers=node1,node2, node3
worker.sticky_session=True

worker.status.type=status

 

The above configuration tells mod_jk to multiplex 30 connections to the available Apache processes, which is 10 processes.  So that means 30 connections multiplexed over 10 processes gives 300 possible connections to each backend worker.  Furthermore, the total connections able to be used in this configuration from Apache is 900 which means  100 connections will be left over for static content or whatnot.

 

 

Next configure maxThreads in each ajp connector to match the above.

 

Node 1 ajp connector:

<Connector port=”8009″
           address=”${jboss.bind.address}”
           emptySessionPath=”true”
           enableLookups=”false”
           redirectPort=”8443″
           protocol=”AJP/1.3″
           maxThreads=”300″
           connectionTimeout=”600000″></Connector>

 

Node 2 ajp connector:

<Connector port=”8009″
           address=”${jboss.bind.address}”
           emptySessionPath=”true”
           enableLookups=”false”
           redirectPort=”8443″
           protocol=”AJP/1.3″
           maxThreads=”300″
           connectionTimeout=”600000″></Connector>

 

Node 3 ajp connector:

<Connector port=”8009″
           address=”${jboss.bind.address}”
           emptySessionPath=”true”
           enableLookups=”false”
           redirectPort=”8443″
           protocol=”AJP/1.3″
           maxThreads=”300″
           connectionTimeout=”600000″></Connector>

 

Remember when using connectionTimeout which is always recommended, prepost_timeout and connect_timeout also need to be set, which is done.  I’m not showing sticky session configuration, but that covered in the main mod_jk article in using mod_jk with JBoss.

 reference from :http://www.jboss.org/community/docs/DOC-11543

UsingMod_jk1.2WithAFirewall

归档在: Linux, apache, jboss — JACKEYJ @ 8:38 AM

Setting up mod_jk with a firewall:

 
Configuring workers.properties:

# Define list of workers that will be used
# for mapping requests
# The configuration directives are valid
# for the mod_jk version 1.2.18 and later
#
worker.list=loadbalancer,status

# Define Node1
# modify the host as your host IP or DNS name.
worker.node1.port=8009
#Using an IP prevents a DNS lookup
worker.node1.host=192.168.1.2
worker.node1.type=ajp13
worker.node1.lbfactor=1
worker.node1.connect_timeout=10000
worker.node1.prepost_timeout=10000
worker.node1.socket_keepalive=True

# Define Node2
# modify the host as your host IP or DNS name.
worker.node2.port=8009
worker.node2.host=192.168.1.3
worker.node2.type=ajp13
worker.node2.lbfactor=1
worker.node2.connect_timeout=10000
worker.node2.prepost_timeout=10000
worker.node2.socket_keepalive=True

# Load-balancing behaviour
worker.loadbalancer.type=lb
worker.loadbalancer.balance_workers=node1,node2

# Status worker for managing load balancer
worker.status.type=status

 

 

socket_keepalive=true is the most important setting. connect_timeout and

prepost_timeout are to “work-around” firewalls that

ignore keepalives or close the connection for unknown reasons.

 

 

 
Configuring server.xml:

The main concern with server.xml is setting the connectionTimeout which

sets the SO_TIMEOUT of the underlying socket.  So when a connection in

Tomcat hasn’t had a request in the amount of time specified by

connectionTimeout, then the connection dies off.  Why is this a good

thing?…because if the connection hasn’t been used for a certain period of

time then there is the chance that it is half-close on the mod_jk end.

If the connection isn’t closed there will be an inflation of threads

which can over time hit the maxThreads count in Tomcat then Tomcat will

not be able to accept any new connections.

 

When setting connectionTimeout in Tomcat, mod_jk should also have

connect_timeout/prepost_timeout set, which allows detection that the

Tomcat connection has been closed and preventing a retry request.

 

 

<Connector port=”8009″
           address=”${jboss.bind.address}”
           emptySessionPath=”true”
           enableLookups=”false”
           redirectPort=”8443″
           protocol=”AJP/1.3″
           maxThreads=”200″
           connectionTimeout=”60000″></Connector>

 
Configuring Apache

 

Make note that maxThreads for the AJP connection should coincide with

the MaxClients set in Apache’s httpd.conf.  MaxClients needs to be set

in the correct module in Apache. 

 

 

This can be determined by running httpd -V:

 

# httpd -V

Server version: Apache/2.2.3
Server built:   Sep 11 2006 09:43:05
Server’s Module Magic Number: 20051115:3
Server loaded:  APR 1.2.7, APR-Util 1.2.8
Compiled using: APR 1.2.7, APR-Util 1.2.7
Architecture:   32-bit
Server MPM:     Prefork
  threaded:     no
    forked:     yes (variable process count)
Server compiled with….
-D APACHE_MPM_DIR=”server/mpm/prefork”
-D APR_HAS_SENDFILE
-D APR_HAS_MMAP
-D APR_HAVE_IPV6 (IPv4-mapped addresses enabled)
-D APR_USE_SYSVSEM_SERIALIZE
-D APR_USE_PTHREAD_SERIALIZE
-D SINGLE_LISTEN_UNSERIALIZED_ACCEPT
-D APR_HAS_OTHER_CHILD
-D AP_HAVE_RELIABLE_PIPED_LOGS
-D DYNAMIC_MODULE_LIMIT=128
-D HTTPD_ROOT=”/etc/httpd”
-D SUEXEC_BIN=”/usr/sbin/suexec”
-D DEFAULT_PIDLOG=”logs/httpd.pid”
-D DEFAULT_SCOREBOARD=”logs/apache_runtime_status”
-D DEFAULT_LOCKFILE=”logs/accept.lock”
-D DEFAULT_ERRORLOG=”logs/error_log”
-D AP_TYPES_CONFIG_FILE=”conf/mime.types”
-D SERVER_CONFIG_FILE=”conf/httpd.conf”

 

Which tells me the Server MPM is Prefork

 

httpd.conf:

<IfModule prefork.c>
StartServers       8
MinSpareServers    5
MaxSpareServers   20
MaxClients       200
MaxRequestsPerChild  0
</IfModule>

 

Or if Apache is using worker, it is
<IfModule worker.c>
StartServers         2
MaxClients         200
MinSpareThreads     25
MaxSpareThreads     75
ThreadsPerChild     25
MaxRequestsPerChild  0
</IfModule>

 

MaxRequestsPerChild is 0, this is the recommended value when using

mod_jk as mod_jk keeps open persistent connections.  The key values in

the above configuration are MaxClients and MaxRequestsPerChild, the rest

of the values are left as default.  Note that MaxRequestsPerChild is

recommended to be 0 however the value may need to be greater than 0

depending on if Apache is used for other modules also, especially in the

case of resource leakage.

2008年10月24日

安泰资讯:jconsole使用实例

归档在: Linux, jboss, java — JACKEYJ @ 4:07 PM

转载自:www.dangdangwanggoushu.net

环境:
服务器端: CentOS4.2 + jdk1.5 + JBoss4.2.3GA
客户端: Windows xp sp3 + jdk1.5.0.6
==================================================================================
jconsole远程监视的配置步骤如下:
服务器端:
1. cp $JAVA_HOME/jre/lib/management/jmxremote.password.template \
$JAVA_HOME/www.dangdangwanggoushu.net.jmxremote.password
chmod 600 $JAVA_HOME/jmxremote.password #必须的,否则提示"Error: Password file read access must be restricted…"

2. vi jmxremote.password 去掉#monitorRole RED前的注释并将RED修改为你要设置的密码。(安全起见,只开放有只读权限的用户).由于权限是只读使用:wq!保存退出。

3. 修改 $JBOSS/bin/run.conf,在JAVA_OPT添加三个参数:
-Dcom.sun.management.jmxremote.port=1010
-Dcom.sun.management.jmxremote.password.file=$JAVA_HOME/www.dangdangwanggoushu.net.jmxremote.password   
-Dcom.sun.management.jmxremote.ssl=false

下面是我的jboss配置启动参数:
if [ "x$JAVA_OPTS" = "x" ]; then
   JAVA_OPTS="-Dcom.sun.management.jmxremote\
        -Dcom.sun.management.jmxremote.port=9010\
        -Dcom.sun.management.jmxremote.ssl=false\
        -Dcom.sun.management.jmxremote.authenticate=false\
        -server -Xms256m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=128m\
        -Djava.rmi.server.hostname=192.168.1.122"
fi

提示:如果是在其他机器上进行监控,则必须加上-Djava.rmi.server.hostname=IP项,否则提示无法连接。

4. 执行hostname -i ,如果显示的是127.0.0.1,则需要修改/etc/hosts文件

5. vi /etc/hosts,修改如下:
#127.0.0.1              localhost localhost.localdomain localhost www.dangdangwanggoushu.net

服务器的真实IP地址        localhost localhost.localdomain localhost www.dangdangwanggoushu.net
具体原因是服务器端解释机器名的问题,相关问题见: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6209663
服务器端配置参见: http://java.sun.com/j2se/1.5.0/docs/guide/management/agent.html#remote

6. 启动jboss 检查监听端口是否启动 netstat -na|grep 1010 查看1010端口是否已在监听

[root@download ~]# netstat -nap|grep 9010
tcp        0      0 0.0.0.0:9010                0.0.0.0:*                   LISTEN      15216/java

========================================================================================
客户端:
1. 到你的jdk安装路径bin目录下,运行jconsole

2. 指定连接参数
远程主机: 服务器的真实IP地址
端口: 9010 ($JAVA_ARGS中-Dcom.sun.management.jmxremote.port指定的端口)
用户名: monitorRole (jmxremote.password中指定的用户名)  #我配置的不需要认证,这个项目可以忽略
密码: your_password(jmxremote.password中设置的密码)    #我配置的不需要认证,这个项目可以忽略
3. 连接 -> OK

客户端配置参见: http://java.sun.com/j2se/1.5.0/docs/guide/management/jconsole.html
jconsole文档地址:http://java.sun.com/j2se/1.5.0/docs/tooldocs/share/jconsole.html

2008年09月25日

安泰信息:Debian Linux Apahe2.0.63 JBoss 4.2.2 Java 1.5 集群安装

归档在: Linux, apache, jboss, java, ubuntu — JACKEYJ @ 11:43 AM

Apahe2/JBoss/Java Cluster Guide

1 Download needed software

1.1 Jboss4.2.2 GA

Please go http://www.jboss.org/download/ to find the jboss-4.2.3.GA.zip to download.

 

1.2 Java SE 5.0 updated 16

Please go
https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewProductDetail-Start?ProductRef=jdk-1.5.0_16-oth-JPR@CDS-CDS_Developer

And select Platform with Linux, Language with Multi-language, then download
jdk-1_5_0_16-linux-i586.bin.

 

1.3 Apache httpd 2.0.63

Please go http://httpd.apache.org/download.cgi to find httpd-2.0.63.tar.gz to download.

 

1.4 Tomcat Connectors 1.2.9

Please go http://apache.deathculture.net/tomcat/tomcat-connectors/jk/source/jk-1.2.26/ to find tomcat-connectors-1.2.26-src.tar.gz to download

 

2 Java installation

Login debian OS with root user, then create a linux user. E.g ‘deploy’.

Login with ‘deploy’ account, then upload jdk-1_5_0_16-linux-i586.bin to home directory.

chmod 755 jdk-1_5_0_16-linux-i586.bin

./ jdk-1_5_0_16-linux-i586.bin

ln –s jdk-1_5_0_16-linux-i586 jdk

Extract java and link it to jdk as above. Then modify envirement variable on profile.

cd /home/deploy

vi .bash_profile

#add for Jboss and jdk begin

JAVA_HOME=/home/deploy/jdk;export JAVA_HOME

CLASSPATH=./:/home/deploy/jdk/lib/dt.jar:/home/deploy/jdk/lib/tools.jar;export CLASSPATH

PATH=$PATH:/home/deploy/jdk/bin:/home/deploy/jdk/jre/bin;export PATH

alias l=”/bin/ls -al”

export HOME=/home/deploy

export PS1=’$PWD>’

set EDITOR=vi

set -o vi

after modify the .bash_profile and save it, then logout.

3 JBoss installation

Login with deploy account, then upload jboss-4.2.3.GA.zip to home directory.

3.1 Extract Jboss package

unzip jboss-4.2.3.zip

move jboss-4.2.3 jboss

Extract jboss-4.2.3.GA.zip to jboss-4.2.3.GA and rename the directory to jboss.

 

3.2 Copy need LIB and jar to default deployment

If Jboss need to run on cluster, copy some LIB and jar file from its ‘all’ directory to ‘default’ directory. Please execute those commands as follows:

cd ~/jboss/server/default/lib/

cp ~/jboss/server/all/lib/jgroups.jar .

cp ~/jboss/server/all/lib/jbossha.jar .

cd ~/jboss /server/default/deploy

cp -r ~/jboss/server/all/deploy/jboss-web-cluster.sar/ .

cp ~/jboss/server/all/deploy/cluster-service.xml .

cd jboss/server/default/deploy/jboss-web.deployer/META-INF/

 

3.3 Configure cluster parameter

vi jboss-server.xml

Then, for each JBoss Tomcat instance in the cluster, we need to tell it to add the jvmRoute value to its session cookies so that mod_jk can route incoming requests. Locate the <attribute> element with a name of UseJK, and set its value to true line 114 on jboss-server.xml.

 

cd ~/jboss/server/default/deploy/jboss-web.deployer/

vi server.xml

Please find the line as <Engine name=”jboss.web” defaultHost=”localhost”>, and add jvmRoute=”debian01″ to this line, different nodes should different jvmRoute name, result as follows:

<Engine name=”jboss.web” jvmRoute=”debian01″ defaultHost=”localhost”>

 

cd ~/jboss/server/default/deploy

vi cluster-service.xml

Cluster might apply UDP and TCP communication protocol, mask UDP configure node from line 39 to 80, then unmask TCP configure node.

locate line 85, find bind_addr=”thishost” and change thishost to ip address of the current host.

find start_port=”7800″ and change 7800 to 7820.

find TCPPING initial_hosts=”thishost[7800],otherhost[7800]”, change thishost to ip address of the current host,

change otherhost to ip address of another node. thange the two “7800″ to “7820″.

Sample TCP configure as follows:

         <Config>

            <TCP bind_addr=”10.5.6.44” start_port=”7820” loopback=”true”

                 tcp_nodelay=”true”

                 recv_buf_size=”20000000″   

                 send_buf_size=”640000″

                 discard_incompatible_packets=”true”          

                 enable_bundling=”false”

                 max_bundle_size=”64000″

                 max_bundle_timeout=”30″       

                 use_incoming_packet_handler=”true”

                 use_outgoing_packet_handler=”false”

                 down_thread=”false” up_thread=”false”   

                 use_send_queues=”false”                            

                 sock_conn_timeout=”300″

                 skip_suspected_members=”true”/>

            <TCPPING initial_hosts=”10.5.6.44[7820],10.5.6.246[7820]” port_range=”3″

                     timeout=”3000″

                     down_thread=”false” up_thread=”false”

                     num_initial_members=”3″/>    

            <MERGE2 max_interval=”100000″                       

                    down_thread=”false” up_thread=”false” min_interval=”20000″/>

            <FD_SOCK down_thread=”false” up_thread=”false”/>

            <FD timeout=”10000″ max_tries=”5″ down_thread=”false” up_thread=”false” shun=”true”/>

            <VERIFY_SUSPECT timeout=”1500″ down_thread=”false” up_thread=”false”/>

            <pbcast.NAKACK max_xmit_size=”60000″

                           use_mcast_xmit=”false” gc_lag=”0″

                           retransmit_timeout=”300,600,1200,2400,4800″

                           down_thread=”false” up_thread=”false”

                           discard_delivered_msgs=”true”/>

            <pbcast.STABLE stability_delay=”1000″ desired_avg_gossip=”50000″

                           down_thread=”false” up_thread=”false”

                           max_bytes=”400000″/>

            <pbcast.GMS print_local_addr=”true” join_timeout=”3000″

                        down_thread=”false” up_thread=”false”

                        join_retry_timeout=”2000″ shun=”true”

                        view_bundling=”true”/>

            <pbcast.STATE_TRANSFER down_thread=”false” up_thread=”false” use_flush=”false”/>

         </Config>

 

3.4 JNDI DataSource

cd ~/jboss/server/default/deploy

cp ~/jboss/docs/examples/jca/postgres-ds.xml .

vi postgres-ds.xml

Please modify servername, port, database name, user name and password on postgres-ds.xml.

 

3.5 Configure other node as above.

 

4 Apache2.0.x and connctors installation

It seem that debian sarge don’t support apache2.2.x version. If you install apache via apt-get method, apache might not support mod_jk. So should compile and install apache2.0.x by manual.

4.1 Upload apache package

Please upload httpd-2.0.63.tar.gz to /usr/src directory.

 

4.2 Compile & Install apache2.0.x

Login with root

cd /usr/src/

tar zxvf httpd-2.0.63.tar.gz

cd httpd-2.0.63

./configure -prefix=/usr/local/apache2 –enable-so –enable-modules=all  –enable-mods-shared=all

If debian has multiple CPU, please add -with-mpm=prefork to above command line.

make clean

make

make install

 

4.3 Complie connectors

Upload tomcat-connectors-1.2.26-src.tar.gz to /usr/src directory.

cd /usr/src/tomcat-connectors-1.2.26-src/native

./configure –with-apxs=/usr/local/apache2/bin/apxs

If debian has multiple CPU, please add –enable-prefork to above command line.

make

make install

You can see mod_jk.so on /usr/local/apache2/modules directory.

 

4.4 Apache & connectors configure

cd /usr/local/apache2/conf

Please add the line to httpd.conf.

Include conf/mod_jk.conf 

Please add mod_mk.conf on /usr/local/apache2/conf directory, its content as follows:

# Load mod_jk module

# Specify the filename of the mod_jk lib

LoadModule jk_module modules/mod_jk.so

#LoadModule jk_module modules/mod_jk-1.2.26-httpd-2.2.4.so

 

# Where to find workers.properties

JkWorkersFile conf/workers.properties

 

# Where to put jk logs

JkLogFile logs/mod_jk.log

 

# Set the jk log level [debug/error/info]

JkLogLevel info

 

# Select the log format

JkLogStampFormat  “[%a %b %d %H:%M:%S %Y]”

 

# JkOptions indicates to send SSK KEY SIZE

JkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories

 

# JkRequestLogFormat

JkRequestLogFormat “%w %V %T”

 

# Mount your applications

JkMount /application/* loadbalancer

 

# You can use external file for mount points.

# It will be checked for updates each 60 seconds.

# The format of the file is: /url=worker

# /examples/*=loadbalancer

#JkMountFile conf/uriworkermap.properties

 

# Add shared memory.

# This directive is present with 1.2.10 and

# later versions of mod_jk, and is needed for

# for load balancing to work properly

JkShmFile logs/jk.shm

 

# Add jkstatus for managing runtime data

<Location /jkstatus/>

    JkMount status

    Order deny,allow

    Deny from all

    Allow from 127.0.0.1

</Location>

 

Please add workers.properties on /usr/local/apache2/conf directory, its content as follows:

worker.list=loadbalancer,debian01,debian02

 

# Define the first node…

worker.debian01.port=8009

worker.debian01.host=10.5.6.246

worker.debian01.type=ajp13

 

worker.debian01.lbfactor=1

#worker.debian01.local_worker=1

worker.debian01.cachesize=100

 

# Define the 2nd node…

worker.debian02.port=8009

worker.debian02.host=10.5.6.44

worker.debian02.type=ajp13

worker.debian02.lbfactor=1

#worker.debian02.local_worker=1

worker.debian02.cachesize=100

 

# Now we define the load-balancing behaviour

worker.loadbalancer.type=lb

worker.loadbalancer.balanced_workers=debian01,debian02

 

worker.loadbalancer.sticky_session=1

 

the debian01, debian02 are jvmRoute alias that defined on ~/jboss/server/default/deploy/jboss-web.deployer/server.xml.

10.5.6.246, 10.5.6.44 are ip address of two nodes.

 

4.5 Start/stop jboss and apache

Login with deploy account, then

cd ~/jboss/bin

./run.sh -b 0.0.0.0

If stop jboss, please input ctrl+c on terminal.

 

Login with root,

Cd /usr/local/apache2/bin

Start apache as follows:

./apachectl –k start

Stop apache as follows:

./apachectl stop

 

5 Deploy application on Jboss

2007年05月31日

JBoss Application Server Security Vulnerability Notice

归档在: jboss, java — JACKEYJ @ 7:38 PM

This document (3024921) is provided subject to the disclaimer at the end of this document.

environment

JBoss Application Server versions 4.0.1 SP1
JBoss Application Server versions 4.0.2 SP1
JBoss Application Server versions 4.0.3 SP1
JBoss Application Server versions 4.0.5
Novell Identity Manager UserApplication 3.0
Novell Identity Manager UserApplication 3.0.1 SP1

situation

Symantec discovered a flaw in the DeploymentFileRepository class of the JBoss Application Server. A remote attacker who is able to access the console manager could read or write to files with the permissions of the JBoss AS user. This could potentially lead to arbitrary code execution as the JBoss AS user. (CVE-2006-5750)

Please note that the JBoss AS console manager should always be secured prior to deployment, as directed in the JBoss Application Server Guide. By default, the JBoss AS installer gives users the ability to password protect the console manager, limiting an attack using this vulnerability to authorised users. These steps can also be performed manually.

resolution

The quickest and easiest approach to correct this security vulnerability is to;

1) Remove the offending service
2) Secure the JBoss JMX and Web Consoles
However we strongly feel the best approach is to secure JBoss using the following optional procedures;
- secure jmx-console and web-console authentication via SSL
- secure your Web Application in JBoss Application Server
- use a one-way hash to protect the administrative password property file
- secure the invokers
To remove the offending service use the following steps;
1) undeploy completely the web-console application by removing the directory deploy/management from the ‘default’ and ‘all’ configurations
or
2) comment out the DeploymentFileRepository service deployed by
deploy/management/console-mgr.sar in the ‘default’ and ‘all’ configurations. If console-mgr.sar is packed, unpack it and edit the META-INF/jboss-service.xml descriptor,
commenting out the following entry:

name=”jboss.admin:service=DeploymentFileRepository”>
./deploy/management

The web-console will still work, without the ability to create alerts/monitors/snapshots.


Secure the Jmx and Web Console’s
1) Secure the JMX Console using a username/password file
a) Locate the jmx-console.war directory. Normally found in server/default/deploy in your JBOSS_HOME directory.
b) edit the WEB-INF/web.xml, uncomment the security-constraint block
c) edit the WEB-INF/jmx-console-users.properties or server/default/conf/props/jmx-console-users.properties (version >=4.0.2) and WEB-INF/jmx-console- roles.properties or

server/default/conf/props/jmx-console-roles.properties (version >=4.0.2) and change the users and passwords to what you desire.
Please note: They will need the JBossAdmin role specified in the web.xml file to run the JMX Console.
d) edit the WEB-INF/jboss-web.xml, uncomment the security-domain block. The security-domain value of jmx-console maps is declared in the login-config.xml JAAS configuration file which

defines how authentication and authorization is done.

2)Secure the JMX Console using your own JAAS domain -
a) edit the WEB-INF/web.xml as above, uncommenting the security-constraint block. Change the role-name value to be the role in your domain that can access the console
b) edit the WEB-INF/jboss-web.xml as in step1, set the security domain to be the name of your security domain. For example, if your login-config.xml has an application-policy whose name

is MyDomain then your JAAS domain java:/jaas/MyDomain
c) redeploy the application.

3)Secure the web console
a) In the deploy directory, locate management/web-console.war and make the same changes as above to the WEB-INF/web.xml, WEB-INF/jboss-web.xml and the users/groups properties

file.
The default JAAS domain used by the web-console is java:/jaas/web-console and is defined in login-config.xml in the conf directory. You can use a custom JAAS domain or customize the existing domain in the same way as with the JMX console. Typically you would just use the same domain (java:/jaas/jmx-console) as the jmx-console so that you have a single user/role mapping to configure.

Update for 4.0.2
The jmx-console-roles.properties and jmx-console-users.properties files have been moved to server\default\conf\props.
The web console,is unpacked already in the default server configuration as deploy/management/console-mgr.sar/web-console.war. Edit the WEB-INF/web.xml and jboss-web.xml files as per securing the JMX console.

A quicker method to secure the Web and JMX console is the following:
1) Navigate to JBOSS_HOME/server/default/deploy/jmx-console.war/WEB-INF/web.xml
and uncomment the security-constraint block, add a block after the end of the block
example:

BASIC
JMXConsole

2) Navigate to JBOSS_HOME/server/default/deploy/jmx-console.war/WEB-INF/jboss-web.xml
and uncomment the security-domain block

3) Navigate to $JBOSS_HOME/server/default/conf/props/jmx-console-users.properties
and change the password for admin

4) Navigate to JBOSS_HOME/server/default/deploy/management/console-mgr.sar/web-console.war/WEB-INF/web.xml
and uncomment the security-constraint block

5) Navigate to JBOSS_HOME/server/default/deploy/management/console-mgr.sar/web-console.war/WEB-INF/jboss-web.xml
and uncomment the security-domain block

6) Navigate to JBOSS_HOME/server/default/conf/login-config.xml
and change the path to the web-console-users.properties and the web-console-roles.properties as follows (add props/ to the front of the path)
props/web-console-users.properties
props/web-console-roles.properties

7) Navigate to JBOSS_HOME/server/default/deploy/management/console-mgr.sar/web-console.war/WEB-INF/classes/web-console-*.properties and JBOSS_HOME/server/default/conf/props
edit as needed

8) Navigate to JBOSS_HOME/server/default/conf/props/jmx-console-roles.properties and JBOSS_HOME/server/default/conf/props/web-console-roles.properties
and edit as needed

9) Restart jboss

How to secure the JMX-console and Web-console authentication via SSL
These steps will redirect jboss admin pages to https://localhost:8443

1)You must first enable http authenication as outlined in the sections previously outlined above


2)Navigate to JBOSS_HOME/server/default/deploy/management/console-mgr.sar/web-console.war/WEB-INF/web.xml, include the following just before end of tag security-constraint


CONFIDENTIAL


3)Navigate to JBOSS_HOME/server/default/deploy/jmx-console.war/WEB-INF/web.xml,include the following just before end of tag security-constraint


CONFIDENTIAL

4) Create a keystore and supply a secure password. (for information on creating a keystore please see TID#3103136 How to install a signed certificate into Jboss for the IDM3 User Application,
http://www.novell.com/support/search.do?cmd=displayKC&docType=kc&externalId=


5)Enable SSL in JBoss
-locate jbossweb-tomcat55.sar file under \jboss\server\YourJBossServer\deploy.
-In it, find server.xml and open that file in a text editor.
-Enable SSL by uncommenting “SSL/TLS Connector” or adding the following section if it is not there:


maxThreads=”100″ strategy=”ms” maxHttpHeaderSize=”8192″
emptySessionPath=”true”
scheme=”https” secure=”true” clientAuth=”false”
keystoreFile=”${jboss.server.home.dir}/spitfire/conf/jboss.jks”
keystorePass=”changeit” sslProtocol = “TLS” />

**Note 1: Remember to point “keystoreFile” to the keystore you created. example: ${jboss.server.home.dir}/conf/server.keystore
**Note 2: Remember to change the keystorePass=”changeit” to your keystore password

6)Restart your JBoss Server and test
When restarting the JBoss Server you should see the server running on 2 ports, your http port and your ssl port https:8443

Securing a Web Application in JBoss AS

1) Create a simple security domain for JBoss SX
a) Open the ${jboss.dist}/server/${server.name}/conf/login-config.xml file
1) This file sets up the configuration for the security domains available to applications running in the server. The file contains a few example domains you may want to look at for

reference.
2) JBoss SX uses JAAS for the infrastructure of the underlying security
3) JAAS uses a class called a “login module” to interact with a security store for authenticating credentials.
4) This file basically hooks up a security domain to a JAAS login module.
5) JBoss Application Server comes packed with the “UsersRolesLoginModule”. The “UsersRolesLoginModule” allows you to specify user names, passwords and roles in a simple

property file.

b) Copy the “jmx-console” domain policy
1) The “jmx-console” security domain policy contains the basics for configuring a UsersRolesLoginModule based security domain.

code=”org.jboss.security.auth.spi.UsersRolesLoginModule”
flag = “required”>

name=”usersProperties”>
props/jmx-console-users.properties

name=”rolesProperties”>
props/jmx-console-roles.properties

2) copy this section to the bottom of the file
3) edit the “name” attribute on the application-policy attribute to “my-web”
4) edit the “userProperties” module-option text value to be “props/my-web-users.properties”
5) edit the “roleProperties” module-option text value to be “props/my-web-roles.properties”
6) save the login-config.xml file.

c) In the ${jboss.dist}/server/conf/props directory,
1) copy the jmx-console-users.properties into a new file called my-web-users.properties,
2) copy the jmx-console-roles.properties into a new file called my-web-roles.properties.
3) open “my-web-users.properties” file, notice that you will see a single entry like: “admin=admin” (The structure is “username=password”). When a user logs into the security domain,

the login module will examine the properties data in this file for users.
4) Add a new user, for example “tester=security”, to the file under “admin=admin”
5) Save file
6) open the my-web-roles.properties file, notice an entry similar to the following: “admin=JBossAdmin,HttpInvoker”.
These entries define the roles a user has associated with their account at login. The structure is “username=Role1,Role2,…” the username is the user you wish to assign roles to,and the

Roles entries are a comma separated list of roles to assign to that user.
7) Add a new entry to this file, for example “tester=WebAppUser” on a new line below the “admin=….”.
8) Save file.

2) Configure the web application for security by adding constraints to the web deployment descriptor.
a) modify the web.xml in the WEB-INF directory of the web application you are securing to add in the following:

All resources
Protects all resources
/*

WebAppUser


WebAppUser

BASIC
Test Realm

Note: “security-constraint” is used to define what resources in the web application are protected.
“url-pattern” element specifies the URL pattern to protect (example above protects _all_ resources in the web application)
“auth-contraint” element specifies which roles have access to the protected resource (example just specifies one role)
-This role name must match the name of the role you specified in “my-web-roles.properties” file.
“login-config” element specifies how authentication occurs with the web application.
“auth-method” element specifies how the browser gets credentials from the user.
-”BASIC”, “DIGEST”, “FORM”, and “CLIENT-CERT” are possible methods to retrieve data from the browser user.
The example above uses “BASIC”, but this method should not be used in a production environment unless you are using SSL/TLS
“realm-name” element just specifies the authentication realm name that is given to the browser for authentication.

3) Configure the jboss-web.xml file to point to the “my-web” application.
a) edit the jboss-web.xml in the WEB-INF directory of the web application you are securing
-add the following in the “jboss-web” element:

java:/jaas/my-web

This instructs JBoss Application Server to connect the web application to the “my-web” security domain we defined in the login-config.xml file earlier. 4) Start the JBoss Application Server

5) In a browser navigate to your application
-you should be prompted for username and password.

6) Enter the user and password we created earlier in our example we used “tester” for the username, and “security” for the password.
If your set-up is correct, you will be allowed access to the web application.

To test,
1) close browser

2) open and navigating back to your application.

3) When prompted, enter no credentials, or “admin” with password: admin,
you should not have access to the application

Protecting the Administrator password property file

You can also use a one-way hash for protecting the admin password property file.

In the above section on “Securing a Web Application in JBoss AS” in step 1 section “b” we used the following configuration fragment:

props/jmx-console-users.properties
props/jmx-console-roles.properties

To add the hash support, you need to add the following options to it:
MD5
base64
Now in the usersProperties file, you no longer do user=pass. Instead, you do user=md5(pass).

The user is responsible for generating the md5() value, either by themselves or using the following program (please notice that it relies on org.jboss.security.Util, which is in jbosssx.jar).

import java.security.MessageDigest;
import org.jboss.security.Util;

class HashPassword
{
public static void main(String[] args)
{
String password = args[0];
MessageDigest md = null;
try
{
md = MessageDigest.getInstance(”MD5″);
}
catch(Exception e)
{
e.printStackTrace();
}
byte[] passwordBytes = password.getBytes();
byte[] hash = md.digest(passwordBytes);
String passwordHash = Util.encodeBase64(hash);
System.out.println(”password hash: “+passwordHash);
}
}

Securing the Invokers
1)Enabling authentication to the RMIAdaptor service
- in JBossAS 4.0.x, edit jmx-invoker-service.xml
- in JBossAS 3.2.x, edit jmx-invoker-adaptor-server.sar/META-INF/jboss-service.xml
and uncomment the descriptors section of the invoke operation:


The detached invoker entry point
invoke

The method invocation context
invocation
org.jboss.invocation.Invocation java.lang.Object

securityDomain=”java:/jaas/jmx-console”/>

The value of the securityDomain attribute maps to the security domain name found in the conf/login-config.xml definitions the same way as the jboss.xml, jboss-web.xml security-domain elements.

2)Enabling authorization to the RMIAdaptor service
-An “AuthorizationInterceptor” is available in JBoss. The place the interceptor after the “AuthenticationInterceptor”

configuration: * authorizingClass : Fully Qualified Name of a class that does the authorization and contains a method with the following signature

“public void authorize( Principal caller, Subject subject, String objectname,String opname)” that can throw a java.lang.SecurityException

An example of an authorizing class is the org.jboss.jmx.connector.invoker.RolesAuthorization, which looks for an hardcoded “JBossAdmin?” role in the authenticated subject.

securityDomain=”java:/jaas/jmx-console”/>

authorizingClass=”org.jboss.jmx.connector.invoker.RolesAuthorization”/>

Starting with 4.0.4.GA, Jboss has an authorization delegate that looks for passwords from a properties file called as “jmxinvoker-roles.properties” in a jar file or can be in the conf directory.

securityDomain=”java:/jaas/jmx-console”/>

authorizingClass=”org.jboss.jmx.connector.invoker.ExternalizableRolesAuthorization”/>

The format of the “jmxinvoker-roles.properties” file is:

#Specify the roles that are authorized to access the jmx invoker delimited by comma
roles=testRole,testRole1

If you don’t succeed in securing the RMIInvoker

1) try placing the security-service.xml in a SAR

2) create a folder named security.sar that has a subfolder named META-INF

3) move your security-service.xml to this folder and rename it to jboss-service.xml

4)Place the security.sar in the deploy-folder

status

Security Alert
Top Issue

document

Document ID: 3024921
Creation Date: 2007-02-09 15:53:34.0
Modified Date: 2007-02-09 08:52:10.0
Novell Product: Identity Manager

disclaimer

The Origin of this information may be internal or external to Novell. Novell makes all reasonable efforts to verify this information. However, the information provided in this document is for your information only. Novell makes no explicit or implied claims to the validity of this information.
Any trademarks referenced in this document are the property of their respective owners. Consult your product manuals for complete trademark information.

2007年03月21日

通过Apache proxy 连接Tomcat

归档在: 未分类, Linux, apache, jboss, java — JACKEYJ @ 2:25 AM

以前都是通过mod_jk来使用apache+tomcat.

今天在晚上看到最新的Apache2.2.4正式发布了proxy功能,于是就进行了一下测试.结果还不错,比mod_jk配置要方便多了.

测试情况:

系统:winxp sp2 apache2.2.4 tomcat 5.0

配置:

1.修改apache的httpd.conf文件,启用proxy,如下:

#########################################################
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
#########################################################

2.在httpd.conf中启用vhost配置

# Virtual hosts
Include conf/extra/httpd-vhosts.conf

3.在httpd-vhost.conf配置一个虚拟主机,如下:


ServerAdmin admin@viiving.com
    ProxyPass / ajp://localhost:8009/
ProxyPassReverse / ajp://localhost:8009/
ServerName localhost
ServerAlias test.viiving.com
ErrorLog logs/dummy-host3.www.viiving.com-error_log
CustomLog logs/dummy-host3.www.viiving.com-access_log common
>4.启动tomcat和apache在浏览器中输入http://localhost/index.jsp连接地址就可以访问到tomcat中的内容.

5.其他

linux(CentOS4.4 and Ubuntu6.06)环境下的配置
./configure -prefix=/data/apache2 -enable-so -enable-rewrite=share -enable-proxy=share -enable-proxy-ajp=share -enable-dav =share

______________________________________________________________________
reference other doc

(更多…)

2007年03月02日

通过ssh隧道访问内部网络

归档在: 未分类, Linux, DB, apache, jboss — JACKEYJ @ 11:27 AM

一。简介:

大多数人知道SSH是用来替代R命令集,是用于加密的远程登录,文件传输,甚至加密的
FTP(SSH2内置), 因此SSH成为使用极广的服务之一,不仅如此,SSH还有另一项非常有
用的功能,就是它的端口转发隧道功能,利用此功能,让一些不安全的服务象POP3,
SMTP,FTP,LDAP等等通过SSH的加密隧道传输,然后,既然这些服务本身是不安全的,
密码和内容是明文传送的,现在其它中间媒介也没无监听了。

二。图示:

SSH的加密隧道保护的只是中间传输的安全性,使得任何通常的嗅探工具软件无法获取发
送内容。如下图:
假设客户机和服务器都运行Linux,且以POP3为例。

C (pop3 server: S)              S
_______                         ________
|     |                         |      |
|     |________POP3___________ >|      |
|_____|                         |______|
(图一:正常的POP3)

(图一:正常的POP3)

C (pop3 server:C)               S (pop3 client: S)
_______                         ________
|     |                         |      |
|     |——–SSH连接———>|      |
|_____|                         |______|

(图二:SSH隧道后的POP3)

如图一: 正常的POP3连接是客户C向服务器S进行连接,C的设置是POP3服务器为S。
如图二: 用SSH隧道的话,客户C设置pop3服务器为自己(localhost),然后设置SSH加密
隧道
,如果设置在同样的端口110听取C的请求,则对C来说,pop3服务器是自己本身,端口也
是110 对S来说,看到的pop3请求地址不是来自C,而也是自己本身,因为有了SSH隧道。

三。SSH隧道设置

1. 首先必须在C和S上安装SSH,确保SSH首先能工作。
2. 我们用简单的一个命令如下:

# ssh -C -P -f sshaccount@S -L 110:S:110 sleep 7200

解释如下:
-C 使用压缩功能,是可选的,加快速度。

-P 用一个非特权端口进行出去的连接。

-f 一旦SSH完成认证并建立port forwarding,则转入后台运行。

sshaccount 客户C在服务器S上的SSH连接帐号

-L 110:S:110 转发C对本地端口110的连接到远程服务器S的110端口。
也可以用高端端口(普通用户使用,因为普通用户不能在低于1024的端口上建立SSH隧道)
如果用高端端口,如:-L 1110:S:110,这样任何用户都可建立这种加密隧道。

sleep 7200 一般用于script,必须给一个命令,我们给一个sleep等待空 命令,这里为
2小时,你可以
设为更长用于保持整个连接过程, 如 sleep 100000000 。

四。检验

设置后你就可以在客户C上用 # telnet localhost 110 命令而连到 S 上收取email,
而整个过程也被加密。

五。其它常见问题:

1. 每次启动该命令时需要输入密码以验证SSH连接,你也可以用RSA键对的方法自动化
SSH连接。
看文章荟萃中的另一篇文章《如何在两台linux服务器之间用RSA键对的方法SSH/SCP不需
密码》

2. 如果你希望上面的命令永远保持运行状态,你可以用如下的scripts.
#!/bin/sh
while [ 1 ] ; do
ssh -C -P -f sshaccount@S -L 110:S:110 sleep 7200
sleep 1
done

3. 你可以在一个命令中用多个L 参数 ,如 -L 1110:S:110 -L 225:S:25 -L
389:S:389

4. 一些windows客户端软件,象netscape mail,不能改变pop3端口号,被强迫到110,
则你只能指定110

5. Linux下的fetchmail常用来自动接收邮件,可在.fetchmailrc中利用
preconnect参数预连接 ,指定上面的命令行。

6. 如果客户端是windows, 则可用tera Term pro,参考
http://www.phys.washington.edu/Computing/winftpssh.html

SSH隧道进行安全 TCP/IP 联接

我们可以使用 SSHPostgreSQL 服务器和客户端之间的网络联接进行加密。经过适当处理后,这样做可以获得一个足够安全的网络联接。 即使是没有 SSL 的客户端上也如此。

首先确认 SSH 正在和 PostgreSQL 服务器的同一台机器上正确地运行, 而且你可以通过某个用户用SSH登录。然后你可以用下面这样的命令从客户端的机器上建立一个安全通道:

ssh -L 3333:foo.com:5432 joe@foo.com

-L 参数的第一个数字,3333,是通道你这端的端口号;可以自由选择。 第二个数字,5432,是通道的远端:你的服务器使用的端口号。 在两个端口号之间的名称或者 IP 地址是你准备联接的数据库服务器。 为了使用这个通道与你的数据库服务器联接,你在本机于端口 3333 联接:

psql -h localhost -p 3333 postgres

对于数据库服务器而言,她会把你当做真正的用户 joe@foo.com 并且使用为这个用户和主机设置的认证手段进行认证。 请注意,服务器不会认为连接是 SSL 加密的,因为实际上在 SSH 服务器和 PostgreSQL 服务器之间是没有加密的。 只要它们在同一台机器上,这么做并不会导致任何安全漏洞。

为了保证能够成功地建立通道,你必须被允许作为 joe@foo.com 通过ssh建立联接, 就象你使用ssh建立终端会话一样。

提示: 还有几种不同的产品可以提供安全的通道,所使用的过程类似我们刚刚描述的过程。

上面是postgre的ssh连接方式。同样也使用mysql,oracle等数据库。

测试例子

自公司的内部网络里面通过ssh方式访问另外一个网络里面的http和ssl服务,为了测试我作了3层的ssh连接。

ssh -L 80:localhost:8000 root@192.16.2.22

ssh -L 8000:localhost:8000 test1@59.11.89.15
ssh -L 8000:localhost:80 test@192.168.1.24

ssh -L 443:localhost:4443 test@192.168.1.229

ssh -L 4443:localhost:4443 test1@59.11.89.15
ssh -L 4443:localhost:443 test@192.168.1.24

这样之后就可以在本地通过http://localhost and https://localhost

不过测试过程中遇到了一些问题。当我们把localhost替换成server的ip地址的时候就发生了channel 3: open failed: connect failed: Connection refused的错误。

2007年02月05日

Apache HTTP Server 与 Tomcat 的三种连接方式介绍

归档在: 未分类, Linux, apache, jboss, java — JACKEYJ @ 2:38 PM

developerWorks 中国  >  Open source | Web development >

Apache HTTP Server 与 Tomcat 的三种连接方式介绍 
 
  文档选项
   将此页作为电子邮件发送
 
 

拓展 Tomcat 应用
  下载 IBM 开源 J2EE 应用服务器 WAS CE 新版本 V1.1
 
 
级别: 初级

刘 冬 (javayou@gmail.com), 开发工程师,  
2007 年 1 月 15 日

整合 Apache Http Server 和 Tomcat 可以提升对静态文件的处理性能、利用 Web 服务器来做负载均衡以及容错、无缝的升级应用程序。本文介绍了三种整合 Apache 和 Tomcat 的方式。
首先我们先介绍一下为什么要让 Apache 与 Tomcat 之间进行连接。事实上 Tomcat 本身已经提供了 HTTP 服务,该服务默认的端口是 8080,装好 tomcat 后通过 8080 端口可以直接使用 Tomcat 所运行的应用程序,你也可以将该端口改为 80。

既然 Tomcat 本身已经可以提供这样的服务,我们为什么还要引入 Apache 或者其他的一些专门的 HTTP 服务器呢?原因有下面几个:
1. 提升对静态文件的处理性能

2. 利用 Web 服务器来做负载均衡以及容错

3. 无缝的升级应用程序

这三点对一个 web 网站来说是非常之重要的,我们希望我们的网站不仅是速度快,而且要稳定,不能因为某个 Tomcat 宕机或者是升级程序导致用户访问不了,而能完成这几个功能的、最好的 HTTP 服务器也就只有 apache 的 http server 了,它跟 tomcat 的结合是最紧密和可靠的。

接下来我们介绍三种方法将 apache 和 tomcat 整合在一起。

JK

这是最常见的方式,你可以在网上找到很多关于配置JK的网页,当然最全的还是其官方所提供的文档。JK 本身有两个版本分别是 1 和 2,目前 1 最新的版本是 1.2.19,而版本 2 早已经废弃了,以后不再有新版本的推出了,所以建议你采用版本 1。

JK 是通过 AJP 协议与 Tomcat 服务器进行通讯的,Tomcat 默认的 AJP Connector 的端口是 8009。JK 本身提供了一个监控以及管理的页面 jkstatus,通过 jkstatus 可以监控 JK 目前的工作状态以及对到 tomcat 的连接进行设置,如下图所示:

图 1:监控以及管理的页面 jkstatus
图 1:监控以及管理的页面 jkstatus
在这个图中我们可以看到当前JK配了两个连接分别到 8109 和 8209 端口上,目前 s2 这个连接是停止状态,而 s1 这个连接自上次重启后已经处理了 47 万多个请求,流量达到 6.2 个 G,最大的并发数有 13 等等。我们也可以利用 jkstatus 的管理功能来切换 JK 到不同的 Tomcat 上,例如将 s2 启用,并停用 s1,这个在更新应用程序的时候非常有用,而且整个切换过程对用户来说是透明的,也就达到了无缝升级的目的。关于 JK 的配置文章网上已经非常多了,这里我们不再详细的介绍整个配置过程,但我要讲一下配置的思路,只要明白了配置的思路,JK 就是一个非常灵活的组件。

JK 的配置最关键的有三个文件,分别是

httpd.conf
Apache 服务器的配置文件,用来加载 JK 模块以及指定 JK 配置文件信息

workers.properties
到 Tomcat 服务器的连接定义文件

uriworkermap.properties
URI 映射文件,用来指定哪些 URL 由 Tomcat 处理,你也可以直接在 httpd.conf 中配置这些 URI,但是独立这些配置的好处是 JK 模块会定期更新该文件的内容,使得我们修改配置的时候无需重新启动 Apache 服务器。

其中第二、三个配置文件名都可以自定义。下面是一个典型的 httpd.conf 对 JK 的配置

# (httpd.conf) # 加载 mod_jk 模块
LoadModule jk_module modules/mod_jk.so
# # Configure mod_jk #
JkWorkersFile conf/workers.properties
JkMountFile conf/uriworkermap.properties
JkLogFile logs/mod_jk.log JkLogLevel warn

接下来我们在 Apache 的 conf 目录下新建两个文件分别是 workers.properties、uriworkermap.properties。这两个文件的内容大概如下

# # workers.properties #   # list the workers by name
worker.list=DLOG4J, status  # localhost server 1 # ------------------------
worker.s1.port=8109
worker.s1.host=localhost
worker.s1.type=ajp13
# localhost server 2 # ------------------------
worker.s2.port=8209
worker.s2.host=localhost
worker.s2.type=ajp13
worker.s2.stopped=1
worker.DLOG4J.type=lb
worker.retries=3
worker.DLOG4J.balanced_workers=s1, s2
worker.DLOG4J.sticky_session=1
worker.status.type=status

以上的 workers.properties 配置就是我们前面那个屏幕抓图的页面所用的配置。首先我们配置了两个类型为 ajp13 的 worker 分别是 s1 和 s2,它们指向同一台服务器上运行在两个不同端口 8109 和 8209 的 Tomcat 上。接下来我们配置了一个类型为 lb(也就是负载均衡的意思)的 worker,它的名字是 DLOG4J,这是一个逻辑的 worker,它用来管理前面配置的两个物理连接 s1 和 s2。最后还配置了一个类型为 status 的 worker,这是用来监控 JK 本身的模块。有了这三个 worker 还不够,我们还需要告诉 JK,哪些 worker 是可用的,所以就有 worker.list = DLOG4J, status 这行配置。

接下来便是 URI 的映射配置了,我们需要指定哪些链接是由 Tomcat 处理的,哪些是由 Apache 直接处理的,看看下面这个文件你就能明白其中配置的意义

/*=DLOG4J
/jkstatus=status
!/*.gif=DLOG4J
!/*.jpg=DLOG4J
!/*.png=DLOG4J
!/*.css=DLOG4J
!/*.js=DLOG4J
!/*.htm=DLOG4J
!/*.html=DLOG4J

相信你已经明白了一大半了:所有的请求都由 DLOG4J 这个 worker 进行处理,但是有几个例外,/jkstatus 请求由 status 这个 worker 处理。另外这个配置中每一行数据前面的感叹号是什么意思呢?感叹号表示接下来的 URI 不要由 JK 进行处理,也就是 Apache 直接处理所有的图片、css 文件、js 文件以及静态 html 文本文件。

通过对 workers.properties 和 uriworkermap.properties 的配置,可以有各种各样的组合来满足我们前面提出对一个 web 网站的要求。您不妨动手试试!


  

回页首

http_proxy

这是利用 Apache 自带的 mod_proxy 模块使用代理技术来连接 Tomcat。在配置之前请确保是否使用的是 2.2.x 版本的 Apache 服务器。因为 2.2.x 版本对这个模块进行了重写,大大的增强了其功能和稳定性。

http_proxy 模式是基于 HTTP 协议的代理,因此它要求 Tomcat 必须提供 HTTP 服务,也就是说必须启用 Tomcat 的 HTTP Connector。一个最简单的配置如下

ProxyPass /images ! ProxyPass /css ! ProxyPass /js ! ProxyPass / http://localhost:8080/

在这个配置中,我们把所有 http://localhost 的请求代理到 http://localhost:8080/ ,这也就是 Tomcat 的访问地址,除了 images、css、js 几个目录除外。我们同样可以利用 mod_proxy 来做负载均衡,再看看下面这个配置

ProxyPass /images !
ProxyPass /css !
ProxyPass /js !
ProxyPass / balancer://example/
BalancerMember http://server1:8080/
BalancerMember http://server2:8080/
BalancerMember http://server3:8080/

配置比 JK 简单多了,而且它也可以通过一个页面来监控集群运行的状态,并做一些简单的维护设置。

图 2:监控集群运行状态
图 2:监控集群运行状态


  

回页首

ajp_proxy

ajp_proxy 连接方式其实跟 http_proxy 方式一样,都是由 mod_proxy 所提供的功能。配置也是一样,只需要把 http:// 换成 ajp:// ,同时连接的是 Tomcat 的 AJP Connector 所在的端口。上面例子的配置可以改为:

ProxyPass /images !
ProxyPass /css !
ProxyPass /js !
ProxyPass / balancer://example/
BalancerMember ajp://server1:8080/
BalancerMember ajp://server2:8080/
BalancerMember ajp://server3:8080/

采用 proxy 的连接方式,需要在 Apache 上加载所需的模块,mod_proxy 相关的模块有 mod_proxy.so、mod_proxy_connect.so、mod_proxy_http.so、mod_proxy_ftp.so、mod_proxy_ajp.so, 其中 mod_proxy_ajp.so 只在 Apache 2.2.x 中才有。如果是采用 http_proxy 方式则需要加载 mod_proxy.so 和 mod_proxy_http.so;如果是 ajp_proxy 则需要加载 mod_proxy.so 和 mod_proxy_ajp.so这两个模块。


  

回页首

三者比较

相对于 JK 的连接方式,后两种在配置上是比较简单的,灵活性方面也一点都不逊色。但就稳定性而言就不像 JK 这样久经考验,毕竟 Apache 2.2.3 推出的时间并不长,采用这种连接方式的网站还不多,因此,如果是应用于关键的互联网网站,还是建议采用 JK 的连接方式。

 

参考资料

 

关于作者

Powered by ZJANT