### Add Example and Test Subdirectories Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/libarchive/CMakeLists.txt Includes subdirectories for examples, tests, and the ld_preload example. ```cmake add_subdirectory(examples) add_subdirectory(test) add_subdirectory(ld_preload_example) ``` -------------------------------- ### Add Examples Subdirectory in CMake Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/openjpeg/CMakeLists.txt Includes the 'examples' subdirectory for building related examples. ```cmake add_subdirectory(examples) ``` -------------------------------- ### Run the sandboxed example Source: https://github.com/google/sandboxed-api/blob/main/contrib/libtiff/README.md Execute the sandboxed example binary by providing the absolute path to the project directory. ```bash ./example/sandboxed absolute/path/to/project/dir ``` -------------------------------- ### Build Jsonnet Examples Source: https://github.com/google/sandboxed-api/blob/main/contrib/jsonnet/README.md Commands to build the Jsonnet examples within the contrib/jsonnet directory. ```bash mkdir -p build && cd build cmake .. -G Ninja -Wno-dev -DSAPI_BUILD_TESTING=ON ninja ``` -------------------------------- ### Run PNG to PNG Example Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/libpng/README.md Execute the PNG to PNG conversion example. Requires building with -DLIBPNG_SAPI_BUILD_EXAMPLES=ON. ```bash ./examples/pngtopng /absolute/path/to/input/image.png /absolute/path/to/output/image.png ``` -------------------------------- ### Run RGB to BGR Example Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/libpng/README.md Execute the RGB to BGR conversion example. Requires building with -DLIBPNG_SAPI_BUILD_EXAMPLES=ON. ```bash ./examples/rgbtobgr /absolute/path/to/input/image.png /absolute/path/to/output/image.png ``` -------------------------------- ### Install SAPI libraries and headers via CMake Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/CMakeLists.txt Configures the installation of build targets and header files, excluding specific directories like tests and examples. ```cmake foreach(_dir IN ITEMS . sandbox2 sandbox2/allowlists sandbox2/network_proxy sandbox2/unwind sandbox2/util util) get_property(_sapi_targets DIRECTORY ${_dir} PROPERTY BUILDSYSTEM_TARGETS) list(FILTER _sapi_targets INCLUDE REGEX ^\(sapi|sandbox2\).*) list(FILTER _sapi_targets EXCLUDE REGEX _test) install(TARGETS ${_sapi_targets} DESTINATION ${CMAKE_INSTALL_LIBDIR}) set_property(TARGET ${_sapi_targets} PROPERTY SOVERSION 1) endforeach() file(GLOB_RECURSE _sapi_headers true ${CMAKE_CURRENT_LIST_DIR}/*.h) list(FILTER _sapi_headers EXCLUDE REGEX /\(tools|examples\)/) foreach(_file ${_sapi_headers}) get_filename_component(_dir ${_file} DIRECTORY) string(REPLACE ${CMAKE_CURRENT_LIST_DIR} "" _dir ${_dir}) install(FILES ${_file} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/sandboxed_api/${_dir}) endforeach() configure_file( "${PROJECT_SOURCE_DIR}/cmake/sapi.pc.in" "${PROJECT_BINARY_DIR}/sapi.pc" @ONLY ) install(FILES "${PROJECT_BINARY_DIR}/sapi.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") ``` -------------------------------- ### Install Additional Dependencies Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/gdal/README.md Commands to install PNG, PCRE, and PROJ libraries. ```bash sudo apt-get install libpng-dev ``` ```bash sudo apt-get install libpcre3 libpcre3-dev ``` ```bash sudo apt-get install libproj-dev ``` -------------------------------- ### Add Example Subdirectory Conditionally Source: https://github.com/google/sandboxed-api/blob/main/contrib/zopfli/CMakeLists.txt Adds the 'example' subdirectory to the build if the 'SAPI_BUILD_EXAMPLES' variable is set to true. This allows selective building of examples. ```cmake if(SAPI_BUILD_EXAMPLES) add_subdirectory(example) endif() ``` -------------------------------- ### Configure and Install pkg-config File Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/sandbox2/CMakeLists.txt Use these commands to generate a pkg-config file from a template and install it to the system library directory. ```cmake configure_file( "${PROJECT_SOURCE_DIR}/cmake/sandbox2.pc.in" "${PROJECT_BINARY_DIR}/sandbox2.pc" @ONLY ) install(FILES "${PROJECT_BINARY_DIR}/sandbox2.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") ``` -------------------------------- ### Configure Build Options for Examples and Tests Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/libuv/CMakeLists.txt Sets CMake options to enable or disable the building of examples and tests for the libuv integration. ```cmake option(SAPI_UV_ENABLE_EXAMPLES "" ON) option(SAPI_UV_ENABLE_TESTS "" ON) ``` -------------------------------- ### Define Sum Library Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/examples/sum/CMakeLists.txt Creates a static library for the sum example and links required dependencies. ```cmake add_library(sapi_sum STATIC sum.c sum_cpp.cc ) add_library(sapi::sum ALIAS sapi_sum) add_dependencies(sapi_sum sapi::sum_params_proto ) target_link_libraries(sapi_sum PRIVATE $ absl::log sapi::base PUBLIC protobuf::libprotobuf ) ``` -------------------------------- ### Install GDAL from Sources Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/gdal/raster_to_gtiff/README.md Steps to install GDAL from its source code, configuring it to use the previously installed PROJ library. This process ensures the static version of libgdal is available for use with Sandboxed API. ```shell cd build git clone https://github.com/OSGeo/gdal mkdir gdal_build cd gdal/gdal ./configure --prefix=/path/to/build/gdal_build --with-proj=/path/to/build/proj_build make -j8 make install ``` -------------------------------- ### Install PROJ from Sources Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/gdal/raster_to_gtiff/README.md Follow these steps to install PROJ from its source code, ensuring a clean installation within a specified build directory. This is necessary for GDAL to use a recent version of PROJ. ```shell mkdir build && cd build wget https://download.osgeo.org/proj/proj-7.1.1.tar.gz tar xvzf proj-7.1.1.tar.gz mkdir proj_build cd proj-7.1.1 ./configure --prefix=/path/to/build/proj_build make -j8 make install make check ``` -------------------------------- ### Build Example 1: Simple Network Request Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/curl/examples/CMakeLists.txt This CMakeLists.txt configures an executable for a simple network request using the Sandboxed API and curl. It links against necessary Sandboxed API libraries. ```cmake add_executable(example1 example1.cc ../sandbox.h ) target_link_libraries(example1 PRIVATE curl_sapi curl_util sapi::sapi ) ``` -------------------------------- ### Add Callbacks for Examples and Tests Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/libuv/CMakeLists.txt Conditionally adds callback header and source files to a list if examples or tests are enabled. These callbacks are used by the examples and tests. ```cmake if (SAPI_UV_ENABLE_EXAMPLES OR SAPI_UV_TESTS) list(APPEND SAPI_UV_CALLBACKS "${CMAKE_CURRENT_SOURCE_DIR}/callbacks/callbacks.h" "${CMAKE_CURRENT_SOURCE_DIR}/callbacks/callbacks.cc" ) endif() ``` -------------------------------- ### Verify GDAL Installation Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/gdal/raster_to_gtiff/README.md After installing GDAL, verify the installation by checking the version of the gdalinfo utility. This confirms that GDAL has been built and installed correctly. ```shell cd ../../gdal_build/bin/ ./gdalinfo --version ``` -------------------------------- ### Build LibCurl Sandbox Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/curl/README.md Commands to build the sandboxed libcurl library. Ensure you have Sandboxed API installed and provide the correct path. ```bash mkdir -p build && cd build cmake .. -G Ninja -D SAPI_ROOT= cmake --build . ``` -------------------------------- ### Define Main Executable Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/examples/sum/CMakeLists.txt Configures the main executable for the sum example and links necessary SAPI and Abseil libraries. ```cmake add_executable(sapi_main_sum main_sum.cc ) set_target_properties(sapi_main_sum PROPERTIES OUTPUT_NAME main_sum) add_executable(sapi::main_sum ALIAS sapi_main_sum) target_link_libraries(sapi_main_sum PRIVATE absl::core_headers absl::log absl::log_initialize absl::flags_parse absl::status absl::statusor absl::strings sapi::base sapi::sapi sapi::status sapi::sum_sapi sapi::vars ) ``` -------------------------------- ### Configure pngtopng Executable in CMake Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/libpng/examples/CMakeLists.txt Defines the build target for the pngtopng example, linking necessary SAPI and PNG libraries. ```cmake add_executable(pngtopng example1.cc ../tests/libpng.h ../sandboxed.h ) find_package(PNG REQUIRED) target_link_libraries(pngtopng PRIVATE sapi::sapi sapi::temp_file libpng_sapi "${PNG_LIBRARY}" ) target_include_directories(pngtopng INTERFACE "${PNG_INCLUDE_DIR}" ) ``` -------------------------------- ### Install GDAL Dependencies Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/gdal/README.md Commands to install necessary system packages for GDAL on Linux. ```bash sudo apt-get install python3.6-dev sudo add-apt-repository ppa:ubuntugis/ppa && sudo apt update sudo apt-get install gdal-bin sudo apt-get install libgdal-dev ``` -------------------------------- ### Build Example 2: In-Memory Data Handling Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/curl/examples/CMakeLists.txt This CMakeLists.txt configures an executable for handling network data in memory using the Sandboxed API and curl. It includes the necessary Sandboxed API and curl libraries. ```cmake add_executable(example2 example2.cc ../sandbox.h ) target_link_libraries(example2 PRIVATE curl_sapi curl_util sapi::sapi ) ``` -------------------------------- ### Build LibUV Sandbox Library Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/libuv/README.md Build the library using CMake. Ensure SAPI_ROOT is set to the path of your Sandboxed API installation. ```bash mkdir -p build cd build cmake .. -G Ninja -D SAPI_ROOT=[path to sandboxed-api] cmake --build . ``` -------------------------------- ### CMake Minimum Version and Project Setup Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/libarchive/CMakeLists.txt Sets the minimum required CMake version and defines the project name and language. ```cmake cmake_minimum_required(VERSION 3.16) project(libarchive_sapi CXX) ``` -------------------------------- ### Set Interface Include Directories Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/libarchive/examples/CMakeLists.txt Specifies interface include directories for 'sapi_minitar_lib'. This makes headers in the 'examples' directory available to targets linking against this library. ```cmake target_include_directories(sapi_minitar_lib INTERFACE "${PROJECT_SOURCE_DIR}/examples" ) ``` -------------------------------- ### Build Example 3: Simple SSL Request Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/curl/examples/CMakeLists.txt This CMakeLists.txt configures an executable for making a simple SSL network request with the Sandboxed API and curl. It ensures the Sandboxed API and curl libraries are linked. ```cmake add_executable(example3 example3.cc ../sandbox.h ) target_link_libraries(example3 PRIVATE curl_sapi curl_util sapi::sapi ) ``` -------------------------------- ### Build Example 5: Multi-Threaded Network Operations Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/curl/examples/CMakeLists.txt This CMakeLists.txt configures an executable for performing network operations in multiple threads using the Sandboxed API and curl. It links against the necessary Sandboxed API and curl libraries. ```cmake add_executable(example5 example5.cc ../sandbox.h ) target_link_libraries(example5 PRIVATE curl_sapi curl_util sapi::sapi ) ``` -------------------------------- ### Configure rgbtobgr Executable in CMake Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/libpng/examples/CMakeLists.txt Defines the build target for the rgbtobgr example, linking necessary SAPI and PNG libraries. ```cmake add_executable(rgbtobgr example2.cc ../tests/libpng.h ../sandboxed.h ) target_link_libraries(rgbtobgr PRIVATE sapi::sapi sapi::temp_file libpng_sapi "${PNG_LIBRARY}" ) target_include_directories(rgbtobgr INTERFACE "${PNG_INCLUDE_DIR}" ) ``` -------------------------------- ### Add global forkserver library constructor Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/sandbox2/CMakeLists.txt Adds a static library that ensures the global forkserver is started very early. Use this only if necessary, as the forkserver typically starts on demand. ```cmake # Use only if Sandbox2 global forkserver has to be started very early on. # By default the forkserver is started on demand. add_library(sandbox2_start_global_forkserver_lib_constructor STATIC global_forkclient_lib_ctor.cc ) add_library(sandbox2::start_global_forkserver_lib_constructor ALIAS sandbox2_start_global_forkserver_lib_constructor) target_link_libraries(sandbox2_start_global_forkserver_lib_constructor PRIVATE absl::core_headers sapi::base sandbox2::fork_client sandbox2::global_forkserver ) ``` -------------------------------- ### CMake Minimum Version and Project Setup Source: https://github.com/google/sandboxed-api/blob/main/contrib/zopfli/CMakeLists.txt Sets the minimum required CMake version and defines the project name and language. Ensure your CMake version is compatible. ```cmake cmake_minimum_required(VERSION 3.13..3.26) project(sapi_zopfli CXX) ``` -------------------------------- ### Build Example 6: Transactions with Sandboxed API Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/curl/examples/CMakeLists.txt This CMakeLists.txt configures an executable for using transactions within the Sandboxed API, likely for network operations with curl. It links the Sandboxed API and curl libraries. ```cmake add_executable(example6 example6.cc ../sandbox.h ) target_link_libraries(example6 PRIVATE curl_sapi curl_util sapi::sapi ) ``` -------------------------------- ### Setup Sandboxed API Cache Variables Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/libuv/CMakeLists.txt Configures cache variables for the Sandboxed API, including the root path and build flags for examples and testing. The FORCE option ensures these values override any existing cache entries. ```cmake set(SAPI_ROOT "" CACHE PATH "Path to the Sandboxed API source tree") set(SAPI_BUILD_EXAMPLES ${SAPI_UV_ENABLE_EXAMPLES} CACHE BOOL "" FORCE) set(SAPI_BUILD_TESTING ${SAPI_UV_ENABLE_TESTS} CACHE BOOL "" FORCE) ``` -------------------------------- ### Initialize Sandbox and Execute Function Source: https://context7.com/google/sandboxed-api/llms.txt Demonstrates initializing a sandboxed library instance and invoking a function through an auto-generated API wrapper. ```cpp #include "sandboxed_api/examples/hello_sapi/hello_sapi.sapi.h" int main() { // Create sandbox instance (auto-generated from library) HelloSandbox sandbox; // Initialize the sandbox - starts the sandboxed process absl::Status status = sandbox.Init(); if (!status.ok()) { std::cerr << "Failed to initialize sandbox: " << status.message() << "\n"; return 1; } // Create API wrapper for the sandboxed library HelloApi api(&sandbox); // Call sandboxed function - returns StatusOr absl::StatusOr result = api.AddTwoIntegers(1000, 337); if (result.ok()) { std::cout << "1000 + 337 = " << result.value() << "\n"; // Output: 1337 } // Sandbox is automatically terminated when it goes out of scope return 0; } ``` -------------------------------- ### Build the Project Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/openjpeg/README.md Standard build sequence using CMake and Ninja within the project directory. ```bash mkdir build && cd build cmake -G Ninja ninja ``` -------------------------------- ### Run Tests Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/libpng/README.md Run the library tests. Requires building with -DLIBPNG_SAPI_BUILD_TESTING=ON. ```bash cd tests ctest . ``` -------------------------------- ### Create Basic Sandbox with Sandbox2 PolicyBuilder Source: https://context7.com/google/sandboxed-api/llms.txt Illustrates how to create and configure a sandboxed process using Sandbox2's low-level API. This includes setting resource limits, defining a security policy with allowed/blocked syscalls and file access, and running the sandbox. ```cpp #include "sandboxed_api/sandbox2/sandbox2.h" #include "sandboxed_api/sandbox2/executor.h" #include "sandboxed_api/sandbox2/policybuilder.h" #include "sandboxed_api/sandbox2/result.h" int main() { // Path to the binary to sandbox std::string binary_path = "/path/to/sandboxee"; std::vector args = {binary_path, "--arg1", "value"}; std::vector envs = {"PATH=/usr/bin", "HOME=/tmp"}; // Create executor for the sandboxed binary auto executor = std::make_unique(binary_path, args, envs); // Configure resource limits executor->limits() ->set_rlimit_as(256ULL << 20) // 256 MB address space .set_rlimit_cpu(60) // 60 seconds CPU time .set_rlimit_fsize(64ULL << 20) // 64 MB max file size .set_rlimit_nofile(256) // 256 file descriptors .set_walltime_limit(absl::Seconds(30)); // 30 second wall time // Build security policy auto policy = sandbox2::PolicyBuilder() .AllowStaticStartup() .AllowRead() .AllowWrite() .AllowExit() .AllowSystemMalloc() .AllowSyscall(__NR_getpid) // Block specific syscalls with custom error .BlockSyscallWithErrno(__NR_ptrace, EPERM) // Add file access .AddFile("/etc/passwd", /*is_ro=*/true) .AddDirectory("/tmp", /*is_ro=*/false) .BuildOrDie(); // Create and run sandbox sandbox2::Sandbox2 sandbox(std::move(executor), std::move(policy)); sandbox2::Result result = sandbox.Run(); // Check result if (result.final_status() == sandbox2::Result::OK) { std::cout << "Sandbox exited normally with code: " << result.reason_code() << "\n"; return 0; } else { std::cerr << "Sandbox failed: " << result.ToString() << "\n"; if (!result.stack_trace().empty()) { std::cerr << "Stack trace:\n" << result.GetStackTrace() << "\n"; } return 1; } } ``` -------------------------------- ### Conditional Subdirectory Inclusion for Examples and Tests Source: https://github.com/google/sandboxed-api/blob/main/contrib/libxls/CMakeLists.txt These CMake commands conditionally add subdirectories for examples and tests based on build flags. Examples are included if 'SAPI_BUILD_EXAMPLES' is true, and tests are included if 'BUILD_TESTING' and 'SAPI_BUILD_TESTING' are both true. ```cmake if(SAPI_BUILD_EXAMPLES) add_subdirectory(example) endif() if(BUILD_TESTING AND SAPI_BUILD_TESTING) add_subdirectory(test) endif() ``` -------------------------------- ### Configure Sandbox2 BPF Helper Test Executable Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/sandbox2/util/CMakeLists.txt Builds the sandbox2_bpf_helper_test executable. Links against absl::strings, sandbox2::bpf_helper, and sapi::test_main. ```cmake add_executable(sandbox2_bpf_helper_test bpf_helper_test.cc ) set_target_properties(sandbox2_bpf_helper_test PROPERTIES OUTPUT_NAME bpf_helper_test ) target_link_libraries(sandbox2_bpf_helper_test PRIVATE absl::strings sandbox2::bpf_helper sapi::test_main ) gtest_discover_tests_xcompile(sandbox2_bpf_helper_test) ``` -------------------------------- ### Run Sandboxed PFFFT for Testing Source: https://github.com/google/sandboxed-api/blob/main/contrib/pffft/README.md Navigate to the build directory and execute the sandboxed PFFFT binary for testing purposes. ```bash cd build ./pffft_sandboxed ``` -------------------------------- ### Build the sandboxed library Source: https://github.com/google/sandboxed-api/blob/main/contrib/libtiff/README.md Use CMake to configure and build the project from the build directory. ```bash mkdir -p build && cd build && cmake .. \ -DSAPI_ROOT=$HOME/sapi_root \ -DBUILD_SHARED_LIBS=OFF make -j 8 ``` -------------------------------- ### Build Sandbox2 Static Bin Executable Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/sandbox2/examples/static/CMakeLists.txt Defines the `sandbox2_static_bin` executable, setting its output name and linking it with `sapi::base` using a fully static link (`-static-pie`). This ensures the binary is self-contained. ```bazel add_executable(sandbox2_static_bin static_bin.cc ) set_target_properties(sandbox2_static_bin PROPERTIES OUTPUT_NAME static_bin) add_executable(sandbox2::static_bin ALIAS sandbox2_static_bin) target_link_libraries(sandbox2_static_bin PRIVATE sapi::base -static-pie # Fully static link ) ``` -------------------------------- ### Create Dynamic Library Sandboxing Policy Source: https://context7.com/google/sandboxed-api/llms.txt Configure a policy for sandboxing dynamically linked binaries by allowing dynamic startup and mapping the binary and its libraries. This policy includes standard operations and optional network operations, along with necessary system directories. ```cpp #include "sandboxed_api/sandbox2/policybuilder.h" #include "sandboxed_api/sandbox2/allowlists/map_exec.h" std::unique_ptr CreateDynamicLibraryPolicy( const std::string& binary_path) { return sandbox2::PolicyBuilder() // Allow dynamic linking startup .AllowDynamicStartup(sandbox2::MapExec()) // Standard operations .AllowRead() .AllowWrite() .AllowOpen() .AllowStat() .AllowExit() .AllowSystemMalloc() .AllowHandleSignals() // Network operations (if needed) .AllowSyscalls({__NR_socket, __NR_connect, __NR_sendto, __NR_recvfrom}) // Add the binary and its libraries .AddFile(binary_path, /*is_ro=*/true) .AddLibrariesForBinary(binary_path) // Add required system directories .AddDirectory("/lib", /*is_ro=*/true) .AddDirectory("/lib64", /*is_ro=*/true) .AddDirectory("/usr/lib", /*is_ro=*/true) .BuildOrDie(); } ``` -------------------------------- ### Build networkproxy_bin Executable Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/sandbox2/examples/network_proxy/CMakeLists.txt Defines the networkproxy_bin executable, sets its output name, and links required libraries for the network proxy client functionality. ```bazel add_executable(sandbox2_networkproxy_bin networkproxy_bin.cc ) set_target_properties(sandbox2_networkproxy_bin PROPERTIES OUTPUT_NAME networkproxy_bin ) add_executable(sandbox2::networkproxy_bin ALIAS sandbox2_networkproxy_bin) target_link_libraries(sandbox2_networkproxy_bin PRIVATE absl::status absl::flags absl::flags_parse absl::log absl::log_globals absl::log_initialize absl::statusor absl::str_format absl::strings sandbox2::client sandbox2::comms sapi::fileops sandbox2::network_proxy_client sapi::base sapi::status sapi::strerror ) ``` -------------------------------- ### Configure Sandbox2 Seccomp Unotify Test Executable Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/sandbox2/util/CMakeLists.txt Builds the sandbox2_seccomp_unotify_test executable. Links against sandbox2::seccomp_unotify, absl::statusor, and sapi testing utilities. ```cmake add_executable(sandbox2_seccomp_unotify_test seccomp_unotify_test.cc ) set_target_properties(sandbox2_seccomp_unotify_test PROPERTIES OUTPUT_NAME seccomp_unotify_test ) target_link_libraries(sandbox2_seccomp_unotify_test PRIVATE sandbox2::seccomp_unotify absl::statusor sapi::fileops sapi::testing sapi::test_main ) gtest_discover_tests_xcompile(sandbox2_seccomp_unotify_test) ``` -------------------------------- ### Configure Sandbox2 PID Waiter Test Executable Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/sandbox2/util/CMakeLists.txt Builds the sandbox2_pid_waiter_test executable. Links against absl::time, sandbox2::pid_waiter, and sapi threading utilities. ```cmake add_executable(sandbox2_pid_waiter_test pid_waiter_test.cc ) set_target_properties(sandbox2_pid_waiter_test PROPERTIES OUTPUT_NAME pid_waiter_test ) target_link_libraries(sandbox2_pid_waiter_test PRIVATE absl::time sandbox2::pid_waiter sapi::test_main sapi::thread ) ``` -------------------------------- ### Find and Check TurboJPEG with PkgConfig Source: https://github.com/google/sandboxed-api/blob/main/contrib/turbojpeg/CMakeLists.txt Locates the TurboJPEG library using PkgConfig and makes its imported target available. This requires TurboJPEG to be installed and discoverable by PkgConfig. ```cmake find_package(PkgConfig REQUIRED) pkg_check_modules(TURBOJPEG REQUIRED IMPORTED_TARGET libturbojpeg) ``` -------------------------------- ### Configure and define the sapi_base library Source: https://github.com/google/sandboxed-api/blob/main/CMakeLists.txt Sets up the base library with C++ standard features, include directories, and compiler-specific flags. ```cmake configure_file(cmake/sapi_force_cxx_linkage.cc.in "${SAPI_BINARY_DIR}/sapi_force_cxx_linkage.cc" COPYONLY) add_library(sapi_base STATIC "${SAPI_BINARY_DIR}/sapi_force_cxx_linkage.cc" ) add_library(sapi::base ALIAS sapi_base) target_compile_features(sapi_base PUBLIC cxx_std_${SAPI_CXX_STANDARD} ) set_target_properties(sapi_base PROPERTIES INTERFACE_POSITION_INDEPENDENT_CODE ON ) target_include_directories(sapi_base PUBLIC "${SAPI_BINARY_DIR}" "${SAPI_SOURCE_DIR}" "${Protobuf_INCLUDE_DIR}" ) target_compile_options(sapi_base PUBLIC -fno-exceptions ) if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") target_compile_options(sapi_base PUBLIC # The syscall tables in sandbox2/syscall_defs.cc are `std::array`s using # CTAD and have more entries than the default limit of 256. -fbracket-depth=768 ) endif() set(_sapi_check_no_deprecated -Wno-deprecated SAPI_HAS_W_NO_DEPRECATED ) set(_sapi_check_frame_larger_than # For sandbox2/util.cc's CloneAndJump() -Wframe-larger-than=40960 SAPI_HAS_W_FRAME_LARGER_THAN ) set(_sapi_check_no_deprecated_declarations -Wno-deprecated-declarations SAPI_HAS_W_NO_DEPRECATED_DECLARATIONS ) set(_sapi_check_no_psabi -Wno-psabi SAPI_HAS_W_NO_PSABI ) foreach(check IN ITEMS _sapi_check_no_deprecated _sapi_check_frame_larger_than _sapi_check_no_deprecated_declarations _sapi_check_no_psabi) list(GET ${check} 0 opt_value) list(GET ${check} 1 var_name) check_cxx_compiler_flag(${opt_value} ${var_name}) if(${var_name}) target_compile_options(sapi_base PUBLIC ${opt_value}) endif() endforeach() ``` -------------------------------- ### Configure Sandboxed API with CMake Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/examples/hello_sapi/CMakeLists.txt Sets up the Sandboxed API root path and configures build options to exclude examples and testing. This is essential for integrating Sandboxed API into your project. ```cmake cmake_minimum_required(VERSION 3.12) project(hello_sapi_project CXX) # Path to the Sandboxed API source tree. Unlike Bazel, CMake does not download # downstream dependencies by default. So the option below needs to be adjusted # to point to a local checkout or a Git submodule. # The default value is chosen so that this example can be easily tried out for # a regular checkout of Sandboxed API. set(SAPI_ROOT "${PROJECT_SOURCE_DIR}/../../.." CACHE PATH "Path to the Sandboxed API source tree") # Configure options and include Sandboxed API as a sub-directory. set(SAPI_BUILD_EXAMPLES OFF CACHE BOOL "") set(SAPI_BUILD_TESTING OFF CACHE BOOL "") add_subdirectory("${SAPI_ROOT}" "${CMAKE_BINARY_DIR}/sandboxed-api-build" EXCLUDE_FROM_ALL) ``` -------------------------------- ### Configure Sandbox2 MiniElf Test Executable Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/sandbox2/util/CMakeLists.txt Builds the sandbox2_minielf_test executable. Includes configuration for test data and links against various libraries including absl, sapi, and sandbox2 components. ```cmake add_executable(sandbox2_minielf_test minielf_test.cc ) set_target_properties(sandbox2_minielf_test PROPERTIES OUTPUT_NAME minielf_test ) configure_file(testdata/hello_world testdata/hello_world COPYONLY) configure_file(testdata/chrome_grte_header testdata/chrome_grte_header COPYONLY) target_link_libraries(sandbox2_minielf_test PRIVATE absl::algorithm_container absl::status_matchers absl::statusor sapi::fileops sapi::file_helpers sandbox2::maps_parser sandbox2::minielf sapi::testing sapi::test_main PUBLIC absl::statusor ) gtest_discover_tests_xcompile(sandbox2_minielf_test PROPERTIES ENVIRONMENT "TEST_TMPDIR=/tmp" ENVIRONMENT "TEST_SRCDIR=${PROJECT_BINARY_DIR}" ) ``` -------------------------------- ### Map File Descriptors to Sandboxee Source: https://context7.com/google/sandboxed-api/llms.txt Demonstrates how to pass host file descriptors to a sandboxed process using IPC. MapFd transfers ownership, while MapDupedFd keeps the file descriptor open in the host. ```cpp #include "sandboxed_api/sandbox2/sandbox2.h" #include "sandboxed_api/sandbox2/ipc.h" int main() { std::string binary = "/path/to/sandboxee"; auto executor = std::make_unique(binary, {binary}); // Open files in the host process int input_fd = open("/input/file.txt", O_RDONLY); int output_fd = open("/output/result.txt", O_WRONLY | O_CREAT, 0644); // Map host FDs to sandboxee FDs // MapFd transfers ownership - fd will be closed after sending executor->ipc()->MapFd(input_fd, STDIN_FILENO); // input_fd -> stdin executor->ipc()->MapFd(output_fd, STDOUT_FILENO); // output_fd -> stdout // Named mapping - sandboxee retrieves via Client::GetMappedFD("config") int config_fd = open("/etc/config.json", O_RDONLY); executor->ipc()->MapFd(config_fd, "config"); // MapDupedFd keeps the fd open in the host int log_fd = open("/var/log/sandbox.log", O_WRONLY | O_APPEND); executor->ipc()->MapDupedFd(log_fd, STDERR_FILENO); // Can still use log_fd // ReceiveFd creates a socketpair for bidirectional communication int host_socket = executor->ipc()->ReceiveFd("data_channel"); auto policy = sandbox2::PolicyBuilder() .AllowRead() .AllowWrite() .AllowExit() .AllowSafeFcntl() .BuildOrDie(); sandbox2::Sandbox2 sandbox(std::move(executor), std::move(policy)); sandbox.RunAsync(); // Communicate through the socketpair const char* message = "Hello from host!"; write(host_socket, message, strlen(message)); char response[256]; ssize_t n = read(host_socket, response, sizeof(response) - 1); if (n > 0) { response[n] = '\0'; std::cout << "Received: " << response << "\n"; } sandbox2::Result result = sandbox.AwaitResult(); close(host_socket); close(log_fd); return result.final_status() == sandbox2::Result::OK ? 0 : 1; } ``` -------------------------------- ### CMake Project Setup for OpenJPEG Sandboxed API Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/openjpeg/CMakeLists.txt Configures the CMake project for OpenJPEG with C++17 standard and sets build options for shared libraries. It includes the OpenJPEG source and the Sandboxed API build. ```cmake cmake_minimum_required(VERSION 3.10) project(openjpeg-sapi C CXX) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED True) # To override lib option -- else SAPI won't work set(BUILD_SHARED_LIBS OFF CACHE BOOL "Build OpenJPEG shared library and link executables against it." FORCE) add_subdirectory(openjpeg) ``` -------------------------------- ### Build Example 4: Multi-Poll Network Operations Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/curl/examples/CMakeLists.txt This CMakeLists.txt configures an executable for managing multiple network operations concurrently using poll with the Sandboxed API and curl. It links the required Sandboxed API and curl libraries. ```cmake add_executable(example4 example4.cc ../sandbox.h ) target_link_libraries(example4 PRIVATE curl_sapi curl_util sapi::sapi ) ``` -------------------------------- ### Run tests Source: https://github.com/google/sandboxed-api/blob/main/contrib/libtiff/README.md Execute the test suite for the sandboxed library. ```bash ./test/tests ``` -------------------------------- ### Define Zlib Sandboxed API Library Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/examples/zlib/CMakeLists.txt Configures the Zlib sandboxed API library, specifying exported functions, header files, and external library dependencies. This setup allows Zlib functions to be called in a sandboxed environment. ```cmake add_sapi_library(zlib-sapi FUNCTIONS deflateInit_ deflate deflateEnd INPUTS "${ZLIB_INCLUDE_DIRS}/zlib.h" LIBRARY ZLIB::ZLIB LIBRARY_NAME Zlib NAMESPACE "sapi::zlib" ) add_library(sapi::zlib_sapi ALIAS zlib-sapi) target_link_libraries(zlib-sapi PRIVATE ZLIB::ZLIB ) ``` -------------------------------- ### Define SAPI Test Library and Executable Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/tests/CMakeLists.txt Configures a static library, a SAPI library wrapper, and a test executable for sandboxed testing. ```cmake if(BUILD_TESTING AND SAPI_BUILD_TESTING AND NOT CMAKE_CROSSCOMPILING) # sandboxed_api/examples/sum/lib:sum add_library(sapi_test_lib STATIC sapi_test_lib_cpp.cc ) add_library(sapi::test_lib ALIAS sapi_test_lib) target_link_libraries(sapi_test_lib PRIVATE absl::algorithm_container absl::span sapi::base ) # sandboxed_api/examples/sum/lib:sum-sapi add_sapi_library(sapi_test-sapi FUNCTIONS accumulate INPUTS sapi_test_lib_cpp.cc LIBRARY sapi_test_lib LIBRARY_NAME SapiTest NAMESPACE "" ) add_library(sapi::sapi_test_sapi ALIAS sapi_test-sapi) target_link_libraries(sapi_test-sapi PRIVATE sapi::base ) # sandboxed_api:sapi_test add_executable(sapi_test sapi_test.cc ) target_link_libraries(sapi_test PRIVATE absl::status absl::status_matchers absl::statusor absl::time benchmark sandbox2::result sapi::fileops sapi::proto_arg_proto sapi::sapi sapi::sapi_test_sapi sapi::status sapi::stringop_sapi sapi::sum_sapi sapi::test_main sapi::testing sapi::thread ) gtest_discover_tests_xcompile(sapi_test) endif() ``` -------------------------------- ### Fetch and Make Zopfli Available Source: https://github.com/google/sandboxed-api/blob/main/contrib/zopfli/CMakeLists.txt Fetches the Zopfli library from its Git repository using FetchContent and makes it available for use. Ensure network access to the repository. ```cmake FetchContent_Declare(zopfli GIT_REPOSITORY https://github.com/google/zopfli.git GIT_TAG 831773bc28e318b91a3255fa12c9fcde1606058b ) FetchContent_MakeAvailable(zopfli) ``` -------------------------------- ### Build sandbox2 namespace test executable Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/sandbox2/CMakeLists.txt Sets up the sandbox2_namespace_test executable, defining its dependencies and linking required libraries for namespace testing. ```cmake add_executable(sandbox2_namespace_test namespace_test.cc ) set_target_properties(sandbox2_namespace_test PROPERTIES OUTPUT_NAME namespace_test ) add_dependencies(sandbox2_namespace_test sandbox2::testcase_namespace ) target_link_libraries(sandbox2_namespace_test PRIVATE absl::check absl::status absl::statusor absl::strings sandbox2::allowlists_all_syscalls sandbox2::allowlists_unrestricted_networking sandbox2::allowlists_namespaces sapi::fileops sandbox2::namespace sandbox2::sandbox2 sapi::testing sapi::temp_file sapi::test_main ) gtest_discover_tests_xcompile(sandbox2_namespace_test PROPERTIES ENVIRONMENT "TEST_TMPDIR=/tmp" ENVIRONMENT "TEST_SRCDIR=${PROJECT_BINARY_DIR}" ) ``` -------------------------------- ### Build networkproxy_sandbox Executable Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/sandbox2/examples/network_proxy/CMakeLists.txt Defines the networkproxy_sandbox executable, its dependencies, and links necessary libraries for network proxy functionality within a sandbox environment. ```bazel add_executable(sandbox2_networkproxy_sandbox networkproxy_sandbox.cc ) add_executable(sandbox2::networkproxy_sandbox ALIAS sandbox2_networkproxy_sandbox) add_dependencies(sandbox2_networkproxy_sandbox sandbox2::networkproxy_bin ) target_link_libraries(sandbox2_networkproxy_sandbox PRIVATE absl::flags absl::flags_parse absl::log absl::log_globals absl::log_initialize absl::log_severity absl::statusor absl::strings absl::time sandbox2::bpf_helper sandbox2::comms sandbox2::network_proxy_testing sapi::runfiles sandbox2::sandbox2 sapi::base ) ``` -------------------------------- ### Initialize GDAL Submodule Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/gdal/README.md Command to add the GDAL repository as a git submodule. ```bash git submodule add https://github.com/OSGeo/gdal/tree/master/gdal ``` -------------------------------- ### Test GDAL Implementation Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/gdal/README.md Commands to build the project using CMake/Ninja and execute the raster test. ```bash mkdir build && cd build cmake .. -G Ninja ninja ./raster ``` -------------------------------- ### Configure filewrapper test suite Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/tools/filewrapper/CMakeLists.txt Sets up the test executable, links testing dependencies, and configures test environment variables. ```cmake if(BUILD_TESTING AND SAPI_BUILD_TESTING) # sandboxed_api/tools/filewrapper:filewrapper_test add_executable(sapi_filewrapper_test filewrapper_test.cc ) set_target_properties(sapi_filewrapper_test PROPERTIES OUTPUT_NAME filewrapper_test ) configure_file(testdata/filewrapper_embedded.bin testdata/filewrapper_embedded.bin COPYONLY) target_link_libraries(sapi_filewrapper_test PRIVATE filewrapper_embedded absl::status_matchers sapi::file_helpers sapi::fileops sapi::testing sapi::test_main ) gtest_discover_tests_xcompile(sapi_filewrapper_test PROPERTIES ENVIRONMENT "TEST_TMPDIR=/tmp" ENVIRONMENT "TEST_SRCDIR=${PROJECT_BINARY_DIR}" ) endif() ``` -------------------------------- ### Transfer File Descriptors with Sandboxed API Source: https://context7.com/google/sandboxed-api/llms.txt Demonstrates how to open a file on the host, transfer its file descriptor to a sandboxed process, and use it for reading within the sandbox. Ensure the file descriptor is properly closed after use. ```cpp #include "sandboxed_api/vars.h" #include absl::Status TransferFileDescriptors(sapi::SandboxBase* sandbox) { MyApi api(sandbox); // Open a file in the host process int fd = open("/path/to/file", O_RDONLY); if (fd < 0) { return absl::ErrnoToStatus(errno, "Failed to open file"); } // Wrap the fd for transfer sapi::v::Fd remote_fd(fd); // Transfer fd to sandboxee SAPI_RETURN_IF_ERROR(sandbox->TransferToSandboxee(&remote_fd)); // Use the remote fd in sandboxed function int remote_fd_num = remote_fd.GetRemoteFd(); if (remote_fd_num < 0) { return absl::InternalError("Failed to get remote fd"); } // Read from file in sandboxee char buffer[256] = {0}; sapi::v::Array buf(buffer, sizeof(buffer)); sapi::v::Int bytes_read; SAPI_RETURN_IF_ERROR(sandbox->Call("read", &bytes_read, &remote_fd, buf.PtrAfter(), sapi::v::UInt(sizeof(buffer) - 1))); std::cout << "Read " << bytes_read.GetValue() << " bytes: " << buffer << "\n"; // Close the remote fd SAPI_RETURN_IF_ERROR(remote_fd.CloseRemoteFd(sandbox->rpc_channel())); return absl::OkStatus(); } ``` -------------------------------- ### Configure PROJ database path Source: https://github.com/google/sandboxed-api/blob/main/oss-internship-2020/gdal/raster_to_gtiff/README.md Sets the environment variable to point to the proj.db file for use within the sandbox. ```bash export PROJ_DB_PATH=/path/to/proj.db ``` -------------------------------- ### Build Main Zlib Application Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/examples/zlib/CMakeLists.txt Creates an executable for the main Zlib application, linking it with necessary Sandboxed API components and Google libraries. This allows the application to utilize the sandboxed Zlib functionality. ```cmake add_executable(sapi_main_zlib main_zlib.cc ) set_target_properties(sapi_main_zlib PROPERTIES OUTPUT_NAME main_zlib) target_link_libraries(sapi_main_zlib PRIVATE sapi::base absl::flags_parse absl::log absl::log_initialize absl::log_severity absl::status absl::statusor sapi::sapi sapi::status sapi::zlib_sapi ) ``` -------------------------------- ### Use Shared Memory Buffer Source: https://context7.com/google/sandboxed-api/llms.txt Shows how to create a shared memory buffer for efficient data transfer. Requires AllowSharedMemory in the sandbox policy. ```cpp #include "sandboxed_api/sandbox2/buffer.h" #include "sandboxed_api/sandbox2/sandbox2.h" int main() { // Create a shared buffer auto buffer_result = sandbox2::Buffer::CreateWithSize( 1 << 20, // 1 MB "shared_data"); if (!buffer_result.ok()) { std::cerr << "Failed to create buffer: " << buffer_result.status() << "\n"; return 1; } std::unique_ptr buffer = std::move(*buffer_result); // Write data to the buffer (visible to both host and sandboxee) uint8_t* data = buffer->data(); std::memcpy(data, "Initial data from host", 22); std::string binary = "/path/to/sandboxee"; auto executor = std::make_unique(binary, {binary}); // Map the buffer's fd to the sandboxee // Sandboxee can mmap this fd to access the shared memory executor->ipc()->MapDupedFd(buffer->fd(), "shared_buffer"); auto policy = sandbox2::PolicyBuilder() .AllowRead() .AllowWrite() .AllowExit() .AllowMmapWithoutExec() .AllowSharedMemory() // Required for shared memory .BuildOrDie(); sandbox2::Sandbox2 sandbox(std::move(executor), std::move(policy)); sandbox.Run(); // Read data modified by sandboxee std::cout << "Buffer after sandboxee: " << reinterpret_cast(buffer->data()) << "\n"; return 0; } ``` -------------------------------- ### Build LodePNG Sandboxed API Source: https://github.com/google/sandboxed-api/blob/main/contrib/lodepng/README.md Commands to build the sandboxed API. Ensure you are in the project's root directory. ```bash mkdir -p build && cd build cmake .. -G Ninja cmake --build . ``` -------------------------------- ### Configure Lodepng SAPI Build Source: https://github.com/google/sandboxed-api/blob/main/contrib/lodepng/CMakeLists.txt Defines the project, fetches the Lodepng source, and configures the SAPI library interface for specific Lodepng functions. ```cmake cmake_minimum_required(VERSION 3.13..3.26) project(lodepng_sapi C CXX) include(CTest) include(GoogleTest) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED 17) if(NOT TARGET sapi::sapi) set(SAPI_ROOT "../.." CACHE PATH "Path to the Sandboxed API source tree") add_subdirectory("${SAPI_ROOT}" "${CMAKE_BINARY_DIR}/sandboxed-api-build" EXCLUDE_FROM_ALL) endif() FetchContent_Declare(lodepng GIT_REPOSITORY https://github.com/lvandeve/lodepng.git GIT_TAG 3d9fda048393e32cc11d0c3d3caba0a85c1c2dfe # 2022-05-22 ) FetchContent_MakeAvailable(lodepng) # lodepng can be compiled as both C++ and C. We want the latter, so enforce # C as the language. set_source_files_properties() does not work here. configure_file(lodepng.gen.h.in "${lodepng_BINARY_DIR}/lodepng.gen.h") configure_file("${lodepng_SOURCE_DIR}/lodepng.cpp" "${lodepng_BINARY_DIR}/lodepng.c" COPYONLY) # Build static library add_library(lodepng STATIC "${lodepng_BINARY_DIR}/lodepng.c" "${lodepng_BINARY_DIR}/lodepng.gen.h" "${lodepng_SOURCE_DIR}/lodepng.h" ) target_include_directories(lodepng PUBLIC "${lodepng_BINARY_DIR}" "${lodepng_SOURCE_DIR}" ) target_compile_definitions(lodepng PUBLIC LODEPNG_NO_COMPILE_CPP ) # Build SAPI library add_sapi_library(lodepng_sapi FUNCTIONS lodepng_decode_memory lodepng_decode32 lodepng_decode24 lodepng_decode_file lodepng_decode32_file lodepng_decode24_file lodepng_encode_memory lodepng_encode32 lodepng_encode24 lodepng_encode_file lodepng_encode32_file lodepng_encode24_file lodepng_save_file lodepng_load_file INPUTS "${lodepng_BINARY_DIR}/lodepng.gen.h" LIBRARY lodepng LIBRARY_NAME Lodepng NAMESPACE "" ) add_library(sapi_contrib::lodepng ALIAS lodepng_sapi) target_include_directories(lodepng_sapi INTERFACE "${PROJECT_BINARY_DIR}" # To find the generated SAPI header ) # Examples and tests add_subdirectory(examples) ``` -------------------------------- ### Create Sandboxed API Library for String Operations Source: https://github.com/google/sandboxed-api/blob/main/sandboxed_api/examples/stringop/CMakeLists.txt Creates a Sandboxed API library named 'stringop-sapi' that exposes various string manipulation functions. It depends on the 'sapi_stringop' library and includes C++ source files. ```bazel add_sapi_library(stringop-sapi FUNCTIONS duplicate_string reverse_string pb_duplicate_string pb_reverse_string nop violate get_raw_c_string INPUTS stringop.cc LIBRARY sapi_stringop LIBRARY_NAME Stringop NAMESPACE "" ) add_library(sapi::stringop_sapi ALIAS stringop-sapi) target_link_libraries(stringop-sapi PRIVATE $ sapi::base ) ```