security_box 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +23 -0
- data/LICENSE +21 -0
- data/README.md +232 -0
- data/lib/security_box/assets/security_box.wasm +0 -0
- data/lib/security_box/configuration.rb +77 -0
- data/lib/security_box/errors.rb +9 -0
- data/lib/security_box/guest/main.rb +62 -0
- data/lib/security_box/result.rb +45 -0
- data/lib/security_box/runtime.rb +58 -0
- data/lib/security_box/sandbox.rb +151 -0
- data/lib/security_box/version.rb +5 -0
- data/lib/security_box.rb +28 -0
- metadata +73 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 22aa6209552c4b4a4fbc60fa98b71e6f70448fb308e3c8f133515ef663c32d7c
|
|
4
|
+
data.tar.gz: a33ce5bc7a235946efbd283eb3a8f5a718dc87a971eeb3eff799c5b6701ed172
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: aa260831067c04ed120b56d082b068ffd606a060999921e5e4f21f925eb4b721cd37c6e786a646cf024e02a5eba05f4e8e0354311045df76d3d9fb99838aa0fd
|
|
7
|
+
data.tar.gz: 1d0f95de215b37537d2ba3ca638120599d0461d50b783e1e5b52c5c56375d5729f4c1978e815082dc8c824a0389c1f765147cdf5d06f29981ad05e0f99c7ebc3
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [0.1.0] - 2026-09-13
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Initial gem release: `gem install security_box` includes the packed ruby.wasm
|
|
13
|
+
sandbox image (`lib/security_box/assets/security_box.wasm`), so it works out
|
|
14
|
+
of the box without network access or build tools.
|
|
15
|
+
- `SecurityBox.eval`, `SecurityBox.warmup`, `SecurityBox::Sandbox` and the
|
|
16
|
+
immutable `SecurityBox::Configuration` with `#with`.
|
|
17
|
+
- Limit enforcement: fuel, wall-clock (epoch interruption), memory and
|
|
18
|
+
output-size limits; structured `Result` statuses
|
|
19
|
+
(`:ok`, `:error`, `:timeout`, `:fuel_exhausted`, `:memory_limit`,
|
|
20
|
+
`:sandbox_error`).
|
|
21
|
+
- The sandbox image is built with `rake security_box:build_image` from the
|
|
22
|
+
pinned ruby.wasm release (`2.10.1`) and only needs rebuilding when
|
|
23
|
+
`lib/security_box/guest/*.rb` changes or the pin is bumped.
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Marcelo Junior
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
# security_box
|
|
2
|
+
|
|
3
|
+
[](https://rubygems.org/gems/security_box)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
|
|
6
|
+
A secure sandbox to run untrusted Ruby code, built on top of
|
|
7
|
+
[ruby.wasm](https://github.com/ruby/ruby.wasm) and the
|
|
8
|
+
[wasmtime](https://github.com/bytecodealliance/wasmtime-rb) gem.
|
|
9
|
+
|
|
10
|
+
Guest code runs inside a WebAssembly module compiled to `wasm32-unknown-wasip1`, so it has
|
|
11
|
+
no access to the host filesystem, no network, no processes, no threads and no sockets.
|
|
12
|
+
The host controls CPU (fuel), wall-clock time (epoch interruption), memory and output size,
|
|
13
|
+
and always gets a structured `Result` back — even when the guest code raises, times out or
|
|
14
|
+
tries to escape.
|
|
15
|
+
|
|
16
|
+
## How it works
|
|
17
|
+
|
|
18
|
+
1. A `ruby.wasm` image is packed with the Ruby runtime + stdlib + a small guest
|
|
19
|
+
entrypoint (`lib/security_box/guest/main.rb`).
|
|
20
|
+
2. On every `#eval`, the host creates an exclusive tmpdir, writes the user code to it, and
|
|
21
|
+
mounts it read-write as `/work` inside the sandbox.
|
|
22
|
+
3. A fresh wasm instance boots, evaluates the code and serializes a JSON envelope to
|
|
23
|
+
`/work/out.json`.
|
|
24
|
+
4. The host reads the envelope, maps any wasmtime trap to a `Result` status, closes the
|
|
25
|
+
store and discards the tmpdir.
|
|
26
|
+
|
|
27
|
+
One wasm process per `#eval` means zero residual state between executions.
|
|
28
|
+
|
|
29
|
+
## Requirements
|
|
30
|
+
|
|
31
|
+
- Ruby >= 4.0 (host)
|
|
32
|
+
- `wasmtime` gem (runtime) — the only runtime dependency
|
|
33
|
+
- `ruby_wasm` gem (build-time only, needed to rebuild the sandbox image)
|
|
34
|
+
|
|
35
|
+
## Setup
|
|
36
|
+
|
|
37
|
+
Install from RubyGems:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
gem install security_box
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Or add to your `Gemfile`:
|
|
44
|
+
|
|
45
|
+
```ruby
|
|
46
|
+
gem "security_box"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
The gem ships a prebuilt sandbox image (`lib/security_box/assets/security_box.wasm`,
|
|
50
|
+
about 110MB), so no network access or build tools are needed at install or at
|
|
51
|
+
runtime.
|
|
52
|
+
|
|
53
|
+
### Rebuilding the image (development only)
|
|
54
|
+
|
|
55
|
+
If you change `lib/security_box/guest/*.rb` or bump the pinned ruby.wasm
|
|
56
|
+
release, repack the sandbox image:
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
bundle install
|
|
60
|
+
bundle exec rake security_box:build_image
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
This downloads the pinned ruby.wasm release (`2.10.1`, see the `Rakefile`) and
|
|
64
|
+
packs it with the guest script into `lib/security_box/assets/security_box.wasm`.
|
|
65
|
+
The task skips repacking when the image is already fresh. The image is not
|
|
66
|
+
committed to git.
|
|
67
|
+
|
|
68
|
+
You can point the library at a different image with the `SECURITY_BOX_IMAGE`
|
|
69
|
+
environment variable or by passing `image_path:` in the configuration — useful
|
|
70
|
+
for custom-built images.
|
|
71
|
+
|
|
72
|
+
## Usage
|
|
73
|
+
|
|
74
|
+
### Quick start
|
|
75
|
+
|
|
76
|
+
```ruby
|
|
77
|
+
require "security_box"
|
|
78
|
+
|
|
79
|
+
result = SecurityBox.eval("puts 'hello'; 40 + 2")
|
|
80
|
+
|
|
81
|
+
result.status # => :ok
|
|
82
|
+
result.value # => 42
|
|
83
|
+
result.stdout # => "hello\n"
|
|
84
|
+
result.fuel_used # => > 0
|
|
85
|
+
result.duration_ms # => 257.0 (approx; dominated by the ruby.wasm boot)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### Warming up
|
|
89
|
+
|
|
90
|
+
The first `eval` in a process pays the cold WebAssembly compilation of the image
|
|
91
|
+
(~15s) plus the engine setup. Call `SecurityBox.warmup` ahead of time (e.g., at
|
|
92
|
+
boot) to pay that cost up front — every subsequent `eval` then only pays the
|
|
93
|
+
~240ms guest boot:
|
|
94
|
+
|
|
95
|
+
```ruby
|
|
96
|
+
SecurityBox.warmup
|
|
97
|
+
|
|
98
|
+
SecurityBox.eval("40 + 2").value # => 42 (~250ms, no cold compile)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
`#eval` warms the same caches lazily on first use, so calling `warmup` is a pure
|
|
102
|
+
optimization — behavior and results are identical without it. It accepts the same
|
|
103
|
+
options as `Configuration.build` and is safe to call multiple times.
|
|
104
|
+
|
|
105
|
+
### Multiple evaluations on the same sandbox
|
|
106
|
+
|
|
107
|
+
```ruby
|
|
108
|
+
sandbox = SecurityBox::Sandbox.new
|
|
109
|
+
sandbox.eval("1 + 1").value # => 2
|
|
110
|
+
sandbox.eval("3 * 3").value # => 9
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Per-call limits
|
|
114
|
+
|
|
115
|
+
Options can be passed per call (derived from the configuration without mutating it):
|
|
116
|
+
`timeout_ms`, `fuel`, `memory_size`, `stdout_limit`, `stderr_limit`.
|
|
117
|
+
|
|
118
|
+
```ruby
|
|
119
|
+
# Wall-clock limit via epoch interruption
|
|
120
|
+
SecurityBox.eval("while true; end", timeout_ms: 500).status # => :timeout
|
|
121
|
+
|
|
122
|
+
# Deterministic CPU budget
|
|
123
|
+
SecurityBox.eval("while true; end", fuel: 1_000_000).status # => :fuel_exhausted
|
|
124
|
+
|
|
125
|
+
# Memory limit
|
|
126
|
+
SecurityBox.eval(
|
|
127
|
+
"a = []; loop { a << ('x' * 1024) }",
|
|
128
|
+
memory_size: 128 * 1024 * 1024,
|
|
129
|
+
timeout_ms: 15_000
|
|
130
|
+
).status # => :memory_limit
|
|
131
|
+
|
|
132
|
+
# Output truncation
|
|
133
|
+
SecurityBox.eval('1000.times { print "x" * 1000 }', stdout_limit: 4096).stdout.bytesize # => <= 4096
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Errors from guest code
|
|
137
|
+
|
|
138
|
+
Exceptions raised by guest code are a *result*, not a sandbox failure:
|
|
139
|
+
|
|
140
|
+
```ruby
|
|
141
|
+
result = SecurityBox.eval('raise ArgumentError, "boom"')
|
|
142
|
+
|
|
143
|
+
result.status # => :error
|
|
144
|
+
result.error["class"] # => "ArgumentError"
|
|
145
|
+
result.error["message"] # => "boom"
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### Configuration
|
|
149
|
+
|
|
150
|
+
`SecurityBox::Configuration` is immutable; use `.build` to create and `#with` to derive:
|
|
151
|
+
|
|
152
|
+
```ruby
|
|
153
|
+
config = SecurityBox::Configuration.build(
|
|
154
|
+
fuel: 10_000_000_000, # deterministic CPU budget
|
|
155
|
+
timeout_ms: 2_000, # wall-clock limit (epoch interruption)
|
|
156
|
+
memory_size: 512 * 1024 * 1024, # wasm linear memory limit
|
|
157
|
+
stdout_limit: 1 << 20, # stdout capture capacity in bytes
|
|
158
|
+
stderr_limit: 1 << 16, # stderr capture capacity in bytes
|
|
159
|
+
epoch_interval_ms: 25, # epoch timer granularity
|
|
160
|
+
env: { "LANG" => "C" } # guest environment (empty by default)
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
lean = config.with(timeout_ms: 500, fuel: 5_000_000)
|
|
164
|
+
sandbox = SecurityBox::Sandbox.new(lean)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
### Result statuses
|
|
168
|
+
|
|
169
|
+
| Status | Meaning |
|
|
170
|
+
|---|---|
|
|
171
|
+
| `:ok` | guest code ran and returned a value |
|
|
172
|
+
| `:error` | guest code raised an exception (see `#error`) |
|
|
173
|
+
| `:timeout` | interrupted by the epoch deadline (wall clock) |
|
|
174
|
+
| `:fuel_exhausted` | CPU budget exhausted |
|
|
175
|
+
| `:memory_limit` | exceeded the store `memory_size` |
|
|
176
|
+
| `:sandbox_error` | sandbox failure (unexpected trap, missing/invalid envelope) |
|
|
177
|
+
|
|
178
|
+
Values are JSON-serialized; non-serializable objects are returned as their `inspect`
|
|
179
|
+
string.
|
|
180
|
+
|
|
181
|
+
## Isolation guarantees
|
|
182
|
+
|
|
183
|
+
| Probe inside the guest | Result |
|
|
184
|
+
|---|---|
|
|
185
|
+
| `File.write("/etc/passwd", ...)` | `Errno::ENOENT` (guest does not see the host FS) |
|
|
186
|
+
| `Dir["/*"]` | `[]` (empty root) |
|
|
187
|
+
| `system("ls")` / backticks / `IO.popen` | no-op stubs / `ArgumentError` (nothing executes) |
|
|
188
|
+
| `fork` | `NotImplementedError` |
|
|
189
|
+
| `Thread.new` | `NotImplementedError` (WASI p1 has no threads) |
|
|
190
|
+
| `require "socket"` | `LoadError` (no network) |
|
|
191
|
+
| `ENV` | `{}` (sanitized) |
|
|
192
|
+
| infinite loop | killed by epoch deadline or fuel budget |
|
|
193
|
+
|
|
194
|
+
Notes:
|
|
195
|
+
|
|
196
|
+
- The guest Ruby version is the one from ruby.wasm (4.0), not necessarily the host's.
|
|
197
|
+
- Concurrency: `invoke` holds the GVL, so executions serialize per host process. Scale
|
|
198
|
+
horizontally with multiple processes (e.g., Puma workers); a stuck guest still can't
|
|
199
|
+
hang the process thanks to the epoch deadline.
|
|
200
|
+
|
|
201
|
+
## Running the tests
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
bundle exec rspec spec/
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
The integration suite runs against the real ruby.wasm image. If the image at
|
|
208
|
+
`lib/security_box/assets/security_box.wasm` is missing, the suite builds it
|
|
209
|
+
automatically before running (this may take a few minutes the first time).
|
|
210
|
+
|
|
211
|
+
## Releasing
|
|
212
|
+
|
|
213
|
+
1. Rebuild the image if needed: `bundle exec rake security_box:build_image`
|
|
214
|
+
(also runs automatically before `rake build`/`rake release`).
|
|
215
|
+
2. Verify it is fresh: `bundle exec rake security_box:verify_image`
|
|
216
|
+
3. Run the suite: `bundle exec rake spec`
|
|
217
|
+
4. Build and publish: `bundle exec rake release` (tags git and pushes the gem
|
|
218
|
+
to RubyGems.org)
|
|
219
|
+
|
|
220
|
+
## Learning spike
|
|
221
|
+
|
|
222
|
+
`bin/spike.rb` validates the feasibility questions (Q1–Q9) against the built image and
|
|
223
|
+
prints a timing report:
|
|
224
|
+
|
|
225
|
+
```bash
|
|
226
|
+
bundle exec ruby bin/spike.rb
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
## Documentation
|
|
230
|
+
|
|
231
|
+
- `docs/PLAN.md` — architecture, roadmap and threat model
|
|
232
|
+
- `docs/plan/stages/stage_1.md` — stage 1 findings and measured numbers
|
|
Binary file
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SecurityBox
|
|
4
|
+
# Immutable sandbox configuration. Use .build to create and #with to derive.
|
|
5
|
+
class Configuration
|
|
6
|
+
IMAGE_ENV_VAR = "SECURITY_BOX_IMAGE"
|
|
7
|
+
IMAGE_ASSET_RELATIVE = "assets/security_box.wasm"
|
|
8
|
+
IMAGE_DEV_RELATIVE = "../../build/security_box.wasm"
|
|
9
|
+
|
|
10
|
+
DEFAULTS = {
|
|
11
|
+
image_path: nil, # resolved dynamically (project's build/security_box.wasm)
|
|
12
|
+
fuel: 10_000_000_000,
|
|
13
|
+
timeout_ms: 2_000,
|
|
14
|
+
memory_size: 512 * 1024 * 1024,
|
|
15
|
+
stdout_limit: 1 << 20,
|
|
16
|
+
stderr_limit: 1 << 16,
|
|
17
|
+
epoch_interval_ms: 25,
|
|
18
|
+
env: {}.freeze
|
|
19
|
+
}.freeze
|
|
20
|
+
|
|
21
|
+
attr_reader :image_path, :fuel, :timeout_ms, :memory_size,
|
|
22
|
+
:stdout_limit, :stderr_limit, :epoch_interval_ms, :env
|
|
23
|
+
|
|
24
|
+
def self.build(**options)
|
|
25
|
+
new(**DEFAULTS.merge(options)).freeze
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def initialize(image_path: nil, fuel:, timeout_ms:, memory_size:,
|
|
29
|
+
stdout_limit:, stderr_limit:, epoch_interval_ms:, env:)
|
|
30
|
+
@image_path = image_path || default_image_path
|
|
31
|
+
@fuel = Integer(fuel)
|
|
32
|
+
@timeout_ms = Integer(timeout_ms)
|
|
33
|
+
@memory_size = Integer(memory_size)
|
|
34
|
+
@stdout_limit = Integer(stdout_limit)
|
|
35
|
+
@stderr_limit = Integer(stderr_limit)
|
|
36
|
+
@epoch_interval_ms = Integer(epoch_interval_ms)
|
|
37
|
+
@env = env.freeze
|
|
38
|
+
freeze
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def with(**changes)
|
|
42
|
+
self.class.build(**to_h.merge(changes))
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def to_h
|
|
46
|
+
{
|
|
47
|
+
image_path: @image_path,
|
|
48
|
+
fuel: @fuel,
|
|
49
|
+
timeout_ms: @timeout_ms,
|
|
50
|
+
memory_size: @memory_size,
|
|
51
|
+
stdout_limit: @stdout_limit,
|
|
52
|
+
stderr_limit: @stderr_limit,
|
|
53
|
+
epoch_interval_ms: @epoch_interval_ms,
|
|
54
|
+
env: @env
|
|
55
|
+
}
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
private
|
|
59
|
+
|
|
60
|
+
# Resolution order (first existing path wins):
|
|
61
|
+
# 1. SECURITY_BOX_IMAGE environment variable
|
|
62
|
+
# 2. the image packed inside this library (gem install or checkout)
|
|
63
|
+
# 3. legacy development output (build/security_box.wasm)
|
|
64
|
+
def default_image_path
|
|
65
|
+
candidates = [ENV[IMAGE_ENV_VAR],
|
|
66
|
+
File.expand_path(IMAGE_ASSET_RELATIVE, __dir__),
|
|
67
|
+
File.expand_path(IMAGE_DEV_RELATIVE, __dir__)].compact
|
|
68
|
+
path = candidates.find { |candidate| File.file?(candidate) }
|
|
69
|
+
return path if path
|
|
70
|
+
|
|
71
|
+
raise ImageMissing,
|
|
72
|
+
"Sandbox image not found. Tried: #{candidates.join(', ')}. " \
|
|
73
|
+
"Run `rake security_box:build_image`, set #{IMAGE_ENV_VAR}, " \
|
|
74
|
+
"or pass image_path in the configuration."
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
end
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# Guest entrypoint packed into the ruby.wasm image (/src/main.rb).
|
|
2
|
+
#
|
|
3
|
+
# Input: /work/code.rb (preferred) or ARGV[0].
|
|
4
|
+
# Result: /work/out.json (JSON envelope); fallback: sentinel line on stdout.
|
|
5
|
+
#
|
|
6
|
+
# NOTE (stage 1): the result channel is reliable against accidents, not against
|
|
7
|
+
# an active adversary (guest code can forge the envelope). Token mitigations and
|
|
8
|
+
# schema validation land in Stage 2.
|
|
9
|
+
require "json"
|
|
10
|
+
|
|
11
|
+
module SB
|
|
12
|
+
SENTINEL = "__SECURITY_BOX_RESULT__"
|
|
13
|
+
WORK_DIR = "/work"
|
|
14
|
+
|
|
15
|
+
module_function
|
|
16
|
+
|
|
17
|
+
def run
|
|
18
|
+
code = fetch_code
|
|
19
|
+
return fatal("no code provided") unless code
|
|
20
|
+
|
|
21
|
+
t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
22
|
+
out = evaluate(code)
|
|
23
|
+
out[:duration_ms] = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1000).round(2)
|
|
24
|
+
emit(out)
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def fetch_code
|
|
28
|
+
code_path = File.join(WORK_DIR, "code.rb")
|
|
29
|
+
return File.read(code_path) if File.exist?(code_path)
|
|
30
|
+
|
|
31
|
+
ARGV[0]
|
|
32
|
+
rescue StandardError, SystemCallError
|
|
33
|
+
ARGV[0]
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def evaluate(code)
|
|
37
|
+
{ ok: true, value: jsonable(eval(code, TOPLEVEL_BINDING, "sandbox")) } # rubocop:disable Security/Eval,Style/EvalWithLocation
|
|
38
|
+
rescue Exception => e # rubocop:disable Lint/RescueException
|
|
39
|
+
{ ok: false, value: nil, error: { "class" => e.class.name, "message" => e.message.to_s } }
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Values must survive JSON; the round-trip normalizes what the host will read.
|
|
43
|
+
def jsonable(value)
|
|
44
|
+
JSON.parse(JSON.generate(value))
|
|
45
|
+
rescue StandardError, TypeError
|
|
46
|
+
value.inspect
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# Preferred: /work/out.json. Fallback (no /work): sentinel on stdout.
|
|
50
|
+
def emit(out)
|
|
51
|
+
json = JSON.generate(out)
|
|
52
|
+
File.write(File.join(WORK_DIR, "out.json"), json)
|
|
53
|
+
rescue StandardError, SystemCallError
|
|
54
|
+
$stdout.puts "#{SENTINEL}:#{json}"
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def fatal(message)
|
|
58
|
+
emit({ ok: false, value: nil, error: { "class" => "SecurityBox::Guest", "message" => message } })
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
SB.run
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module SecurityBox
|
|
4
|
+
# Result of a sandbox execution. Possible statuses:
|
|
5
|
+
# :ok — guest code ran and returned a value
|
|
6
|
+
# :error — guest code raised an exception
|
|
7
|
+
# :timeout — interrupted by epoch (wall clock)
|
|
8
|
+
# :fuel_exhausted — CPU budget exhausted
|
|
9
|
+
# :memory_limit — exceeded the store memory_size
|
|
10
|
+
# :sandbox_error — sandbox failure (unexpected trap, missing/invalid envelope)
|
|
11
|
+
class Result
|
|
12
|
+
attr_reader :status, :value, :error, :stdout, :stderr,
|
|
13
|
+
:fuel_used, :duration_ms, :guest_duration_ms
|
|
14
|
+
|
|
15
|
+
def initialize(status:, value: nil, error: nil, stdout: "", stderr: "",
|
|
16
|
+
fuel_used: nil, duration_ms: nil, guest_duration_ms: nil)
|
|
17
|
+
@status = status
|
|
18
|
+
@value = value
|
|
19
|
+
@error = error
|
|
20
|
+
@stdout = stdout
|
|
21
|
+
@stderr = stderr
|
|
22
|
+
@fuel_used = fuel_used
|
|
23
|
+
@duration_ms = duration_ms
|
|
24
|
+
@guest_duration_ms = guest_duration_ms
|
|
25
|
+
freeze
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def ok?
|
|
29
|
+
@status == :ok
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def to_h
|
|
33
|
+
{
|
|
34
|
+
status: @status,
|
|
35
|
+
value: @value,
|
|
36
|
+
error: @error,
|
|
37
|
+
stdout: @stdout,
|
|
38
|
+
stderr: @stderr,
|
|
39
|
+
fuel_used: @fuel_used,
|
|
40
|
+
duration_ms: @duration_ms,
|
|
41
|
+
guest_duration_ms: @guest_duration_ms
|
|
42
|
+
}
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "wasmtime"
|
|
4
|
+
|
|
5
|
+
module SecurityBox
|
|
6
|
+
# Registry of heavyweight artifacts shared across sandboxes:
|
|
7
|
+
# - Engine (one per runtime configuration; owns the epoch timer)
|
|
8
|
+
# - Compiled Module (one per engine+image)
|
|
9
|
+
#
|
|
10
|
+
# Module compilation is slow (~15s the first time per process); the disk cache
|
|
11
|
+
# (Module#serialize) lands in Stage 2.
|
|
12
|
+
module Runtime
|
|
13
|
+
MUTEX = Mutex.new
|
|
14
|
+
|
|
15
|
+
@engines = {}
|
|
16
|
+
@modules = {}
|
|
17
|
+
|
|
18
|
+
class << self
|
|
19
|
+
def engine(epoch_interval_ms:)
|
|
20
|
+
MUTEX.synchronize do
|
|
21
|
+
@engines[epoch_interval_ms] ||= build_engine(epoch_interval_ms)
|
|
22
|
+
end
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def module_for(engine, image_path)
|
|
26
|
+
MUTEX.synchronize do
|
|
27
|
+
@modules[[engine.object_id, image_path]] ||=
|
|
28
|
+
Wasmtime::Module.from_file(engine, image_path)
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
def clear!
|
|
33
|
+
MUTEX.synchronize do
|
|
34
|
+
@engines.clear
|
|
35
|
+
@modules.clear
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
private
|
|
40
|
+
|
|
41
|
+
def build_engine(epoch_interval_ms)
|
|
42
|
+
engine = Wasmtime::Engine.new(consume_fuel: true, epoch_interruption: true)
|
|
43
|
+
if engine.respond_to?(:start_epoch_interval)
|
|
44
|
+
engine.start_epoch_interval(epoch_interval_ms)
|
|
45
|
+
else
|
|
46
|
+
timer = Thread.new do
|
|
47
|
+
loop do
|
|
48
|
+
sleep(epoch_interval_ms / 1000.0)
|
|
49
|
+
engine.increment_epoch
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
timer.name = "security_box-epoch-timer"
|
|
53
|
+
end
|
|
54
|
+
engine
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
end
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "securerandom"
|
|
5
|
+
require "tmpdir"
|
|
6
|
+
|
|
7
|
+
module SecurityBox
|
|
8
|
+
# :oneshot mode sandbox — one wasm instance per #eval.
|
|
9
|
+
#
|
|
10
|
+
# Flow:
|
|
11
|
+
# 1. exclusive tmpdir mounted as /work (read-write)
|
|
12
|
+
# 2. user code written to /work/code.rb
|
|
13
|
+
# 3. guest (/src/main.rb) evaluates it and writes /work/out.json
|
|
14
|
+
# 4. host reads the envelope and returns a Result
|
|
15
|
+
class Sandbox
|
|
16
|
+
GUEST_ENTRYPOINT = "/src/main.rb"
|
|
17
|
+
RESULT_FILE = "out.json"
|
|
18
|
+
CODE_FILE = "code.rb"
|
|
19
|
+
|
|
20
|
+
def initialize(configuration = Configuration.build)
|
|
21
|
+
@config = configuration
|
|
22
|
+
@engine = Runtime.engine(epoch_interval_ms: @config.epoch_interval_ms)
|
|
23
|
+
@module = Runtime.module_for(@engine, @config.image_path)
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# Runs `code` in the sandbox and returns a Result.
|
|
27
|
+
# Per-call options (derived from the configuration without mutating it):
|
|
28
|
+
# timeout_ms:, fuel:, memory_size:, stdout_limit:, stderr_limit:
|
|
29
|
+
def eval(code, **overrides)
|
|
30
|
+
raise ArgumentError, "code is required" if code.nil? || code.empty?
|
|
31
|
+
|
|
32
|
+
config = overrides.empty? ? @config : @config.with(**overrides)
|
|
33
|
+
stdout = +""
|
|
34
|
+
stderr = +""
|
|
35
|
+
t0 = monotonic_ms
|
|
36
|
+
|
|
37
|
+
Dir.mktmpdir("security_box") do |workdir|
|
|
38
|
+
File.write(File.join(workdir, CODE_FILE), code)
|
|
39
|
+
envelope = nil
|
|
40
|
+
status = nil
|
|
41
|
+
fuel_used = nil
|
|
42
|
+
|
|
43
|
+
store = Wasmtime::Store.new(
|
|
44
|
+
@engine,
|
|
45
|
+
wasi_p1_config: build_wasi(workdir, stdout, stderr, config),
|
|
46
|
+
limits: { memory_size: config.memory_size }
|
|
47
|
+
)
|
|
48
|
+
begin
|
|
49
|
+
store.set_fuel(config.fuel)
|
|
50
|
+
instance = build_linker.instantiate(store, @module)
|
|
51
|
+
store.set_epoch_deadline(epoch_ticks(config))
|
|
52
|
+
status = invoke_guest(instance, store)
|
|
53
|
+
fuel_used = config.fuel - store.get_fuel
|
|
54
|
+
envelope = read_envelope(workdir)
|
|
55
|
+
ensure
|
|
56
|
+
store.close
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
build_result(status, envelope, stdout, stderr, fuel_used, monotonic_ms - t0)
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
private
|
|
64
|
+
|
|
65
|
+
def build_wasi(workdir, stdout, stderr, config)
|
|
66
|
+
Wasmtime::WasiConfig.new
|
|
67
|
+
.set_stdin_string("")
|
|
68
|
+
.set_stdout_buffer(stdout, config.stdout_limit)
|
|
69
|
+
.set_stderr_buffer(stderr, config.stderr_limit)
|
|
70
|
+
.set_argv(["ruby", GUEST_ENTRYPOINT])
|
|
71
|
+
.set_env(config.env)
|
|
72
|
+
.set_mapped_directory(workdir, "/work", :read_write)
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def build_linker
|
|
76
|
+
@linker ||= Wasmtime::Linker.new(@engine).tap do |linker|
|
|
77
|
+
Wasmtime::WASI::P1.add_to_linker_sync(linker)
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def epoch_ticks(config)
|
|
82
|
+
[config.timeout_ms / config.epoch_interval_ms + 1, 1].max
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def invoke_guest(instance, store)
|
|
86
|
+
instance.invoke("_start")
|
|
87
|
+
:ok
|
|
88
|
+
rescue Wasmtime::WasiExit => e
|
|
89
|
+
handle_wasi_exit(e, store)
|
|
90
|
+
rescue Wasmtime::Trap => e
|
|
91
|
+
map_trap(e, store)
|
|
92
|
+
rescue Wasmtime::Error
|
|
93
|
+
# Unexpected runtime error (non-trap): treated as a sandbox failure.
|
|
94
|
+
:sandbox_error
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def handle_wasi_exit(exit_error, store)
|
|
98
|
+
# The guest rescues SystemExit; a WasiExit here means exit! or a guest crash
|
|
99
|
+
# before the envelope was written.
|
|
100
|
+
store.linear_memory_limit_hit? ? :memory_limit : :sandbox_error
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def map_trap(trap, store)
|
|
104
|
+
case trap.code
|
|
105
|
+
when :interrupt then :timeout
|
|
106
|
+
when :out_of_fuel then :fuel_exhausted
|
|
107
|
+
when :memory_out_of_bounds then :memory_limit
|
|
108
|
+
else
|
|
109
|
+
store.linear_memory_limit_hit? ? :memory_limit : :sandbox_error
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def read_envelope(workdir)
|
|
114
|
+
path = File.join(workdir, RESULT_FILE)
|
|
115
|
+
return nil unless File.exist?(path)
|
|
116
|
+
|
|
117
|
+
JSON.parse(File.read(path))
|
|
118
|
+
rescue JSON::ParserError
|
|
119
|
+
nil
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
def build_result(status, envelope, stdout, stderr, fuel_used, duration_ms)
|
|
123
|
+
if envelope.nil?
|
|
124
|
+
status = :sandbox_error if status == :ok
|
|
125
|
+
return Result.new(
|
|
126
|
+
status: status, stdout: stdout, stderr: stderr,
|
|
127
|
+
fuel_used: fuel_used, duration_ms: duration_ms
|
|
128
|
+
)
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
guest_error = envelope["error"]
|
|
132
|
+
if envelope["ok"]
|
|
133
|
+
Result.new(
|
|
134
|
+
status: status, value: envelope["value"], stdout: stdout, stderr: stderr,
|
|
135
|
+
fuel_used: fuel_used, duration_ms: duration_ms,
|
|
136
|
+
guest_duration_ms: envelope["duration_ms"]
|
|
137
|
+
)
|
|
138
|
+
else
|
|
139
|
+
Result.new(
|
|
140
|
+
status: :error, error: guest_error, stdout: stdout, stderr: stderr,
|
|
141
|
+
fuel_used: fuel_used, duration_ms: duration_ms,
|
|
142
|
+
guest_duration_ms: envelope["duration_ms"]
|
|
143
|
+
)
|
|
144
|
+
end
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def monotonic_ms
|
|
148
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC) * 1000
|
|
149
|
+
end
|
|
150
|
+
end
|
|
151
|
+
end
|
data/lib/security_box.rb
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "security_box/version"
|
|
4
|
+
require_relative "security_box/errors"
|
|
5
|
+
require_relative "security_box/configuration"
|
|
6
|
+
require_relative "security_box/result"
|
|
7
|
+
require_relative "security_box/runtime"
|
|
8
|
+
require_relative "security_box/sandbox"
|
|
9
|
+
|
|
10
|
+
module SecurityBox
|
|
11
|
+
# Convenience shortcut:
|
|
12
|
+
# SecurityBox.eval("1 + 1") # => Result
|
|
13
|
+
# SecurityBox.eval("1", fuel: 100) # per-call overrides
|
|
14
|
+
def self.eval(code, **overrides)
|
|
15
|
+
Sandbox.new.eval(code, **overrides)
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# Prepares the shared runtime artifacts (Engine + compiled Module) ahead of
|
|
19
|
+
# time so the first #eval skips the cold module compilation (~15s per
|
|
20
|
+
# process). #eval warms these caches lazily on first use, so calling
|
|
21
|
+
# warmup is a pure optimization: behavior and results are identical
|
|
22
|
+
# without it. Accepts the same options as Configuration.build (only
|
|
23
|
+
# image_path and epoch_interval_ms affect what gets warmed). Returns the
|
|
24
|
+
# warmed Sandbox; safe to call multiple times.
|
|
25
|
+
def self.warmup(**options)
|
|
26
|
+
Sandbox.new(Configuration.build(**options))
|
|
27
|
+
end
|
|
28
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: security_box
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Marcelo Junior
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies:
|
|
12
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: wasmtime
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
- - ">="
|
|
17
|
+
- !ruby/object:Gem::Version
|
|
18
|
+
version: '0'
|
|
19
|
+
type: :runtime
|
|
20
|
+
prerelease: false
|
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
22
|
+
requirements:
|
|
23
|
+
- - ">="
|
|
24
|
+
- !ruby/object:Gem::Version
|
|
25
|
+
version: '0'
|
|
26
|
+
description: SecurityBox runs untrusted Ruby code inside a ruby.wasm (wasm32-unknown-wasip1)
|
|
27
|
+
module via the wasmtime gem. The guest has no filesystem, network, processes, threads
|
|
28
|
+
or sockets, and the host enforces CPU (fuel), wall-clock, memory and output-size
|
|
29
|
+
limits, always receiving a structured Result back.
|
|
30
|
+
email:
|
|
31
|
+
- marcelo.jr63@gmail.com
|
|
32
|
+
executables: []
|
|
33
|
+
extensions: []
|
|
34
|
+
extra_rdoc_files: []
|
|
35
|
+
files:
|
|
36
|
+
- CHANGELOG.md
|
|
37
|
+
- LICENSE
|
|
38
|
+
- README.md
|
|
39
|
+
- lib/security_box.rb
|
|
40
|
+
- lib/security_box/assets/security_box.wasm
|
|
41
|
+
- lib/security_box/configuration.rb
|
|
42
|
+
- lib/security_box/errors.rb
|
|
43
|
+
- lib/security_box/guest/main.rb
|
|
44
|
+
- lib/security_box/result.rb
|
|
45
|
+
- lib/security_box/runtime.rb
|
|
46
|
+
- lib/security_box/sandbox.rb
|
|
47
|
+
- lib/security_box/version.rb
|
|
48
|
+
homepage: https://github.com/juneira/security_box
|
|
49
|
+
licenses:
|
|
50
|
+
- MIT
|
|
51
|
+
metadata:
|
|
52
|
+
homepage_uri: https://github.com/juneira/security_box
|
|
53
|
+
source_code_uri: https://github.com/juneira/security_box
|
|
54
|
+
changelog_uri: https://github.com/juneira/security_box/blob/main/CHANGELOG.md
|
|
55
|
+
rubygems_mfa_required: 'true'
|
|
56
|
+
rdoc_options: []
|
|
57
|
+
require_paths:
|
|
58
|
+
- lib
|
|
59
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
60
|
+
requirements:
|
|
61
|
+
- - ">="
|
|
62
|
+
- !ruby/object:Gem::Version
|
|
63
|
+
version: '4.0'
|
|
64
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
65
|
+
requirements:
|
|
66
|
+
- - ">="
|
|
67
|
+
- !ruby/object:Gem::Version
|
|
68
|
+
version: '0'
|
|
69
|
+
requirements: []
|
|
70
|
+
rubygems_version: 4.0.10
|
|
71
|
+
specification_version: 4
|
|
72
|
+
summary: Run untrusted Ruby code inside a WebAssembly sandbox
|
|
73
|
+
test_files: []
|