| 1 |
# Test that path traversal attacks are blocked during file(ARCHIVE_EXTRACT) |
| 2 |
|
| 3 |
set(EXTRACT_DIR "${CMAKE_CURRENT_BINARY_DIR}/extract_dir_abs") |
| 4 |
# Use an absolute path within the build tree (but outside EXTRACT_DIR) |
| 5 |
set(MALICIOUS_FILE "${CMAKE_CURRENT_BINARY_DIR}/SHOULD_NOT_EXIST_ABS.txt") |
| 6 |
|
| 7 |
# Clean up |
| 8 |
file(REMOVE_RECURSE "${EXTRACT_DIR}") |
| 9 |
file(REMOVE "${MALICIOUS_FILE}") |
| 10 |
file(MAKE_DIRECTORY "${EXTRACT_DIR}") |
| 11 |
|
| 12 |
# Create a malicious tar archive using Python |
| 13 |
# The archive contains a file with an absolute path |
| 14 |
set(MALICIOUS_TAR "${CMAKE_CURRENT_BINARY_DIR}/malicious_abs.tar") |
| 15 |
file(REMOVE "${MALICIOUS_TAR}") |
| 16 |
|
| 17 |
execute_process( |
| 18 |
COMMAND "${Python_EXECUTABLE}" -c [==[ |
| 19 |
import sys |
| 20 |
import tarfile |
| 21 |
import io |
| 22 |
|
| 23 |
# Create a tar archive in memory |
| 24 |
tar_data = io.BytesIO() |
| 25 |
with tarfile.open(fileobj=tar_data, mode='w') as tar: |
| 26 |
# Add a file with absolute path |
| 27 |
data = b'malicious content' |
| 28 |
info = tarfile.TarInfo(name=sys.argv[2]) |
| 29 |
info.size = len(data) |
| 30 |
tar.addfile(info, io.BytesIO(data)) |
| 31 |
|
| 32 |
# Write to file |
| 33 |
with open(sys.argv[1], 'wb') as f: |
| 34 |
f.write(tar_data.getvalue()) |
| 35 |
]==] "${MALICIOUS_TAR}" "${MALICIOUS_FILE}" |
| 36 |
RESULT_VARIABLE result |
| 37 |
) |
| 38 |
|
| 39 |
if(NOT result EQUAL 0) |
| 40 |
message(FATAL_ERROR "Failed to create malicious tar archive") |
| 41 |
endif() |
| 42 |
|
| 43 |
# Try to extract the malicious archive using file(ARCHIVE_EXTRACT) |
| 44 |
file(ARCHIVE_EXTRACT |
| 45 |
INPUT "${MALICIOUS_TAR}" |
| 46 |
DESTINATION "${EXTRACT_DIR}" |
| 47 |
) |
| 48 |
|
| 49 |
# The file should not exist outside the extraction directory |
| 50 |
if(EXISTS "${MALICIOUS_FILE}") |
| 51 |
message(FATAL_ERROR "PATH TRAVERSAL VULNERABILITY: File was created outside extraction directory!") |
| 52 |
endif() |