path-absolute.cmake 1.7 KB

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