使用Google Sandboxed-api

使用Google Sandboxed-api

本文章基于Ubuntu20.04

Sandboxed-api介绍

Sandboxed-api是google推出的开源沙箱SandBox2的封装,能共更为方便的实现沙箱的安全操作

Github仓库链接如下 sandboxed-api

Google官方给出的需求如下

The following dependencies must be installed on the system:

  • Linux kernel with support for UTS, IPC, user, PID, and network namespaces
  • Linux userspace API headers
  • To compile your code: GCC 6 (version 7 or higher preferred) or Clang 7 (or higher)
  • For auto-generating header files: Clang Python Bindings
  • Python 3.5 or later
  • Bazel version 2.2.0 or CMake version 3.12 or higher.
    • CMake only: GNU Make or a version of the libcap library headers and a build tool such as Ninja (recommended).

环境配置

Sandbox-api由于操作系统调度模式不同的原因,不支持在Windows上运行

Windows系统可以通过WSL或者其他虚拟方式创建linux系统运行

  1. 首先安装gcc,g++,cmake,make等编译工具链,以及git仓库管理工具

    sudo apt-get update
    sudo apt-get install gcc g++ make git
    sudo apt-get install -qy build-essential linux-libc-dev cmake ninja-build \
      python3 python3-pip libclang-dev libcap-dev
    pip3 install absl-py clang
    # 这里如果系统使用conda一类的管理工具需要使用 conda install absl-py clang
    

    这里推荐用bazel代替cmake,虽然安装会麻烦点,安装bazel参照 bazel

  2. 执行git clone命令,克隆sandboxed-api仓库

    git clone [email protected]:google/sandboxed-api.git
    

Example编译&使用

Clone下来的项目自带了一些example,我们可以先从这些demo入手,看是如何使用的

Google出品,必为精品

# 跳转到git clone下来的仓库文件夹,并进入hello_sapi文件夹
cd sandboxed-api/sandboxed_api/examples/hello_sapi
# 创建并跳入build目录
mkdir build && cd build
# 使用cmake并指定Ninja编译hello_sapi文件夹
cmake -G Ninja ../
# 使用Ninja编译生成的结果
ninja all
# 运行生成的结果
./hello

输出如下的结果,环境搭建就算成功了

Calling into a sandboxee to add two numbers...
[global_forkclient.cc : 131] RAW: Starting global forkserver
  1000 + 337 = 1337

一定要注意,用了conda的话一定要保证环境一致,不然会有一些编译错误

整体项目编译&测试

# 首先回到clone的git目录
mkdir build && cd build
# 使用cmake并指定Ninja编译hello_sapi文件夹
cmake -G Ninja ../
# 使用Ninja编译生成结果
ninja all
# 转到build后的结果
cd sandboxed_api
# 运行测试
./sapi_test

测试的结果如下就是成功了

Running main() from _deps/googletest-src/googletest/src/gtest_main.cc
[==========] Running 7 tests from 2 test suites.
[----------] Global test environment set-up.
[----------] 1 test from SapiTest
[ RUN      ] SapiTest.HasStackTraces
......
[       OK ] SandboxTest.NoRaceInAwaitResult (442 ms)
[ RUN      ] SandboxTest.NoRaceInConcurrentTerminate
I20220506 21:57:54.849763 38607 monitor.cc:393] Stack traces have been disabled
W20220506 21:57:54.852069 38612 sandbox.cc:122] Sandbox2 finished with: Process killed by user - Code: 0 Stack: 
[       OK ] SandboxTest.NoRaceInConcurrentTerminate (1015 ms)
[----------] 6 tests from SandboxTest (2012 ms total)

[----------] Global test environment tear-down
[==========] 7 tests from 2 test suites ran. (4081 ms total)
[  PASSED  ] 7 tests.

你可能感兴趣的:(2021SC@SDUSC,linux,ubuntu,bash)