Repository: phylum-dev/birdcage
Branch: main
Commit: d0c625188385
Files: 45
Total size: 159.0 KB
Directory structure:
gitextract_c3jrejhf/
├── .github/
│ ├── PULL_REQUEST_TEMPLATE.md
│ ├── dependabot.yml
│ └── workflows/
│ └── test.yml
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── Cargo.toml
├── LICENSE
├── README.md
├── SECURITY.md
├── examples/
│ └── sandbox.rs
├── integration/
│ ├── canonicalize.rs
│ ├── command_io.rs
│ ├── consistent_id_mappings.rs
│ ├── delete_before_lockdown.rs
│ ├── env.rs
│ ├── exec.rs
│ ├── exec_symlinked_dir.rs
│ ├── exec_symlinked_dirs_exec.rs
│ ├── exec_symlinked_file.rs
│ ├── fs.rs
│ ├── fs_broken_symlink.rs
│ ├── fs_null.rs
│ ├── fs_readonly.rs
│ ├── fs_restrict_child.rs
│ ├── fs_symlink.rs
│ ├── fs_symlink_dir.rs
│ ├── fs_symlink_dir_separate_perms.rs
│ ├── fs_write_also_read.rs
│ ├── full_env.rs
│ ├── full_sandbox.rs
│ ├── harness.rs
│ ├── missing_exception.rs
│ ├── net.rs
│ └── seccomp.rs
├── rustfmt.toml
└── src/
├── error.rs
├── lib.rs
├── linux/
│ ├── mod.rs
│ ├── namespaces.rs
│ └── seccomp.rs
├── macos.rs
└── process/
├── linux.rs
├── macos.rs
└── mod.rs
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
<!--
Before submitting a PR:
1. Link the associated issue (i.e., `closes #<issueNum>` in description)
2. Ensure that you have met the expected acceptance criteria
3. Ensure that you have created sufficient tests
4. Ensure that you have updated all affected documentation
-->
================================================
FILE: .github/dependabot.yml
================================================
---
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: weekly
================================================
FILE: .github/workflows/test.yml
================================================
name: Test
on:
# Allow running this workflow manually from the Actions tab
workflow_dispatch:
pull_request:
push:
branches:
- main
tags:
- '*'
# Run weekly on the default branch to make sure it always builds with the latest rust release
schedule:
- cron: '30 5 * * 1'
jobs:
test-matrix:
strategy:
fail-fast: false
matrix:
os:
- ubuntu-latest
- macos-latest
runs-on: ${{ matrix.os }}
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Install Rust toolchain
run: |
curl --proto '=https' --tlsv1.2 -sSfL https://sh.rustup.rs \
| sh -s -- -y --default-toolchain stable --profile minimal -c clippy
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
- name: Test Stable
run: |
# On Ubuntu use busybox to bypass user namespace restrictions.
if command -v busybox; then
busybox sh -c "cargo +stable test"
else
cargo +stable test
fi
- name: Test Oldstable
run: |
oldstable=$(cat Cargo.toml | grep rust-version | sed 's/.*"\(.*\)".*/\1/')
rustup toolchain install --profile minimal $oldstable
# On Ubuntu use busybox to bypass user namespace restrictions.
if command -v busybox; then
busybox sh -c "cargo +$oldstable test"
else
cargo "+$oldstable" test
fi
- name: Clippy
run: cargo +stable clippy
- name: Rustfmt
run: |
rustup toolchain install nightly -c rustfmt
cargo +nightly fmt -- --check
# This job reports the results of the test jobs above and is used
# to enforce status checks in the repo settings without needing
# to update those settings every time the test jobs are updated.
test-rollup:
name: Test rollup
runs-on: ubuntu-latest
if: always()
needs: test-matrix
steps:
- name: Check for test jobs failure or cancellation
if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')
run: exit 1
================================================
FILE: .gitignore
================================================
/target
/Cargo.lock
================================================
FILE: CHANGELOG.md
================================================
# Changelog
Notable changes to Birdcage are documented in this file.
The sections should follow the order `Packaging`, `Added`, `Changed`, `Fixed` and `Removed`.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.8.1] - 2024-04-19
### Fixed
- Conversion from Birdcage's to STD's `Command` inheriting all STDIO
## [0.8.0] - 2024-04-19
### Changed
- `Sandbox::spawn` now takes a `birdcage::process::Command`
### Fixed
- (Linux) Sandboxed process not killed when parent is terminated with a signal
## [0.7.1] - 2024-02-07
### Changed
- (Linux) Improved error message with unsupported Kernel versions
## [0.7.0] - 2023-11-30
### Added
- (Linux) PID namespace support
### Fixed
- (Linux) Sandbox lockdown failing when deleting file after adding exception
- (Linux) Environment variables accessible through procfs interface
## [0.6.0] - 2023-11-16
### Fixed
- (Linux) Sandbox exceptions for symbolic links
- (macOS) Modifying exceptions for paths affected by existing exceptions
- (Linux) Symlink/Canonical path's exceptions overriding each other
## [v0.5.0] - 2023-10-13
### Changed
- (Linux) Report invalid paths when adding exceptions
- `Exception::Write` changed to `Exception::WriteAndRead`
### Fixed
- (Linux) Root filesystem exceptions failing sandbox creation
- (Linux) Sandbox not enforcing readonly/noexec restrictions
- (Linux) Exceptions for special files (i.e. /dev/null)
## [0.4.0] - 2023-10-09
### Added
- (Linux) Seccomp system call filter
### Changed
- (Linux) Minimum Kernel version reduced to 3.8
- The sandboxing process now must be single-threaded
### Fixed
- (Linux) Abstract namespace isolation
- (Linux) Socket and pipe isolation
### Contributors
We'd like to thank [@bjorn3](https://github.com/bjorn3) for disclosing an issue
with socket isolation.
## [0.3.1] - 2023-08-31
### Fixed
- Local sockets denied by network sandbox on Linux
## [0.3.0] - 2023-08-31
### Changed
- Linux seccomp network filtering now uses a whitelist instead of a blacklist
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall
community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of
any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address,
without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
[engineering@phylum.io](mailto:engineering@phylum.io).
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of
actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or permanent
ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the
community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
[https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
================================================
FILE: Cargo.toml
================================================
[package]
name = "birdcage"
version = "0.8.1"
description = "Cross-platform embeddable sandbox"
authors = ["Phylum, Inc. <engineering@phylum.io>"]
repository = "https://github.com/phylum-dev/birdcage"
documentation = "https://docs.rs/birdcage"
rust-version = "1.70.0"
license = "GPL-3.0-or-later"
edition = "2021"
[[test]]
name = "harness"
path = "integration/harness.rs"
harness = false
[[test]]
name = "command_io"
path = "integration/command_io.rs"
harness = false
[target.'cfg(target_os = "linux")'.dependencies]
libc = "0.2.132"
log = "0.4.20"
rustix = { version = "0.38.31", features = ["pipe", "stdio", "thread", "process", "fs"] }
seccompiler = "0.3.0"
[dev-dependencies]
clap = { version = "3.2.17", features = ["derive"] }
serde_json = "1.0.108"
serde = { version = "1.0.193", features = ["derive"] }
tempfile = "3.3.0"
[dependencies]
bitflags = "2.4.0"
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and
other kinds of works.
The licenses for most software and other practical works are designed to take
away your freedom to share and change the works. By contrast, the GNU General
Public License is intended to guarantee your freedom to share and change all
versions of a program--to make sure it remains free software for all its users.
We, the Free Software Foundation, use the GNU General Public License for most
of our software; it applies also to any other work released this way by its
authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our
General Public Licenses are designed to make sure that you have the freedom
to distribute copies of free software (and charge for them if you wish), that
you receive source code or can get it if you want it, that you can change
the software or use pieces of it in new free programs, and that you know you
can do these things.
To protect your rights, we need to prevent others from denying you these rights
or asking you to surrender the rights. Therefore, you have certain responsibilities
if you distribute copies of the software, or if you modify it: responsibilities
to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or
for a fee, you must pass on to the recipients the same freedoms that you received.
You must make sure that they, too, receive or can get the source code. And
you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert
copyright on the software, and (2) offer you this License giving you legal
permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that
there is no warranty for this free software. For both users' and authors'
sake, the GPL requires that modified versions be marked as changed, so that
their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified
versions of the software inside them, although the manufacturer can do so.
This is fundamentally incompatible with the aim of protecting users' freedom
to change the software. The systematic pattern of such abuse occurs in the
area of products for individuals to use, which is precisely where it is most
unacceptable. Therefore, we have designed this version of the GPL to prohibit
the practice for those products. If such problems arise substantially in other
domains, we stand ready to extend this provision to those domains in future
versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States
should not allow patents to restrict development and use of software on general-purpose
computers, but in those that do, we wish to avoid the special danger that
patents applied to a free program could make it effectively proprietary. To
prevent this, the GPL assures that patents cannot be used to render the program
non-free.
The precise terms and conditions for copying, distribution and modification
follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works,
such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License.
Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals
or organizations.
To “modify” a work means to copy from or adapt all or part of the work in
a fashion requiring copyright permission, other than the making of an exact
copy. The resulting work is called a “modified version” of the earlier work
or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the
Program.
To “propagate” a work means to do anything with it that, without permission,
would make you directly or secondarily liable for infringement under applicable
copyright law, except executing it on a computer or modifying a private copy.
Propagation includes copying, distribution (with or without modification),
making available to the public, and in some countries other activities as
well.
To “convey” a work means any kind of propagation that enables other parties
to make or receive copies. Mere interaction with a user through a computer
network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the
extent that it includes a convenient and prominently visible feature that
(1) displays an appropriate copyright notice, and (2) tells the user that
there is no warranty for the work (except to the extent that warranties are
provided), that licensees may convey the work under this License, and how
to view a copy of this License. If the interface presents a list of user commands
or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making
modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard
defined by a recognized standards body, or, in the case of interfaces specified
for a particular programming language, one that is widely used among developers
working in that language.
The “System Libraries” of an executable work include anything, other than
the work as a whole, that (a) is included in the normal form of packaging
a Major Component, but which is not part of that Major Component, and (b)
serves only to enable use of the work with that Major Component, or to implement
a Standard Interface for which an implementation is available to the public
in source code form. A “Major Component”, in this context, means a major essential
component (kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to produce
the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source
code needed to generate, install, and (for an executable work) run the object
code and to modify the work, including scripts to control those activities.
However, it does not include the work's System Libraries, or general-purpose
tools or generally available free programs which are used unmodified in performing
those activities but which are not part of the work. For example, Corresponding
Source includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically linked
subprograms that the work is specifically designed to require, such as by
intimate data communication or control flow between those subprograms and
other parts of the work.
The Corresponding Source need not include anything that users can regenerate
automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright
on the Program, and are irrevocable provided the stated conditions are met.
This License explicitly affirms your unlimited permission to run the unmodified
Program. The output from running a covered work is covered by this License
only if the output, given its content, constitutes a covered work. This License
acknowledges your rights of fair use or other equivalent, as provided by copyright
law.
You may make, run and propagate covered works that you do not convey, without
conditions so long as your license otherwise remains in force. You may convey
covered works to others for the sole purpose of having them make modifications
exclusively for you, or provide you with facilities for running those works,
provided that you comply with the terms of this License in conveying all material
for which you do not control copyright. Those thus making or running the covered
works for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of your copyrighted
material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure
under any applicable law fulfilling obligations under article 11 of the WIPO
copyright treaty adopted on 20 December 1996, or similar laws prohibiting
or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention
of technological measures to the extent such circumvention is effected by
exercising rights under this License with respect to the covered work, and
you disclaim any intention to limit operation or modification of the work
as a means of enforcing, against the work's users, your or third parties'
legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive
it, in any medium, provided that you conspicuously and appropriately publish
on each copy an appropriate copyright notice; keep intact all notices stating
that this License and any non-permissive terms added in accord with section
7 apply to the code; keep intact all notices of the absence of any warranty;
and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you
may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce
it from the Program, in the form of source code under the terms of section
4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and
giving a relevant date.
b) The work must carry prominent notices stating that it is released under
this License and any conditions added under section 7. This requirement modifies
the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone
who comes into possession of a copy. This License will therefore apply, along
with any applicable section 7 additional terms, to the whole of the work,
and all its parts, regardless of how they are packaged. This License gives
no permission to license the work in any other way, but it does not invalidate
such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate
Legal Notices; however, if the Program has interactive interfaces that do
not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works,
which are not by their nature extensions of the covered work, and which are
not combined with it such as to form a larger program, in or on a volume of
a storage or distribution medium, is called an “aggregate” if the compilation
and its resulting copyright are not used to limit the access or legal rights
of the compilation's users beyond what the individual works permit. Inclusion
of a covered work in an aggregate does not cause this License to apply to
the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections
4 and 5, provided that you also convey the machine-readable Corresponding
Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including
a physical distribution medium), accompanied by the Corresponding Source fixed
on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including
a physical distribution medium), accompanied by a written offer, valid for
at least three years and valid for as long as you offer spare parts or customer
support for that product model, to give anyone who possesses the object code
either (1) a copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical medium customarily
used for software interchange, for a price no more than your reasonable cost
of physically performing this conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written
offer to provide the Corresponding Source. This alternative is allowed only
occasionally and noncommercially, and only if you received the object code
with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis
or for a charge), and offer equivalent access to the Corresponding Source
in the same way through the same place at no further charge. You need not
require recipients to copy the Corresponding Source along with the object
code. If the place to copy the object code is a network server, the Corresponding
Source may be on a different server (operated by you or a third party) that
supports equivalent copying facilities, provided you maintain clear directions
next to the object code saying where to find the Corresponding Source. Regardless
of what server hosts the Corresponding Source, you remain obligated to ensure
that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform
other peers where the object code and Corresponding Source of the work are
being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from
the Corresponding Source as a System Library, need not be included in conveying
the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible
personal property which is normally used for personal, family, or household
purposes, or (2) anything designed or sold for incorporation into a dwelling.
In determining whether a product is a consumer product, doubtful cases shall
be resolved in favor of coverage. For a particular product received by a particular
user, “normally used” refers to a typical or common use of that class of product,
regardless of the status of the particular user or of the way in which the
particular user actually uses, or expects or is expected to use, the product.
A product is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent the
only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures,
authorization keys, or other information required to install and execute modified
versions of a covered work in that User Product from a modified version of
its Corresponding Source. The information must suffice to ensure that the
continued functioning of the modified object code is in no case prevented
or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically
for use in, a User Product, and the conveying occurs as part of a transaction
in which the right of possession and use of the User Product is transferred
to the recipient in perpetuity or for a fixed term (regardless of how the
transaction is characterized), the Corresponding Source conveyed under this
section must be accompanied by the Installation Information. But this requirement
does not apply if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has been installed
in ROM).
The requirement to provide Installation Information does not include a requirement
to continue to provide support service, warranty, or updates for a work that
has been modified or installed by the recipient, or for the User Product in
which it has been modified or installed. Access to a network may be denied
when the modification itself materially and adversely affects the operation
of the network or violates the rules and protocols for communication across
the network.
Corresponding Source conveyed, and Installation Information provided, in accord
with this section must be in a format that is publicly documented (and with
an implementation available to the public in source code form), and must require
no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License
by making exceptions from one or more of its conditions. Additional permissions
that are applicable to the entire Program shall be treated as though they
were included in this License, to the extent that they are valid under applicable
law. If additional permissions apply only to part of the Program, that part
may be used separately under those permissions, but the entire Program remains
governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any
additional permissions from that copy, or from any part of it. (Additional
permissions may be written to require their own removal in certain cases when
you modify the work.) You may place additional permissions on material, added
by you to a covered work, for which you have or can give appropriate copyright
permission.
Notwithstanding any other provision of this License, for material you add
to a covered work, you may (if authorized by the copyright holders of that
material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of
sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author
attributions in that material or in the Appropriate Legal Notices displayed
by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring
that modified versions of such material be marked in reasonable ways as different
from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors
of the material; or
e) Declining to grant rights under trademark law for use of some trade names,
trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by
anyone who conveys the material (or modified versions of it) with contractual
assumptions of liability to the recipient, for any liability that these contractual
assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions”
within the meaning of section 10. If the Program as you received it, or any
part of it, contains a notice stating that it is governed by this License
along with a term that is a further restriction, you may remove that term.
If a license document contains a further restriction but permits relicensing
or conveying under this License, you may add to a covered work material governed
by the terms of that license document, provided that the further restriction
does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place,
in the relevant source files, a statement of the additional terms that apply
to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form
of a separately written license, or stated as exceptions; the above requirements
apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided
under this License. Any attempt otherwise to propagate or modify it is void,
and will automatically terminate your rights under this License (including
any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from
a particular copyright holder is reinstated (a) provisionally, unless and
until the copyright holder explicitly and finally terminates your license,
and (b) permanently, if the copyright holder fails to notify you of the violation
by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently
if the copyright holder notifies you of the violation by some reasonable means,
this is the first time you have received notice of violation of this License
(for any work) from that copyright holder, and you cure the violation prior
to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses
of parties who have received copies or rights from you under this License.
If your rights have been terminated and not permanently reinstated, you do
not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy
of the Program. Ancillary propagation of a covered work occurring solely as
a consequence of using peer-to-peer transmission to receive a copy likewise
does not require acceptance. However, nothing other than this License grants
you permission to propagate or modify any covered work. These actions infringe
copyright if you do not accept this License. Therefore, by modifying or propagating
a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives
a license from the original licensors, to run, modify and propagate that work,
subject to this License. You are not responsible for enforcing compliance
by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization,
or substantially all assets of one, or subdividing an organization, or merging
organizations. If propagation of a covered work results from an entity transaction,
each party to that transaction who receives a copy of the work also receives
whatever licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the Corresponding
Source of the work from the predecessor in interest, if the predecessor has
it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights
granted or affirmed under this License. For example, you may not impose a
license fee, royalty, or other charge for exercise of rights granted under
this License, and you may not initiate litigation (including a cross-claim
or counterclaim in a lawsuit) alleging that any patent claim is infringed
by making, using, selling, offering for sale, or importing the Program or
any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License
of the Program or a work on which the Program is based. The work thus licensed
is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled
by the contributor, whether already acquired or hereafter acquired, that would
be infringed by some manner, permitted by this License, of making, using,
or selling its contributor version, but do not include claims that would be
infringed only as a consequence of further modification of the contributor
version. For purposes of this definition, “control” includes the right to
grant patent sublicenses in a manner consistent with the requirements of this
License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent
license under the contributor's essential patent claims, to make, use, sell,
offer for sale, import and otherwise run, modify and propagate the contents
of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement
or commitment, however denominated, not to enforce a patent (such as an express
permission to practice a patent or covenant not to sue for patent infringement).
To “grant” such a patent license to a party means to make such an agreement
or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the
Corresponding Source of the work is not available for anyone to copy, free
of charge and under the terms of this License, through a publicly available
network server or other readily accessible means, then you must either (1)
cause the Corresponding Source to be so available, or (2) arrange to deprive
yourself of the benefit of the patent license for this particular work, or
(3) arrange, in a manner consistent with the requirements of this License,
to extend the patent license to downstream recipients. “Knowingly relying”
means you have actual knowledge that, but for the patent license, your conveying
the covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that country
that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement,
you convey, or propagate by procuring conveyance of, a covered work, and grant
a patent license to some of the parties receiving the covered work authorizing
them to use, propagate, modify or convey a specific copy of the covered work,
then the patent license you grant is automatically extended to all recipients
of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope
of its coverage, prohibits the exercise of, or is conditioned on the non-exercise
of one or more of the rights that are specifically granted under this License.
You may not convey a covered work if you are a party to an arrangement with
a third party that is in the business of distributing software, under which
you make payment to the third party based on the extent of your activity of
conveying the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by you
(or copies made from those copies), or (b) primarily for and in connection
with specific products or compilations that contain the covered work, unless
you entered into that arrangement, or that patent license was granted, prior
to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied
license or other defenses to infringement that may otherwise be available
to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise)
that contradict the conditions of this License, they do not excuse you from
the conditions of this License. If you cannot convey a covered work so as
to satisfy simultaneously your obligations under this License and any other
pertinent obligations, then as a consequence you may not convey it at all.
For example, if you agree to terms that obligate you to collect a royalty
for further conveying from those to whom you convey the Program, the only
way you could satisfy both those terms and this License would be to refrain
entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to
link or combine any covered work with a work licensed under version 3 of the
GNU Affero General Public License into a single combined work, and to convey
the resulting work. The terms of this License will continue to apply to the
part which is the covered work, but the special requirements of the GNU Affero
General Public License, section 13, concerning interaction through a network
will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the
GNU General Public License from time to time. Such new versions will be similar
in spirit to the present version, but may differ in detail to address new
problems or concerns.
Each version is given a distinguishing version number. If the Program specifies
that a certain numbered version of the GNU General Public License “or any
later version” applies to it, you have the option of following the terms and
conditions either of that numbered version or of any later version published
by the Free Software Foundation. If the Program does not specify a version
number of the GNU General Public License, you may choose any version ever
published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of
the GNU General Public License can be used, that proxy's public statement
of acceptance of a version permanently authorizes you to choose that version
for the Program.
Later license versions may give you additional or different permissions. However,
no additional obligations are imposed on any author or copyright holder as
a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM
PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL
ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM
AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO
USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE
PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot
be given local legal effect according to their terms, reviewing courts shall
apply local law that most closely approximates an absolute waiver of all civil
liability in connection with the Program, unless a warranty or assumption
of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible
use to the public, the best way to achieve this is to make it free software
which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach
them to the start of each source file to most effectively state the exclusion
of warranty; and each file should have at least the “copyright” line and a
pointer to where the full notice is found.
Birdcage, cross-platform embeddable sandbox
Copyright (C) 2022 Phylum, Inc.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like
this when it starts in an interactive mode:
Birdcage Copyright (C) 2022 Phylum, Inc.
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain
conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands might
be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a “copyright disclaimer” for the program, if necessary. For
more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General Public
License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
================================================
FILE: README.md
================================================
# Birdcage
<div align="center">
[][license]
[][issues]
[][CoC]
[](https://crates.io/crates/birdcage)
[](https://docs.rs/birdcage)
[license]: https://github.com/phylum-dev/birdcage/blob/main/LICENSE
[issues]: https://github.com/phylum-dev/birdcage/issues
[CoC]: https://github.com/phylum-dev/birdcage/blob/main/CODE_OF_CONDUCT.md
[][protection]
</div>
## About
Birdcage is a cross-platform embeddable sandboxing library allowing restrictions
to Filesystem and Network operations using native operating system APIs.
Birdcage was originally developed for use by the [Phylum CLI] as an extra layer
of [protection] against potentially malicious dependencies (see the [blog post]
for details). To better protect yourself from these security risks, [sign up
now]!
[phylum cli]: https://github.com/phylum-dev/cli
[protection]: https://www.phylum.io/defend-developers
[blog post]: https://blog.phylum.io/sandboxing-package-installations-arms-developers-with-defense-against-open-source-attacks-and-unintended-consequences/
[sign up now]: https://www.phylum.io/
Birdcage focuses **only** on Filesystem and Network operations. It **is not** a
complete sandbox preventing all side-effects or permanent damage. Applications
can still execute most system calls, which is especially dangerous when
execution is performed as root. Birdcage should be combined with other security
mechanisms, especially if you are executing known-malicious code.
## Example
An example for using Birdcage's API can be found in `./examples/sandbox`, which
runs an application with CLI-configurable restrictions applied.
Trying to run without any exceptions will produce an error:
```bash
$ cargo run --example sandbox -- echo "Hello, Sandbox\!"
Error: Os { code: 13, kind: PermissionDenied, message: "Permission denied" }
```
Running the same command with explicit permissions allows execution:
```bash
$ cargo run --example sandbox -- -e /usr/bin/echo -e /usr/lib echo "Hello, Sandbox\!"
Hello, Sandbox!
```
Check out `cargo run --example sandbox -- --help` for more information on how to
use the example.
## Supported Platforms
- Linux via [namespaces]
- macOS via `sandbox_init()` (aka Seatbelt)
[namespaces]: https://man7.org/linux/man-pages/man7/namespaces.7.html
================================================
FILE: SECURITY.md
================================================
# Security Policy
Phylum was founded by a team of security researchers at heart, and we take the security of our tooling seriously.
## Reporting a Vulnerability
We love coordinated disclosure!
Please email [security@phylum.io](mailto:security@phylum.io) to start a conversation!
We'll coordinate a secure communication mechanism first, then evaluate the reported issue(s)
and keep you apprised each step of the way.
================================================
FILE: examples/sandbox.rs
================================================
//! Sandbox arbitrary executables.
use std::error::Error;
use std::path::PathBuf;
use birdcage::process::Command;
use birdcage::{Birdcage, Exception, Sandbox};
use clap::{Parser, ValueHint};
#[derive(Parser)]
#[clap(author, about)]
struct Cli {
/// Allowed read paths.
#[clap(short = 'r', long, value_name = "PATH", value_hint = ValueHint::AnyPath)]
allow_read: Vec<PathBuf>,
/// Allowed write paths.
#[clap(short = 'w', long, value_name = "PATH", value_hint = ValueHint::AnyPath)]
allow_write: Vec<PathBuf>,
/// Allowed read and execute paths.
#[clap(short = 'e', long, value_name = "PATH", value_hint = ValueHint::AnyPath)]
allow_execute: Vec<PathBuf>,
/// Allowed environment variable access.
#[clap(long, value_name = "VAR")]
allow_env: Vec<String>,
/// Allow networking.
#[clap(short = 'n', long)]
allow_networking: bool,
/// Command to be executed in the sandbox.
cmd: String,
/// Arguments for the sandboxed command.
#[clap(allow_hyphen_values = true, multiple_values = true)]
args: Vec<String>,
}
fn main() -> Result<(), Box<dyn Error>> {
let cli = Cli::parse();
// Setup sandbox and its exceptions.
let mut birdcage = Birdcage::new();
for path in cli.allow_read {
birdcage.add_exception(Exception::Read(path))?;
}
for path in cli.allow_write {
birdcage.add_exception(Exception::WriteAndRead(path))?;
}
for path in cli.allow_execute {
birdcage.add_exception(Exception::ExecuteAndRead(path))?;
}
for var in cli.allow_env {
birdcage.add_exception(Exception::Environment(var))?;
}
if cli.allow_networking {
birdcage.add_exception(Exception::Networking)?;
}
// Activate sandbox.
let mut command = Command::new(cli.cmd);
command.args(&cli.args);
let mut child = birdcage.spawn(command)?;
// Wait for sandboxee to exit.
child.wait()?;
std::process::exit(0);
}
================================================
FILE: integration/canonicalize.rs
================================================
use std::fs;
use std::path::PathBuf;
use birdcage::{Birdcage, Exception, Sandbox};
use crate::TestSetup;
pub fn setup(_tempdir: PathBuf) -> TestSetup {
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::Read("./".into())).unwrap();
TestSetup { sandbox, data: String::new() }
}
pub fn validate(_data: String) {
// Check for success on reading the `Cargo.toml` file.
let file = fs::read_to_string("./Cargo.toml").unwrap();
assert!(file.contains("birdcage"));
}
================================================
FILE: integration/command_io.rs
================================================
use std::io::Write;
use std::os::unix::process::ExitStatusExt;
use birdcage::process::{Command, Stdio};
use birdcage::{Birdcage, Exception, Sandbox};
// macOs uses `std::process` and thus does not require explicit testing. This
// allows running multiple tests in the same process rather than having to add
// multiple integeration tests.
#[cfg(not(target_os = "linux"))]
fn main() {}
#[cfg(target_os = "linux")]
fn main() {
pipe_stdin_to_stdout();
exit_signal();
}
#[cfg(target_os = "linux")]
fn pipe_stdin_to_stdout() {
// Setup echo-back command.
let mut cmd = Command::new("cat");
cmd.stdin(Stdio::piped());
cmd.stdout(Stdio::piped());
// Spawn sandbox child.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::ExecuteAndRead("/".into())).unwrap();
sandbox.add_exception(Exception::WriteAndRead("/".into())).unwrap();
let mut child = sandbox.spawn(cmd).unwrap();
// Write test data to stdin.
let expected = b"test\n";
child.stdin.as_mut().unwrap().write_all(expected).unwrap();
// Read stdout.
let output = child.wait_with_output().unwrap();
assert_eq!(&output.stdout, expected);
}
#[cfg(target_os = "linux")]
fn exit_signal() {
// Setup echo-back command.
let cmd = Command::new("cat");
// Spawn sandbox child.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::ExecuteAndRead("/".into())).unwrap();
sandbox.add_exception(Exception::WriteAndRead("/".into())).unwrap();
let mut child = sandbox.spawn(cmd).unwrap();
// Kill the child.
child.kill().unwrap();
// Read stdout.
let status = child.wait().unwrap();
assert_eq!(status.signal(), Some(9));
}
================================================
FILE: integration/consistent_id_mappings.rs
================================================
use std::path::PathBuf;
use birdcage::{Birdcage, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
#[derive(Serialize, Deserialize)]
struct TestData {
uid: u32,
gid: u32,
euid: u32,
egid: u32,
}
pub fn setup(_tempdir: PathBuf) -> TestSetup {
let uid = unsafe { libc::getuid() };
let gid = unsafe { libc::getgid() };
let euid = unsafe { libc::geteuid() };
let egid = unsafe { libc::getegid() };
let sandbox = Birdcage::new();
// Serialize test data.
let data = TestData { uid, gid, euid, egid };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
assert_eq!(data.uid, unsafe { libc::getuid() });
assert_eq!(data.gid, unsafe { libc::getgid() });
assert_eq!(data.euid, unsafe { libc::geteuid() });
assert_eq!(data.egid, unsafe { libc::getegid() });
}
================================================
FILE: integration/delete_before_lockdown.rs
================================================
use std::path::PathBuf;
use birdcage::{Birdcage, Exception, Sandbox};
use tempfile::NamedTempFile;
use crate::TestSetup;
pub fn setup(_tempdir: PathBuf) -> TestSetup {
// Create temporary file.
let tempfile = NamedTempFile::new().unwrap();
// Setup sandbox exceptions.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::Read(tempfile.path().into())).unwrap();
tempfile.close().unwrap();
TestSetup { sandbox, data: String::new() }
}
pub fn validate(_data: String) {
// We just want to test sandbox creation worked.
}
================================================
FILE: integration/env.rs
================================================
use std::path::PathBuf;
use std::env;
use birdcage::{Birdcage, Exception, Sandbox};
use crate::TestSetup;
pub fn setup(_tempdir: PathBuf) -> TestSetup {
// Setup our environment variables
env::set_var("PUBLIC", "GOOD");
env::set_var("PRIVATE", "BAD");
// Activate our sandbox.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::Environment("PUBLIC".into())).unwrap();
TestSetup { sandbox, data: String::new() }
}
pub fn validate(_data: String) {
// Only the `PUBLIC` environment variable remains.
let env: Vec<_> = env::vars().collect();
assert_eq!(env, vec![("PUBLIC".into(), "GOOD".into())]);
}
================================================
FILE: integration/exec.rs
================================================
use std::path::PathBuf;
use std::fs;
use std::process::Command;
use birdcage::{Birdcage, Exception, Sandbox};
use crate::TestSetup;
pub fn setup(_tempdir: PathBuf) -> TestSetup {
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::ExecuteAndRead("/usr/bin/true".into())).unwrap();
TestSetup { sandbox, data: String::new() }
}
pub fn validate(_data: String) {
// Check for success when executing `true`.
let cmd = Command::new("/usr/bin/true").status().unwrap();
assert!(cmd.success());
// Check for success on reading the `true` file.
let cmd_file = fs::read("/usr/bin/true");
assert!(cmd_file.is_ok());
}
================================================
FILE: integration/exec_symlinked_dir.rs
================================================
use std::os::unix::fs as unixfs;
use std::path::PathBuf;
use std::process::Command;
use birdcage::{Birdcage, Exception, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
#[derive(Serialize, Deserialize)]
struct TestData {
symlink_dir: PathBuf,
}
pub fn setup(tempdir: PathBuf) -> TestSetup {
// Create symlinked executable dir.
let symlink_dir = tempdir.join("bin");
unixfs::symlink("/usr/bin", &symlink_dir).unwrap();
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::ExecuteAndRead(symlink_dir.clone())).unwrap();
// Serialize test data.
let data = TestData { symlink_dir };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
// Ensure symlinked dir's executable works.
let symlink_dir_exec = data.symlink_dir.join("true");
let cmd = Command::new(symlink_dir_exec).status().unwrap();
assert!(cmd.success());
// Ensure original dir's executable works.
let cmd = Command::new("/usr/bin/true").status().unwrap();
assert!(cmd.success());
}
================================================
FILE: integration/exec_symlinked_dirs_exec.rs
================================================
use std::os::unix::fs as unixfs;
use std::path::PathBuf;
use std::process::Command;
use birdcage::{Birdcage, Exception, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
#[derive(Serialize, Deserialize)]
struct TestData {
symlink_dir_exec: PathBuf,
}
pub fn setup(tempdir: PathBuf) -> TestSetup {
// Create symlinked executable dir.
let symlink_dir = tempdir.join("bin");
let symlink_dir_exec = symlink_dir.join("true");
unixfs::symlink("/usr/bin", &symlink_dir).unwrap();
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::ExecuteAndRead(symlink_dir_exec.clone())).unwrap();
// Serialize test data.
let data = TestData { symlink_dir_exec };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
// Ensure symlinked dir's executable works.
let cmd = Command::new(data.symlink_dir_exec).status().unwrap();
assert!(cmd.success());
// Ensure original dir's executable works.
let cmd = Command::new("/usr/bin/true").status().unwrap();
assert!(cmd.success());
}
================================================
FILE: integration/exec_symlinked_file.rs
================================================
use std::fs;
use std::os::unix::fs as unixfs;
use std::path::PathBuf;
use std::process::Command;
use birdcage::{Birdcage, Exception, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
#[derive(Serialize, Deserialize)]
struct TestData {
symlink_exec: PathBuf,
}
pub fn setup(tempdir: PathBuf) -> TestSetup {
// Create symlinked executable.
let exec_dir = tempdir.join("bin");
fs::create_dir(&exec_dir).unwrap();
let symlink_exec = exec_dir.join("true");
unixfs::symlink("/usr/bin/true", &symlink_exec).unwrap();
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::ExecuteAndRead(symlink_exec.clone())).unwrap();
// Serialize test data.
let data = TestData { symlink_exec };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
// Ensure symlinked executable works.
let cmd = Command::new(data.symlink_exec).status().unwrap();
assert!(cmd.success());
// Ensure original executable works.
let cmd = Command::new("/usr/bin/true").status().unwrap();
assert!(cmd.success());
}
================================================
FILE: integration/fs.rs
================================================
use std::fs;
use std::path::PathBuf;
use birdcage::{Birdcage, Exception, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
const FILE_CONTENT: &str = "expected content";
#[derive(Serialize, Deserialize)]
struct TestData {
public_path: PathBuf,
private_path: PathBuf,
}
pub fn setup(tempdir: PathBuf) -> TestSetup {
// Setup our test files.
let private_path = tempdir.join("private");
fs::write(&private_path, FILE_CONTENT.as_bytes()).unwrap();
let public_path = tempdir.join("public");
fs::write(&public_path, FILE_CONTENT.as_bytes()).unwrap();
// Setup sandbox exceptions.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::Read(public_path.clone())).unwrap();
// Serialize test data.
let data = TestData { public_path, private_path };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
// Access to the public file is allowed.
let content = fs::read_to_string(data.public_path).unwrap();
assert_eq!(content, FILE_CONTENT);
// Access to the private file is prohibited.
let result = fs::read_to_string(data.private_path);
assert!(result.is_err());
}
================================================
FILE: integration/fs_broken_symlink.rs
================================================
use std::fs::{self, File};
use std::os::unix::fs as unixfs;
use std::path::PathBuf;
use birdcage::error::Error;
use birdcage::{Birdcage, Exception, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
#[derive(Serialize, Deserialize)]
struct TestData {
symlink: PathBuf,
}
pub fn setup(tempdir: PathBuf) -> TestSetup {
// Create a target for the symlink.
let tempfile_path = tempdir.join("broken_target");
File::create(&tempfile_path).unwrap();
// Setup a symlink to the target file.
let symlink_str = tempfile_path.to_string_lossy() + "_symlink";
let symlink = PathBuf::from(symlink_str.as_ref());
unixfs::symlink(&tempfile_path, &symlink).unwrap();
// Remove the target, breaking the symlink.
fs::remove_file(&tempfile_path).unwrap();
assert!(!tempfile_path.exists());
// Sandbox exception fails with invalid path error.
let mut sandbox = Birdcage::new();
let result = sandbox.add_exception(Exception::Read(symlink.clone()));
assert!(matches!(result, Err(Error::InvalidPath(_))));
// Serialize test data.
let data = TestData { symlink };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
// Read/Write results in error.
let result = fs::read_to_string(&data.symlink);
assert!(result.is_err());
let result = fs::write(&data.symlink, "bob");
assert!(result.is_err());
}
================================================
FILE: integration/fs_null.rs
================================================
use std::path::PathBuf;
use std::fs;
use birdcage::{Birdcage, Exception, Sandbox};
use crate::TestSetup;
pub fn setup(_tempdir: PathBuf) -> TestSetup {
// Activate our sandbox.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::WriteAndRead("/dev/null".into())).unwrap();
TestSetup { sandbox, data: String::new() }
}
pub fn validate(_data: String) {
// Writing to `/dev/null` is allowed.
fs::write("/dev/null", "blub").unwrap();
}
================================================
FILE: integration/fs_readonly.rs
================================================
use std::fs;
use std::path::PathBuf;
use birdcage::{Birdcage, Exception, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
const FILE_CONTENT: &str = "expected content";
#[derive(Serialize, Deserialize)]
struct TestData {
file: PathBuf,
}
pub fn setup(tempdir: PathBuf) -> TestSetup {
// Setup the test file.
let file = tempdir.join("fs_readonly");
fs::write(&file, FILE_CONTENT.as_bytes()).unwrap();
// Activate our sandbox.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::Read(file.clone())).unwrap();
// Serialize test data.
let data = TestData { file };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
// Reading from the file is allowed.
let content = fs::read_to_string(&data.file).unwrap();
assert_eq!(content, FILE_CONTENT);
// Writing to the file is prohibited.
let result = fs::write(&data.file, FILE_CONTENT.as_bytes());
assert!(result.is_err());
}
================================================
FILE: integration/fs_restrict_child.rs
================================================
use std::fs;
use std::path::PathBuf;
use birdcage::{Birdcage, Exception, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
const FILE_CONTENT: &str = "expected content";
#[derive(Serialize, Deserialize)]
struct TestData {
tempfile: PathBuf,
tempdir: PathBuf,
}
pub fn setup(tempdir: PathBuf) -> TestSetup {
// Setup our test tree.
let tempfile = tempdir.join("target-file");
fs::write(&tempfile, FILE_CONTENT.as_bytes()).unwrap();
// Setup sandbox, allowing read/write to dir, but only read for the file.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::WriteAndRead(tempdir.clone())).unwrap();
sandbox.add_exception(Exception::Read(tempfile.clone())).unwrap();
// Serialize test data.
let data = TestData { tempfile, tempdir };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
// Write access to directory works.
fs::create_dir(data.tempdir.join("boop")).unwrap();
// Read access to file works.
let content = fs::read_to_string(&data.tempfile).unwrap();
assert_eq!(content, FILE_CONTENT);
// Write access to file is denied.
let result = fs::write(&data.tempfile, "no");
assert!(result.is_err());
}
================================================
FILE: integration/fs_symlink.rs
================================================
use std::fs;
use std::os::unix::fs as unixfs;
use std::path::PathBuf;
use birdcage::{Birdcage, Exception, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
const FILE_CONTENT: &str = "expected content";
#[derive(Serialize, Deserialize)]
struct TestData {
private: PathBuf,
public: PathBuf,
}
pub fn setup(tempdir: PathBuf) -> TestSetup {
// Setup our test files.
let private_path = tempdir.join("private");
fs::write(&private_path, FILE_CONTENT.as_bytes()).unwrap();
let public_path = tempdir.join("public");
fs::write(&public_path, FILE_CONTENT.as_bytes()).unwrap();
// Create symlinks for the files.
let private_str = private_path.to_string_lossy() + "_tmpfile";
let private = PathBuf::from(private_str.as_ref());
let public_str = public_path.to_string_lossy() + "_tmpfile";
let public = PathBuf::from(public_str.as_ref());
unixfs::symlink(&private_path, &private).unwrap();
unixfs::symlink(&public_path, &public).unwrap();
// Activate our sandbox.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::Read(public.clone())).unwrap();
// Serialize test data.
let data = TestData { private, public };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
// Access to the public file is allowed.
let content = fs::read_to_string(&data.public).unwrap();
assert_eq!(content, FILE_CONTENT);
// Access to the private file is prohibited.
let result = fs::read_to_string(&data.private);
assert!(result.is_err());
}
================================================
FILE: integration/fs_symlink_dir.rs
================================================
use std::fs;
use std::os::unix::fs as unixfs;
use std::path::PathBuf;
use birdcage::{Birdcage, Exception, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
const FILE_CONTENT: &str = "expected content";
#[derive(Serialize, Deserialize)]
struct TestData {
symlink: PathBuf,
}
pub fn setup(tempdir: PathBuf) -> TestSetup {
// Setup our test directory.
let symlink_target = tempdir.join("target");
fs::create_dir(symlink_target).unwrap();
let symlink = tempdir.join("symlink");
unixfs::symlink(&tempdir, &symlink).unwrap();
// Activate our sandbox.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::WriteAndRead(symlink.clone())).unwrap();
// Serialize test data.
let data = TestData { symlink };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
// Try to create a file in the symlinked directory.
let path = data.symlink.join("tmpfile");
fs::write(&path, FILE_CONTENT.as_bytes()).unwrap();
let content = fs::read_to_string(&path).unwrap();
assert_eq!(content, FILE_CONTENT);
}
================================================
FILE: integration/fs_symlink_dir_separate_perms.rs
================================================
use std::fs;
use std::os::unix::fs as unixfs;
use std::path::PathBuf;
use birdcage::{Birdcage, Exception, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
const FILE_CONTENT: &str = "expected content";
#[derive(Serialize, Deserialize)]
struct TestData {
symlink_src: PathBuf,
}
pub fn setup(tempdir: PathBuf) -> TestSetup {
// Setup our test directories.
let symlink_src = tempdir.join("src");
fs::create_dir(&symlink_src).unwrap();
let symlink_dst = tempdir.join("dst");
unixfs::symlink(&symlink_src, &symlink_dst).unwrap();
// Add read+write for src, but also add readonly for dst.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::WriteAndRead(symlink_src.clone())).unwrap();
sandbox.add_exception(Exception::Read(symlink_dst.clone())).unwrap();
// Serialize test data.
let data = TestData { symlink_src };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
// Ensure writing works.
let testfile = data.symlink_src.join("file");
fs::write(&testfile, FILE_CONTENT).unwrap();
// Ensure reading works.
let content = fs::read_to_string(&testfile).unwrap();
assert_eq!(content, FILE_CONTENT);
}
================================================
FILE: integration/fs_write_also_read.rs
================================================
use std::fs::{self, File};
use std::path::PathBuf;
use birdcage::{Birdcage, Exception, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
const FILE_CONTENT: &str = "expected content";
#[derive(Serialize, Deserialize)]
struct TestData {
path: PathBuf,
}
pub fn setup(tempdir: PathBuf) -> TestSetup {
// Setup our test files.
let path = tempdir.join("fs_write_also_read");
File::create(&path).unwrap();
// Activate our sandbox.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::WriteAndRead(path.clone())).unwrap();
// Serialize test data.
let data = TestData { path };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
// Write access is allowed.
fs::write(&data.path, FILE_CONTENT.as_bytes()).unwrap();
// Read access is allowed.
let content = fs::read_to_string(data.path).unwrap();
assert_eq!(content, FILE_CONTENT);
}
================================================
FILE: integration/full_env.rs
================================================
use std::path::PathBuf;
use std::env;
use birdcage::{Birdcage, Exception, Sandbox};
use crate::TestSetup;
pub fn setup(_tempdir: PathBuf) -> TestSetup {
// Setup our environment variables
env::set_var("PUBLIC", "GOOD");
// Activate our sandbox.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::FullEnvironment).unwrap();
TestSetup { sandbox, data: String::new() }
}
pub fn validate(_data: String) {
// The `PUBLIC` environment variable can be accessed.
assert_eq!(env::var("PUBLIC"), Ok("GOOD".into()));
}
================================================
FILE: integration/full_sandbox.rs
================================================
use std::net::TcpStream;
use std::path::PathBuf;
use std::process::Command;
use std::{env, fs};
use birdcage::{Birdcage, Sandbox};
use serde::{Deserialize, Serialize};
use crate::TestSetup;
#[derive(Serialize, Deserialize)]
struct TestData {
path: PathBuf,
}
pub fn setup(tempdir: PathBuf) -> TestSetup {
const FILE_CONTENT: &str = "expected content";
// Create testfile.
let path = tempdir.join("full_sandbox");
// Ensure non-sandboxed write works.
fs::write(&path, FILE_CONTENT.as_bytes()).unwrap();
// Ensure non-sandboxed read works.
let content = fs::read_to_string(&path).unwrap();
assert_eq!(content, FILE_CONTENT);
// Ensure non-sandboxed socket connect works.
let stream = TcpStream::connect("phylum.io:443");
assert!(stream.is_ok());
drop(stream);
// Ensure non-sandboxed execution works.
let cmd = Command::new("/usr/bin/true").status();
assert!(cmd.is_ok());
// Ensure non-sandboxed env access works.
env::set_var("TEST", "value");
assert_eq!(env::var("TEST"), Ok("value".into()));
// Setup birdcage sandbox.
let sandbox = Birdcage::new();
// Serialize test data.
let data = TestData { path };
let data = serde_json::to_string(&data).unwrap();
TestSetup { sandbox, data }
}
pub fn validate(data: String) {
// Deserialize test data.
let data: TestData = serde_json::from_str(&data).unwrap();
// Ensure sandboxed write is blocked.
let result = fs::write(&data.path, b"x");
assert!(result.is_err());
// Ensure sandboxed read is blocked.
let result = fs::read_to_string(data.path);
assert!(result.is_err());
// Ensure sandboxed socket connect is blocked.
let stream = TcpStream::connect("phylum.io:443");
assert!(stream.is_err());
drop(stream);
// Ensure sandboxed execution is blocked.
let cmd = Command::new("/usr/bin/true").status();
assert!(cmd.is_err());
// Ensure sandboxed env access is blocked.
assert_eq!(env::var_os("TEST"), None);
}
================================================
FILE: integration/harness.rs
================================================
use std::path::PathBuf;
use std::process::{self, Command, Stdio};
use birdcage::{Birdcage, Exception, Sandbox};
test_mods! {
mod canonicalize;
#[cfg(target_os = "linux")]
mod consistent_id_mappings;
mod delete_before_lockdown;
mod env;
mod exec;
mod exec_symlinked_dir;
mod exec_symlinked_dirs_exec;
mod exec_symlinked_file;
mod fs;
mod fs_broken_symlink;
mod fs_null;
mod fs_readonly;
mod fs_restrict_child;
mod fs_symlink;
mod fs_symlink_dir;
mod fs_symlink_dir_separate_perms;
mod fs_write_also_read;
mod full_env;
mod full_sandbox;
mod missing_exception;
mod net;
#[cfg(target_os = "linux")]
mod seccomp;
}
/// Integration test directory.
const TEST_DIR: &str = "integration";
/// Test setup state.
pub struct TestSetup {
pub sandbox: Birdcage,
pub data: String,
}
fn main() {
let mut args = std::env::args().skip(1);
// Get test name or spawn all the tests.
let test_name = match args.next() {
Some(test_name) => test_name,
None => {
spawn_tests();
return;
},
};
// Find test matching the name.
let test = match TESTS.iter().find(|(cmd, ..)| cmd == &test_name) {
Some(test) => test,
None => unreachable!("invalid test module name: {test_name:?}"),
};
// Run setup or test validation.
let arg = args.next().unwrap();
match arg.as_str() {
"--setup" => {
let tempdir = args.next().unwrap();
run_setup(&test_name, tempdir, &test.1);
},
_ => test.2(arg),
}
}
/// Reexecute binary to launch tests as separate processes.
///
/// Returns `true` on success.
fn spawn_tests() {
eprintln!("\nrunning {} tests", TESTS.len());
// Spawn child processes for all tests.
let current_exe = std::env::current_exe().unwrap();
let mut children = Vec::new();
for (cmd, ..) in TESTS {
let tempdir = tempfile::tempdir().unwrap();
let child = Command::new(¤t_exe)
.arg(cmd)
.arg("--setup")
.arg(tempdir.path())
.stderr(Stdio::piped())
.spawn()
.unwrap();
children.push((cmd, child, tempdir));
}
// Check results for each test.
let mut passed = 0;
for (name, child, tempdir) in children {
let output = match child.wait_with_output() {
Ok(output) => output,
Err(err) => {
eprintln!("test {TEST_DIR}/{name}.rs ... \x1b[31mHARNESS FAILURE\x1b[0m: {err}");
continue;
},
};
// Report individual test results.
if !output.status.success() {
eprintln!("test {TEST_DIR}/{name}.rs ... \x1b[31mFAILED\x1b[0m");
// Print stderr on failure if there is some.
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.is_empty() {
eprintln!("\n---- {TEST_DIR}/{name}.rs stderr ----\n{}\n", stderr.trim());
}
} else {
eprintln!("test {TEST_DIR}/{name}.rs ... \x1b[32mok\x1b[0m");
passed += 1;
}
// Cleanup tempdir.
tempdir.close().unwrap();
}
// Print total results.
let failed = TESTS.len() - passed;
if failed > 0 {
eprintln!("\ntest result: \x1b[31mFAILED\x1b[0m. {} passed; {} failed", passed, failed);
} else {
eprintln!("\ntest result: \x1b[32mok\x1b[0m. {} passed; {} failed", passed, failed);
}
eprintln!();
}
/// Run test's setup step and spawn validation child.
fn run_setup(test_name: &str, tempdir: String, setup: &fn(PathBuf) -> TestSetup) {
// Run test setup.
let mut test_setup = setup(PathBuf::from(tempdir));
// Add exceptions to allow self-execution.
let current_exe = std::env::current_exe().unwrap();
for path in [current_exe.clone(), "/usr/lib".into(), "/lib64".into(), "/lib".into()] {
if path.exists() {
test_setup.sandbox.add_exception(Exception::ExecuteAndRead(path)).unwrap();
}
}
// Reexecute test with sandbox enabled.
let mut command = birdcage::process::Command::new(current_exe);
command.args([test_name, test_setup.data.as_str()]);
let child = test_setup.sandbox.spawn(command).unwrap();
// Validate test results.
let output = child.wait_with_output().unwrap();
if !output.status.success() {
process::exit(output.status.code().unwrap_or(1));
}
}
#[macro_export]
macro_rules! test_mods {
($($(#[$cfg:meta])? mod $mod:ident);*;) => {
$(
$( #[$cfg] )?
mod $mod;
)*
const TESTS: &[(&str, fn(std::path::PathBuf) -> $crate::TestSetup, fn(String))] = &[$(
$( #[$cfg] )?
(stringify!($mod), $mod :: setup, $mod :: validate),
)*];
};
}
================================================
FILE: integration/missing_exception.rs
================================================
use std::path::PathBuf;
use birdcage::error::Error;
use birdcage::{Birdcage, Exception, Sandbox};
use crate::TestSetup;
pub fn setup(_tempdir: PathBuf) -> TestSetup {
let mut sandbox = Birdcage::new();
// Add a path that doesn't exist.
let result = sandbox.add_exception(Exception::Read("/does/not/exist".into()));
// Ensure it is appropriately reported that exception was NOT added.
match result {
Err(Error::InvalidPath(path)) => assert_eq!(path, PathBuf::from("/does/not/exist")),
_ => panic!("expected path error"),
}
TestSetup { sandbox, data: String::new() }
}
pub fn validate(_data: String) {
// Ensure locking is always successful.
}
================================================
FILE: integration/net.rs
================================================
use std::path::PathBuf;
use std::net::TcpStream;
use birdcage::{Birdcage, Exception, Sandbox};
use crate::TestSetup;
pub fn setup(_tempdir: PathBuf) -> TestSetup {
// Setup sandbox exceptions.
let mut sandbox = Birdcage::new();
sandbox.add_exception(Exception::Networking).unwrap();
TestSetup { sandbox, data: String::new() }
}
pub fn validate(_data: String) {
let result = TcpStream::connect("8.8.8.8:443");
assert!(result.is_ok());
}
================================================
FILE: integration/seccomp.rs
================================================
use std::path::PathBuf;
use std::ffi::CString;
use birdcage::{Birdcage, Sandbox};
use crate::TestSetup;
pub fn setup(_tempdir: PathBuf) -> TestSetup {
TestSetup { sandbox: Birdcage::new(), data: String::new() }
}
pub fn validate(_data: String) {
// Ensure `chdir` is allowed.
let root_path = CString::new("/").unwrap();
let result = unsafe { libc::chdir(root_path.as_ptr()) };
assert_eq!(result, 0);
// Ensure `unshare` is always blocked.
let result = unsafe { libc::unshare(libc::CLONE_NEWUSER) };
assert_eq!(result, -1);
// Ensure `clone` is blocked with `CLONE_NEWUSER`.
let stack = unsafe { libc::malloc(4096) };
let flags = libc::CLONE_NEWUSER as libc::c_ulong;
let result = unsafe { libc::syscall(libc::SYS_clone, flags, stack) };
assert_eq!(result, -1);
}
================================================
FILE: rustfmt.toml
================================================
format_code_in_doc_comments = true
group_imports = "StdExternalCrate"
match_block_trailing_comma = true
condense_wildcard_suffixes = true
use_field_init_shorthand = true
normalize_doc_attributes = true
overflow_delimited_expr = true
imports_granularity = "Module"
use_small_heuristics = "Max"
normalize_comments = true
reorder_impl_items = true
use_try_shorthand = true
newline_style = "Unix"
format_strings = true
wrap_comments = true
================================================
FILE: src/error.rs
================================================
//! Sandboxing errors.
use std::error::Error as StdError;
use std::fmt::{self, Display, Formatter};
use std::io::Error as IoError;
#[cfg(target_os = "linux")]
use std::io::ErrorKind as IoErrorKind;
use std::path::PathBuf;
use std::result::Result as StdResult;
#[cfg(target_os = "linux")]
use seccompiler::{BackendError, Error as SeccompError};
/// Birdcage result type.
pub type Result<T> = StdResult<T, Error>;
/// Sandboxing error.
#[derive(Debug)]
pub enum Error {
/// Seccomp errors.
#[cfg(target_os = "linux")]
Seccomp(SeccompError),
/// Invalid sandbox exception path.
InvalidPath(PathBuf),
/// I/O error.
Io(IoError),
/// Sandbox activation failed.
ActivationFailed(String),
}
impl StdError for Error {}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
#[cfg(target_os = "linux")]
Self::Seccomp(error) => write!(f, "seccomp error: {error}"),
Self::InvalidPath(path) => write!(f, "invalid path: {path:?}"),
#[cfg(target_os = "linux")]
Self::Io(error) if error.kind() == IoErrorKind::Unsupported => {
write!(
f,
"unsupported operation, please ensure Kernel version is at least 5.12: {error}"
)
},
Self::Io(error) => write!(f, "input/output error: {error}"),
Self::ActivationFailed(error) => {
write!(f, "failed to initialize a sufficient sandbox: {error}")
},
}
}
}
#[cfg(target_os = "linux")]
impl From<SeccompError> for Error {
fn from(error: SeccompError) -> Self {
Self::Seccomp(error)
}
}
#[cfg(target_os = "linux")]
impl From<BackendError> for Error {
fn from(error: BackendError) -> Self {
Self::Seccomp(SeccompError::Backend(error))
}
}
impl From<IoError> for Error {
fn from(error: IoError) -> Self {
Self::Io(error)
}
}
================================================
FILE: src/lib.rs
================================================
//! Birdcage sandbox.
//!
//! This crate provides a cross-platform API for an embedded sandbox for macOS
//! and Linux.
//!
//! # Example
//!
//! ```rust
//! use std::fs;
//!
//! use birdcage::process::Command;
//! use birdcage::{Birdcage, Exception, Sandbox};
//!
//! // Reads without sandbox work.
//! fs::read_to_string("./Cargo.toml").unwrap();
//!
//! // Allow access to our test executable.
//! let mut sandbox = Birdcage::new();
//! sandbox.add_exception(Exception::ExecuteAndRead("/bin/cat".into())).unwrap();
//! let _ = sandbox.add_exception(Exception::ExecuteAndRead("/lib64".into()));
//! let _ = sandbox.add_exception(Exception::ExecuteAndRead("/lib".into()));
//!
//! // Initialize the sandbox; by default everything is prohibited.
//! let mut command = Command::new("/bin/cat");
//! command.arg("./Cargo.toml");
//! let mut child = sandbox.spawn(command).unwrap();
//!
//! // Reads with sandbox should fail.
//! let status = child.wait().unwrap();
//! assert!(!status.success());
//! ```
use std::env;
use std::path::PathBuf;
use crate::error::Result;
#[cfg(target_os = "linux")]
use crate::linux::LinuxSandbox;
#[cfg(target_os = "macos")]
use crate::macos::MacSandbox;
use crate::process::{Child, Command};
pub mod error;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
pub mod process;
/// Default platform sandbox.
///
/// This type will automatically pick the default sandbox for each available
/// platform.
#[cfg(target_os = "linux")]
pub type Birdcage = LinuxSandbox;
/// Default platform sandbox.
///
/// This type will automatically pick the default sandbox for each available
/// platform.
#[cfg(target_os = "macos")]
pub type Birdcage = MacSandbox;
pub trait Sandbox: Sized {
/// Setup the sandboxing environment.
fn new() -> Self;
/// Add a new exception to the sandbox.
///
/// Exceptions added for symlinks will also automatically apply to the
/// symlink's target.
fn add_exception(&mut self, exception: Exception) -> Result<&mut Self>;
/// Setup sandbox and spawn a new process.
///
/// This will setup the sandbox in the **CURRENT** process, before launching
/// the sandboxee. Since most of the restrictions will also be applied to
/// the calling process, it is recommended to create a separate process
/// before calling this method. The calling process is **NOT** fully
/// sandboxed.
///
/// # Errors
///
/// Sandboxing will fail if the calling process is not single-threaded.
///
/// After failure, the calling process might still be affected by partial
/// sandboxing restrictions.
fn spawn(self, sandboxee: Command) -> Result<Child>;
}
/// Sandboxing exception rule.
///
/// An exception excludes certain resources from the sandbox, allowing sandboxed
/// applications to still access these resources.
#[derive(Debug, Clone)]
pub enum Exception {
/// Allow read access to the path and anything beneath it.
Read(PathBuf),
/// Allow writing and reading the path and anything beneath it.
WriteAndRead(PathBuf),
/// Allow executing and reading the path and anything beneath it.
///
/// This is grouped with reading as a convenience, since execution will
/// always also require read access.
ExecuteAndRead(PathBuf),
/// Allow reading an environment variable.
Environment(String),
/// Allow reading **all** environment variables.
FullEnvironment,
/// Allow networking.
Networking,
}
/// Restrict access to environment variables.
pub(crate) fn restrict_env_variables(exceptions: &[String]) {
// Invalid unicode will cause `env::vars()` to panic, so we don't have to worry
// about them getting ignored.
for (key, _) in env::vars().filter(|(key, _)| !exceptions.contains(key)) {
env::remove_var(key);
}
}
================================================
FILE: src/linux/mod.rs
================================================
//! Linux sandboxing.
use std::collections::HashMap;
use std::ffi::CString;
use std::io::{Error as IoError, ErrorKind as IoErrorKind};
use std::os::fd::OwnedFd;
use std::os::unix::ffi::OsStrExt;
use std::path::{Component, Path, PathBuf};
use std::{env, fs, io, ptr};
use rustix::pipe::pipe;
use rustix::process::{Gid, Pid, Uid, WaitOptions};
use crate::error::{Error, Result};
use crate::linux::namespaces::{MountAttrFlags, Namespaces};
use crate::linux::seccomp::SyscallFilter;
use crate::{Child, Command, Exception, Sandbox};
mod namespaces;
mod seccomp;
/// Linux sandboxing.
#[derive(Default)]
pub struct LinuxSandbox {
env_exceptions: Vec<String>,
path_exceptions: PathExceptions,
allow_networking: bool,
full_env: bool,
}
impl Sandbox for LinuxSandbox {
fn new() -> Self {
Self::default()
}
fn add_exception(&mut self, exception: Exception) -> Result<&mut Self> {
match exception {
Exception::Read(path) => self.path_exceptions.update(path, false, false)?,
Exception::WriteAndRead(path) => self.path_exceptions.update(path, true, false)?,
Exception::ExecuteAndRead(path) => self.path_exceptions.update(path, false, true)?,
Exception::Environment(key) => self.env_exceptions.push(key),
Exception::FullEnvironment => self.full_env = true,
Exception::Networking => self.allow_networking = true,
}
Ok(self)
}
fn spawn(self, sandboxee: Command) -> Result<Child> {
// Ensure calling process is not multi-threaded.
assert!(
thread_count().unwrap_or(0) == 1,
"`Sandbox::spawn` must be called from a single-threaded process"
);
// Remove environment variables.
if !self.full_env {
crate::restrict_env_variables(&self.env_exceptions);
}
// Create pipes to hook up init's stdio.
let stdin_pipe = sandboxee.stdin.make_pipe(true)?;
let stdout_pipe = sandboxee.stdout.make_pipe(false)?;
let stderr_pipe = sandboxee.stderr.make_pipe(false)?;
let exit_signal_pipe = pipe().map_err(IoError::from)?;
// Spawn isolated sandbox PID 1.
let allow_networking = self.allow_networking;
let init_arg = ProcessInitArg::new(
self,
sandboxee,
exit_signal_pipe,
stdin_pipe,
stdout_pipe,
stderr_pipe,
);
let init_arg = spawn_sandbox_init(init_arg, allow_networking)?;
// Deconstruct init args, dropping unused FDs.
let (pid, stdin_tx, stdout_rx, stderr_rx, exit_signal_rx) = {
let ProcessInitArg {
// Extract used fields.
pid,
stdin_tx,
stdout_rx,
stderr_rx,
exit_signal_rx,
// Deconstruct all remaining fields to manually drop them.
path_exceptions: _x0,
exit_signal_tx: _x1,
parent_euid: _x2,
parent_egid: _x3,
stdout_tx: _x4,
stderr_tx: _x5,
sandboxee: _x6,
stdin_rx: _x7,
} = init_arg;
(pid, stdin_tx, stdout_rx, stderr_rx, exit_signal_rx)
};
let child = Child::new(pid, exit_signal_rx, stdin_tx, stdout_rx, stderr_rx)?;
Ok(child)
}
}
/// Create sandbox child process.
///
/// This function uses `clone` to setup the sandbox's init process with user
/// namespace isolations in place.
///
/// Returns PID of the child process if successful.
fn spawn_sandbox_init(init_arg: ProcessInitArg, allow_networking: bool) -> Result<ProcessInitArg> {
unsafe {
// Initialize child process stack memory.
let stack_size = 1024 * 1024;
let child_stack = libc::mmap(
ptr::null_mut(),
stack_size,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_STACK,
-1,
0,
);
if child_stack == libc::MAP_FAILED {
return Err(IoError::last_os_error().into());
}
// Stack grows downward on all relevant Linux processors.
let stack_top = child_stack.add(stack_size);
// Construct clone flags with required namespaces.
let mut flags =
libc::CLONE_NEWIPC | libc::CLONE_NEWNS | libc::CLONE_NEWPID | libc::CLONE_NEWUSER;
if !allow_networking {
flags |= libc::CLONE_NEWNET;
}
// Spawn sandbox init process.
let init_arg_raw = Box::into_raw(Box::new(init_arg));
let init_pid =
libc::clone(sandbox_init, stack_top, flags | libc::SIGCHLD, init_arg_raw as _);
if init_pid == -1 {
Err(IoError::last_os_error().into())
} else {
let mut init_arg = Box::from_raw(init_arg_raw);
init_arg.pid = init_pid;
Ok(*init_arg)
}
}
}
/// PID 1 inside the sandbox.
///
/// This function is the entry point for the process which is used to launch the
/// sandboxee and act as init system for the PID namespace.
extern "C" fn sandbox_init(arg: *mut libc::c_void) -> libc::c_int {
let init_arg: Box<ProcessInitArg> = unsafe { Box::from_raw(arg as _) };
match sandbox_init_inner(*init_arg) {
Ok(exit_code) => exit_code,
Err(err) => {
eprintln!("sandboxing failure: {err}");
1
},
}
}
/// PID 1 inside the sandbox.
///
/// Wrapper to simplify error handling.
fn sandbox_init_inner(mut init_arg: ProcessInitArg) -> io::Result<libc::c_int> {
// Close all unused FDs.
init_arg.stdin_tx.take();
init_arg.stdout_rx.take();
init_arg.stderr_rx.take();
drop(init_arg.exit_signal_rx);
// Hook up stdio to parent process.
if let Some(stdin_pipe) = &mut init_arg.stdin_rx {
rustix::stdio::dup2_stdin(stdin_pipe)?;
}
if let Some(stdout_pipe) = &init_arg.stdout_tx {
rustix::stdio::dup2_stdout(stdout_pipe)?;
}
if let Some(stderr_pipe) = &init_arg.stderr_tx {
rustix::stdio::dup2_stderr(stderr_pipe)?;
}
// Map root UID and GID.
namespaces::map_ids(init_arg.parent_euid.as_raw(), init_arg.parent_egid.as_raw(), 0, 0)?;
// Isolate filesystem using a mount namespace.
namespaces::setup_mount_namespace(init_arg.path_exceptions)?;
// Create new procfs directory.
let new_proc_c = CString::new("/proc")?;
namespaces::mount_proc(&new_proc_c)?;
// Drop root user mapping.
namespaces::create_user_namespace(
init_arg.parent_euid.as_raw(),
init_arg.parent_egid.as_raw(),
Namespaces::empty(),
)?;
// Setup system call filters.
SyscallFilter::apply().map_err(|err| IoError::new(IoErrorKind::Other, err))?;
// Block suid/sgid.
//
// This is also blocked by our bind mount's MS_NOSUID flag, so we're just
// doubling-down here.
rustix::thread::set_no_new_privs(true)?;
// Spawn sandboxed process.
let mut std_command = std::process::Command::from(init_arg.sandboxee);
std_command.stdin(std::process::Stdio::inherit());
std_command.stdout(std::process::Stdio::inherit());
std_command.stderr(std::process::Stdio::inherit());
let child = std_command.spawn()?;
// Reap zombie children.
let child_pid = Pid::from_raw(child.id() as i32);
loop {
// Wait for any child to exit.
match rustix::process::wait(WaitOptions::empty())? {
Some((pid, status)) if Some(pid) == child_pid => match status.terminating_signal() {
Some(signal) => {
// Send exit signal to parent.
rustix::io::write(init_arg.exit_signal_tx, &signal.to_le_bytes())?;
return Ok(1);
},
None => return Ok(status.exit_status().unwrap_or(1) as i32),
},
Some(_) => (),
None => unreachable!("none without nohang"),
}
}
}
/// Init process argument passed to `clone`.
struct ProcessInitArg {
path_exceptions: PathExceptions,
sandboxee: Command,
parent_euid: Uid,
parent_egid: Gid,
// FDs used by the child process.
stdin_rx: Option<OwnedFd>,
stdout_tx: Option<OwnedFd>,
stderr_tx: Option<OwnedFd>,
exit_signal_tx: OwnedFd,
// FDs passed to the child for closing them.
stdin_tx: Option<OwnedFd>,
stdout_rx: Option<OwnedFd>,
stderr_rx: Option<OwnedFd>,
exit_signal_rx: OwnedFd,
pid: i32,
}
impl ProcessInitArg {
fn new(
sandbox: LinuxSandbox,
sandboxee: Command,
exit_signal: (OwnedFd, OwnedFd),
stdin: (Option<OwnedFd>, Option<OwnedFd>),
stdout: (Option<OwnedFd>, Option<OwnedFd>),
stderr: (Option<OwnedFd>, Option<OwnedFd>),
) -> Self {
// Get EUID/EGID outside of the namespaces.
let parent_euid = rustix::process::geteuid();
let parent_egid = rustix::process::getegid();
Self {
parent_euid,
parent_egid,
sandboxee,
path_exceptions: sandbox.path_exceptions,
stdin_rx: stdin.0,
stdout_tx: stdout.1,
stderr_tx: stderr.1,
exit_signal_tx: exit_signal.1,
stdin_tx: stdin.1,
stdout_rx: stdout.0,
stderr_rx: stderr.0,
exit_signal_rx: exit_signal.0,
pid: -1,
}
}
}
/// Path permissions required for the sandbox.
#[derive(Default)]
pub(crate) struct PathExceptions {
bind_mounts: HashMap<PathBuf, MountAttrFlags>,
symlinks: Vec<(PathBuf, PathBuf)>,
}
impl PathExceptions {
/// Add or modify a path's exceptions.
///
/// This will add a new bind mount for the canonical path with the specified
/// permission if it does not exist already.
///
/// If the bind mount already exists, it will *ADD* the additional
/// permissions.
fn update(&mut self, path: PathBuf, write: bool, execute: bool) -> Result<()> {
// Use canonical path for indexing.
//
// This ensures that a symlink and its target are treated like the same path for
// exceptions.
//
// If the home path cannot be accessed, we ignore the exception.
let canonical_path = match path.canonicalize() {
Ok(path) => path,
Err(_) => return Err(Error::InvalidPath(path)),
};
// Store original symlink path to create it if necessary.
if path_has_symlinks(&path) {
// Normalize symlink's path.
let absolute = absolute(&path)?;
let normalized = normalize_path(&absolute);
self.symlinks.push((normalized, canonical_path.clone()));
}
// Update bind mount's permission flags.
let flags = self
.bind_mounts
.entry(canonical_path)
.or_insert(MountAttrFlags::RDONLY | MountAttrFlags::NOEXEC);
if write {
flags.remove(MountAttrFlags::RDONLY);
}
if execute {
flags.remove(MountAttrFlags::NOEXEC);
}
Ok(())
}
}
// Copied from Rust's STD:
// https://github.com/rust-lang/rust/blob/42faef503f3e765120ca0ef06991337668eafc32/library/std/src/sys/unix/path.rs#L23C1-L63C2
//
// Licensed under MIT:
// https://github.com/rust-lang/rust/blob/master/LICENSE-MIT
//
/// Make a POSIX path absolute without changing its semantics.
fn absolute(path: &Path) -> io::Result<PathBuf> {
// This is mostly a wrapper around collecting `Path::components`, with
// exceptions made where this conflicts with the POSIX specification.
// See 4.13 Pathname Resolution, IEEE Std 1003.1-2017
// https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13
// Get the components, skipping the redundant leading "." component if it
// exists.
let mut components = path.strip_prefix(".").unwrap_or(path).components();
let path_os = path.as_os_str().as_bytes();
let mut normalized = if path.is_absolute() {
// "If a pathname begins with two successive <slash> characters, the
// first component following the leading <slash> characters may be
// interpreted in an implementation-defined manner, although more than
// two leading <slash> characters shall be treated as a single <slash>
// character."
if path_os.starts_with(b"//") && !path_os.starts_with(b"///") {
components.next();
PathBuf::from("//")
} else {
PathBuf::new()
}
} else {
env::current_dir()?
};
normalized.extend(components);
// "Interfaces using pathname resolution may specify additional constraints
// when a pathname that does not name an existing directory contains at
// least one non- <slash> character and contains one or more trailing
// <slash> characters".
// A trailing <slash> is also meaningful if "a symbolic link is
// encountered during pathname resolution".
if path_os.ends_with(b"/") {
normalized.push("");
}
Ok(normalized)
}
/// Normalize path components, stripping out `.` and `..`.
fn normalize_path(path: &Path) -> PathBuf {
let mut normalized = PathBuf::new();
for component in path.components() {
match component {
Component::Prefix(_) => unreachable!("impl does not consider windows"),
Component::RootDir => normalized.push("/"),
Component::CurDir => continue,
Component::ParentDir => {
normalized.pop();
},
Component::Normal(segment) => normalized.push(segment),
}
}
normalized
}
/// Check if a path contains any symlinks.
fn path_has_symlinks(path: &Path) -> bool {
path.ancestors().any(|path| path.read_link().is_ok())
}
/// Get the number of threads used by the current process.
fn thread_count() -> io::Result<usize> {
// Read process status from procfs.
let status = fs::read_to_string("/proc/self/status")?;
// Parse procfs output.
let (_, threads_start) = status.split_once("Threads:").ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "/proc/self/status missing \"Threads:\"")
})?;
let thread_count = threads_start.split_whitespace().next().ok_or_else(|| {
io::Error::new(io::ErrorKind::InvalidData, "/proc/self/status output malformed")
})?;
// Convert to number.
let thread_count = thread_count
.parse::<usize>()
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
Ok(thread_count)
}
================================================
FILE: src/linux/namespaces.rs
================================================
//! Linux namespaces.
use std::cmp::Ordering;
use std::ffi::{CStr, CString};
use std::fs::{self, File};
use std::io::Error as IoError;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs as unixfs;
use std::path::{Component, Path, PathBuf};
use std::{env, io, mem, ptr};
use bitflags::bitflags;
use crate::linux::PathExceptions;
/// Path for mount namespace's new root.
const NEW_ROOT: &str = "/tmp/birdcage-root";
/// Isolate filesystem access in an existing mount namespace.
///
/// This will deny access to any path which isn't part of `bind_mounts`. Allowed
/// paths are mounted according to their bind mount flags.
pub(crate) fn setup_mount_namespace(exceptions: PathExceptions) -> io::Result<()> {
// Get target paths for new and old root.
let new_root = PathBuf::from(NEW_ROOT);
// Ensure new root is available as an empty directory.
if !new_root.exists() {
fs::create_dir_all(&new_root)?;
}
// Create C-friendly versions for our paths.
let new_root_c = CString::new(new_root.as_os_str().as_bytes()).unwrap();
// Create tmpfs mount for the new root, allowing pivot and ensuring directories
// aren't created outside the sandbox.
mount_tmpfs(&new_root_c)?;
// Sort bind mounts by shortest length, to create parents before their children.
let mut bind_mounts: Vec<_> = exceptions.bind_mounts.into_iter().collect();
bind_mounts.sort_unstable_by(|(a_path, a_flags), (b_path, b_flags)| {
match a_path.components().count().cmp(&b_path.components().count()) {
Ordering::Equal => (a_path, a_flags).cmp(&(b_path, b_flags)),
ord => ord,
}
});
// Bind mount all allowed directories.
for (path, flags) in bind_mounts {
let src_c = CString::new(path.as_os_str().as_bytes()).unwrap();
// Get bind mount destination.
let unrooted_path = path.strip_prefix("/").unwrap();
let dst = new_root.join(unrooted_path);
let dst_c = CString::new(dst.as_os_str().as_bytes()).unwrap();
// Create mount target.
if let Err(err) = copy_tree(&path, &new_root) {
log::error!("skipping birdcage exception {path:?}: {err}");
continue;
}
// Bind path with full permissions.
bind_mount(&src_c, &dst_c)?;
// Remount to update permissions.
update_mount_flags(&dst_c, flags | MountAttrFlags::NOSUID)?;
}
// Ensure original symlink paths are available.
create_symlinks(&new_root, exceptions.symlinks)?;
// Bind mount old procfs.
let old_proc_c = CString::new("/proc").unwrap();
let new_proc = new_root.join("proc");
let new_proc_c = CString::new(new_proc.as_os_str().as_bytes()).unwrap();
fs::create_dir_all(&new_proc)?;
bind_mount(&old_proc_c, &new_proc_c)?;
// Pivot root to `new_root`, placing the old root at the same location.
pivot_root(&new_root_c, &new_root_c)?;
// Remove old root mounted at /, leaving only the new root at the same location.
let root_c = CString::new("/").unwrap();
umount(&root_c)?;
// Prevent child mount namespaces from accessing this namespace's mounts.
deny_mount_propagation()?;
Ok(())
}
/// Create missing symlinks.
///
/// If the parent directory of a symlink is mapped, we do not need to map the
/// symlink ourselves and it's not possible to mount on top of it anyway. So
/// here we make sure that symlinks are created if no bind mount was created for
/// their parent directory.
fn create_symlinks(new_root: &Path, symlinks: Vec<(PathBuf, PathBuf)>) -> io::Result<()> {
for (symlink, target) in symlinks {
// Ignore symlinks if a parent bind mount exists.
let unrooted_path = symlink.strip_prefix("/").unwrap();
let dst = new_root.join(unrooted_path);
if dst.symlink_metadata().is_ok() {
continue;
}
// Create all parent directories.
let parent = match symlink.parent() {
Some(parent) => parent,
None => continue,
};
copy_tree(parent, new_root)?;
// Create the symlink.
unixfs::symlink(target, dst)?;
}
Ok(())
}
/// Replicate a directory tree under a different directory.
///
/// This will create all missing empty diretories and copy their permissions
/// from the source tree.
///
/// If `src` ends in a file, an empty file with matching permissions will be
/// created.
fn copy_tree(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> io::Result<()> {
let mut dst = dst.as_ref().to_path_buf();
let mut src_sub = PathBuf::new();
let src = src.as_ref();
for component in src.components() {
// Append root only to source.
if component == Component::RootDir {
src_sub = src_sub.join(component);
continue;
}
src_sub = src_sub.join(component);
dst = dst.join(component);
// Skip nodes that already exist.
if dst.exists() {
continue;
}
// Create target file/directory.
let metadata = src_sub.metadata()?;
if metadata.is_dir() {
fs::create_dir(&dst)?;
} else {
File::create(&dst)?;
}
// Copy permissions.
let permissions = metadata.permissions();
fs::set_permissions(&dst, permissions)?;
}
Ok(())
}
/// Mount a new tmpfs.
fn mount_tmpfs(dst: &CStr) -> io::Result<()> {
let flags = MountFlags::empty();
let fstype = CString::new("tmpfs").unwrap();
let res = unsafe {
libc::mount(ptr::null(), dst.as_ptr(), fstype.as_ptr(), flags.bits(), ptr::null())
};
if res == 0 {
Ok(())
} else {
Err(IoError::last_os_error())
}
}
/// Mount a new procfs.
pub fn mount_proc(dst: &CStr) -> io::Result<()> {
let flags = MountFlags::NOSUID | MountFlags::NODEV | MountFlags::NOEXEC;
let fstype = CString::new("proc").unwrap();
let res = unsafe {
libc::mount(fstype.as_ptr(), dst.as_ptr(), fstype.as_ptr(), flags.bits(), ptr::null())
};
if res == 0 {
Ok(())
} else {
Err(IoError::last_os_error())
}
}
/// Create a new bind mount.
fn bind_mount(src: &CStr, dst: &CStr) -> io::Result<()> {
let flags = MountFlags::BIND | MountFlags::RECURSIVE;
let res =
unsafe { libc::mount(src.as_ptr(), dst.as_ptr(), ptr::null(), flags.bits(), ptr::null()) };
if res == 0 {
Ok(())
} else {
Err(IoError::last_os_error())
}
}
/// Remount an existing bind mount with a new set of mount flags.
fn update_mount_flags(mount: &CStr, flags: MountAttrFlags) -> io::Result<()> {
let attrs = MountAttr { attr_set: flags.bits(), ..Default::default() };
let res = unsafe {
libc::syscall(
libc::SYS_mount_setattr,
libc::AT_FDCWD,
mount.as_ptr(),
libc::AT_RECURSIVE,
&attrs as *const _,
mem::size_of::<MountAttr>(),
)
};
if res == 0 {
Ok(())
} else {
Err(IoError::last_os_error())
}
}
/// Recursively update the root to deny mount propagation.
fn deny_mount_propagation() -> io::Result<()> {
let flags = MountFlags::PRIVATE | MountFlags::RECURSIVE;
let root = CString::new("/").unwrap();
let res =
unsafe { libc::mount(ptr::null(), root.as_ptr(), ptr::null(), flags.bits(), ptr::null()) };
if res == 0 {
Ok(())
} else {
Err(IoError::last_os_error())
}
}
/// Change root directory to `new_root` and mount the old root in `put_old`.
///
/// The `put_old` directory must be at or undearneath `new_root`.
fn pivot_root(new_root: &CStr, put_old: &CStr) -> io::Result<()> {
// Get target working directory path.
let working_dir = env::current_dir().unwrap_or_else(|_| PathBuf::from("/"));
let result =
unsafe { libc::syscall(libc::SYS_pivot_root, new_root.as_ptr(), put_old.as_ptr()) };
if result != 0 {
return Err(IoError::last_os_error());
}
// Attempt to recover working directory, or switch to root.
//
// Without this, the user's working directory would stay the same, giving him
// full access to it even if it is not bound.
if env::set_current_dir(working_dir).is_err() {
env::set_current_dir("/")?;
}
Ok(())
}
/// Unmount a filesystem.
fn umount(target: &CStr) -> io::Result<()> {
let result = unsafe { libc::umount2(target.as_ptr(), libc::MNT_DETACH) };
match result {
0 => Ok(()),
_ => Err(IoError::last_os_error()),
}
}
/// Create a new user namespace.
///
/// The parent and child UIDs and GIDs define the user and group mappings
/// between the parent namespace and the new user namespace.
pub fn create_user_namespace(
child_uid: u32,
child_gid: u32,
extra_namespaces: Namespaces,
) -> io::Result<()> {
// Get current user's EUID and EGID.
let parent_euid = unsafe { libc::geteuid() };
let parent_egid = unsafe { libc::getegid() };
// Create the namespace.
unshare(Namespaces::USER | extra_namespaces)?;
// Map the UID and GID.
map_ids(parent_euid, parent_egid, child_uid, child_gid)?;
Ok(())
}
/// Update /proc uid/gid maps.
///
/// This should be called after creating a user namespace to ensure proper ID
/// mappings.
pub fn map_ids(
parent_euid: u32,
parent_egid: u32,
child_uid: u32,
child_gid: u32,
) -> io::Result<()> {
let uid_map = format!("{child_uid} {parent_euid} 1\n");
let gid_map = format!("{child_gid} {parent_egid} 1\n");
fs::write("/proc/self/uid_map", uid_map.as_bytes())?;
fs::write("/proc/self/setgroups", b"deny")?;
fs::write("/proc/self/gid_map", gid_map.as_bytes())?;
Ok(())
}
/// Enter a namespace.
fn unshare(namespaces: Namespaces) -> io::Result<()> {
let result = unsafe { libc::unshare(namespaces.bits()) };
match result {
0 => Ok(()),
_ => Err(IoError::last_os_error()),
}
}
bitflags! {
/// Mount syscall flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MountFlags: libc::c_ulong {
/// Ignore suid and sgid bits.
const NOSUID = libc::MS_NOSUID;
/// Disallow access to device special files.
const NODEV = libc::MS_NODEV;
/// Disallow program execution.
const NOEXEC = libc::MS_NOEXEC;
/// Create a bind mount.
const BIND = libc::MS_BIND;
/// Used in conjuction with [`Self::BIND`] to create a recursive bind mount, and
/// in conjuction with the propagation type flags to recursively change the
/// propagation type of all of the mounts in a sub-tree.
const RECURSIVE = libc::MS_REC;
/// Make this mount private. Mount and unmount events do not propagate into or
/// out of this mount.
const PRIVATE = libc::MS_PRIVATE;
/// Do not follow symbolic links when resolving paths.
const NOSYMFOLLOW = 256;
}
}
/// Parameter for the `mount_setattr` syscall.
#[repr(C)]
#[derive(Default)]
struct MountAttr {
attr_set: u64,
attr_clr: u64,
propagation: u64,
userns_fd: u64,
}
bitflags! {
/// Flags for the `mount_setattr` syscall.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MountAttrFlags: u64 {
/// Mount read-only.
const RDONLY = 0x00000001;
/// Ignore suid and sgid bits.
const NOSUID = 0x00000002;
/// Disallow access to device special files.
const NODEV = 0x00000004;
/// Disallow program execution.
const NOEXEC = 0x00000008;
/// Setting on how atime should be updated.
const _ATIME = 0x00000070;
/// - Update atime relative to mtime/ctime.
const RELATI = 0x00000000;
/// - Do not update access times.
const NOATIM = 0x00000010;
/// - Always perform atime updates.
const STRICTATIME = 0x00000020;
/// Do not update directory access times.
const NODIRATIME = 0x00000080;
/// Idmap mount to @userns_fd in struct mount_attr.
const IDMAP = 0x00100000;
/// Do not follow symlinks.
const NOSYMFOLLOW = 0x00200000;
}
}
bitflags! {
/// Unshare system call namespace flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Namespaces: libc::c_int {
/// Unshare the file descriptor table, so that the calling process no longer
/// shares its file descriptors with any other process.
const FILES = libc::CLONE_FILES;
/// Unshare filesystem attributes, so that the calling process no longer shares
/// its root directory, current directory, or umask attributes with any other process.
const FS = libc::CLONE_FS;
/// Unshare the cgroup namespace.
const CGROUP = libc::CLONE_NEWCGROUP;
/// Unshare the IPC namespace, so that the calling process has a private copy of
/// the IPC namespace which is not shared with any other process. Specifying
/// this flag automatically implies [`Namespaces::SYSVSEM`] as well.
const IPC = libc::CLONE_NEWIPC;
/// Unshare the network namespace, so that the calling process is moved into a
/// new network namespace which is not shared with any previously existing process.
const NETWORK = libc::CLONE_NEWNET;
/// Unshare the mount namespace, so that the calling process has a private copy
/// of its namespace which is not shared with any other process. Specifying this
/// flag automatically implies [`Namespaces::FS`] as well.
const MOUNT = libc::CLONE_NEWNS;
/// Unshare the PID namespace, so that the calling process has a new PID
/// namespace for its children which is not shared with any previously existing
/// process. The calling process is **not** moved into the new namespace. The
/// first child created by the calling process will have the process ID 1 and
/// will assume the role of init in the new namespace. Specifying this flag
/// automatically implies [`libc::CLONE_THREAD`] as well.
const PID = libc::CLONE_NEWPID;
/// Unshare the time namespace, so that the calling process has a new time
/// namespace for its children which is not shared with any previously existing
/// process. The calling process is **not** moved into the new namespace.
const TIME = 0x80;
/// Unshare the user namespace, so that the calling process is moved into a new
/// user namespace which is not shared with any previously existing process. The
/// caller obtains a full set of capabilities in the new namespace.
///
/// Requires that the calling process is not threaded; specifying this flag
/// automatically implies [`libc::CLONE_THREAD`] and [`Namespaces::FS`] as well.
const USER = libc::CLONE_NEWUSER;
/// Unshare the UTS IPC namespace, so that the calling process has a private
/// copy of the UTS namespace which is not shared with any other process.
const UTS = libc::CLONE_NEWUTS;
/// Unshare System V semaphore adjustment (semadj) values, so that the calling
/// process has a new empty semadj list that is not shared with any other
/// process. If this is the last process that has a reference to the process's
/// current semadj list, then the adjustments in that list are applied to the
/// corresponding semaphores
const SYSVSEM = libc::CLONE_SYSVSEM;
}
}
================================================
FILE: src/linux/seccomp.rs
================================================
//! Seccomp system call filtering.
use std::collections::BTreeMap;
use seccompiler::{
BpfProgram, SeccompAction, SeccompCmpArgLen, SeccompCmpOp, SeccompCondition, SeccompFilter,
SeccompRule, TargetArch,
};
use crate::Result;
#[cfg(target_arch = "x86_64")]
const ARCH: TargetArch = TargetArch::x86_64;
#[cfg(target_arch = "aarch64")]
const ARCH: TargetArch = TargetArch::aarch64;
/// Bitmask for the clone syscall seccomp filter.
///
/// A 1 in the bitmask means system calls with this flag set will be denied.
///
/// Filtered flags:
/// - CLONE_NEWNS = 0x00020000
/// - CLONE_NEWCGROUP = 0x02000000
/// - CLONE_NEWUTS = 0x04000000
/// - CLONE_NEWIPC = 0x08000000
/// - CLONE_NEWUSER = 0x10000000
/// - CLONE_NEWPID = 0x20000000
/// - CLONE_NEWNET = 0x40000000
const CLONE_NAMESPACE_FILTER: u32 = 0b01111110000000100000000000000000;
/// Seccomp system call filter.
///
/// This filter is aimed at restricting system calls which shouldn't be
/// executable by an untrusted client.
#[derive(Default)]
pub struct SyscallFilter;
impl SyscallFilter {
/// Apply the seccomp filter.
pub fn apply() -> Result<()> {
let mut rules = BTreeMap::new();
// Add exceptions for allowed syscalls.
for syscall in SYSCALL_WHITELIST {
rules.insert(*syscall, Vec::new());
}
// Add exception for the `clone` syscall.
let allow_clone = SeccompCondition::new(
0,
SeccompCmpArgLen::Qword,
SeccompCmpOp::MaskedEq(CLONE_NAMESPACE_FILTER as u64),
0,
)?;
let clone_rule = SeccompRule::new(vec![allow_clone])?;
rules.insert(libc::SYS_clone, vec![clone_rule]);
// Apply seccomp filter.
let filter = SeccompFilter::new(
rules,
// Action performed if no rule matches.
SeccompAction::Errno(libc::EACCES as u32),
// Action performed if any rule matches.
SeccompAction::Allow,
ARCH,
)?;
let program: BpfProgram = filter.try_into()?;
seccompiler::apply_filter(&program)?;
// Change `clone3` syscall error to "not implemented", to force `clone` usage.
let mut rules = BTreeMap::new();
rules.insert(libc::SYS_clone3, Vec::new());
let filter = SeccompFilter::new(
rules,
// Action performed if no rule matches.
SeccompAction::Allow,
// Action performed if any rule matches.
SeccompAction::Errno(libc::ENOSYS as u32),
ARCH,
)?;
let program: BpfProgram = filter.try_into()?;
seccompiler::apply_filter(&program)?;
Ok(())
}
}
/// Unconditionally allowed syscalls for networking.
const SYSCALL_WHITELIST: &[libc::c_long] = &[
libc::SYS_read,
libc::SYS_write,
#[cfg(target_arch = "x86_64")]
libc::SYS_open,
libc::SYS_close,
#[cfg(target_arch = "x86_64")]
libc::SYS_stat,
libc::SYS_fstat,
#[cfg(target_arch = "x86_64")]
libc::SYS_lstat,
#[cfg(target_arch = "x86_64")]
libc::SYS_poll,
libc::SYS_lseek,
libc::SYS_mmap,
libc::SYS_mprotect,
libc::SYS_munmap,
libc::SYS_brk,
libc::SYS_rt_sigaction,
libc::SYS_rt_sigprocmask,
libc::SYS_rt_sigreturn,
libc::SYS_ioctl,
libc::SYS_pread64,
libc::SYS_pwrite64,
libc::SYS_readv,
libc::SYS_writev,
#[cfg(target_arch = "x86_64")]
libc::SYS_access,
#[cfg(target_arch = "x86_64")]
libc::SYS_pipe,
#[cfg(target_arch = "x86_64")]
libc::SYS_select,
libc::SYS_sched_yield,
libc::SYS_mremap,
libc::SYS_msync,
libc::SYS_mincore,
libc::SYS_madvise,
libc::SYS_shmget,
libc::SYS_shmat,
libc::SYS_shmctl,
libc::SYS_dup,
#[cfg(target_arch = "x86_64")]
libc::SYS_dup2,
#[cfg(target_arch = "x86_64")]
libc::SYS_pause,
libc::SYS_nanosleep,
libc::SYS_getitimer,
#[cfg(target_arch = "x86_64")]
libc::SYS_alarm,
libc::SYS_setitimer,
libc::SYS_getpid,
#[cfg(target_arch = "x86_64")]
libc::SYS_sendfile,
libc::SYS_connect,
libc::SYS_accept,
libc::SYS_sendto,
libc::SYS_recvfrom,
libc::SYS_sendmsg,
libc::SYS_recvmsg,
libc::SYS_shutdown,
libc::SYS_bind,
libc::SYS_listen,
libc::SYS_getsockname,
libc::SYS_getpeername,
libc::SYS_setsockopt,
libc::SYS_getsockopt,
#[cfg(target_arch = "x86_64")]
libc::SYS_fork,
#[cfg(target_arch = "x86_64")]
libc::SYS_vfork,
libc::SYS_execve,
libc::SYS_exit,
libc::SYS_wait4,
libc::SYS_kill,
libc::SYS_uname,
libc::SYS_semget,
libc::SYS_semop,
libc::SYS_semctl,
libc::SYS_shmdt,
libc::SYS_msgget,
libc::SYS_msgsnd,
libc::SYS_msgrcv,
libc::SYS_msgctl,
libc::SYS_fcntl,
libc::SYS_flock,
libc::SYS_fsync,
libc::SYS_fdatasync,
libc::SYS_truncate,
libc::SYS_ftruncate,
#[cfg(target_arch = "x86_64")]
libc::SYS_getdents,
libc::SYS_getcwd,
libc::SYS_chdir,
libc::SYS_fchdir,
#[cfg(target_arch = "x86_64")]
libc::SYS_rename,
#[cfg(target_arch = "x86_64")]
libc::SYS_mkdir,
#[cfg(target_arch = "x86_64")]
libc::SYS_rmdir,
#[cfg(target_arch = "x86_64")]
libc::SYS_creat,
#[cfg(target_arch = "x86_64")]
libc::SYS_link,
#[cfg(target_arch = "x86_64")]
libc::SYS_unlink,
#[cfg(target_arch = "x86_64")]
libc::SYS_symlink,
#[cfg(target_arch = "x86_64")]
libc::SYS_readlink,
#[cfg(target_arch = "x86_64")]
libc::SYS_chmod,
libc::SYS_fchmod,
#[cfg(target_arch = "x86_64")]
libc::SYS_chown,
libc::SYS_fchown,
#[cfg(target_arch = "x86_64")]
libc::SYS_lchown,
libc::SYS_umask,
libc::SYS_gettimeofday,
libc::SYS_getrlimit,
libc::SYS_getrusage,
libc::SYS_sysinfo,
libc::SYS_times,
libc::SYS_getuid,
libc::SYS_getgid,
libc::SYS_setuid,
libc::SYS_setgid,
libc::SYS_geteuid,
libc::SYS_getegid,
libc::SYS_setpgid,
libc::SYS_getppid,
#[cfg(target_arch = "x86_64")]
libc::SYS_getpgrp,
libc::SYS_setsid,
libc::SYS_setreuid,
libc::SYS_setregid,
libc::SYS_getgroups,
libc::SYS_setgroups,
libc::SYS_setresuid,
libc::SYS_getresuid,
libc::SYS_setresgid,
libc::SYS_getresgid,
libc::SYS_getpgid,
libc::SYS_setfsuid,
libc::SYS_setfsgid,
libc::SYS_getsid,
libc::SYS_capget,
libc::SYS_capset,
libc::SYS_rt_sigpending,
libc::SYS_rt_sigtimedwait,
libc::SYS_rt_sigqueueinfo,
libc::SYS_rt_sigsuspend,
libc::SYS_sigaltstack,
#[cfg(target_arch = "x86_64")]
libc::SYS_utime,
#[cfg(target_arch = "x86_64")]
libc::SYS_mknod,
libc::SYS_statfs,
libc::SYS_fstatfs,
libc::SYS_getpriority,
libc::SYS_setpriority,
libc::SYS_sched_setparam,
libc::SYS_sched_getparam,
libc::SYS_sched_setscheduler,
libc::SYS_sched_getscheduler,
libc::SYS_sched_get_priority_max,
libc::SYS_sched_get_priority_min,
libc::SYS_sched_rr_get_interval,
libc::SYS_mlock,
libc::SYS_munlock,
libc::SYS_mlockall,
libc::SYS_munlockall,
#[cfg(target_arch = "x86_64")]
libc::SYS_modify_ldt,
libc::SYS_prctl,
#[cfg(target_arch = "x86_64")]
libc::SYS_arch_prctl,
libc::SYS_adjtimex,
libc::SYS_setrlimit,
libc::SYS_sync,
libc::SYS_gettid,
libc::SYS_readahead,
libc::SYS_setxattr,
libc::SYS_lsetxattr,
libc::SYS_fsetxattr,
libc::SYS_getxattr,
libc::SYS_lgetxattr,
libc::SYS_fgetxattr,
libc::SYS_listxattr,
libc::SYS_llistxattr,
libc::SYS_flistxattr,
libc::SYS_removexattr,
libc::SYS_lremovexattr,
libc::SYS_fremovexattr,
libc::SYS_tkill,
#[cfg(target_arch = "x86_64")]
libc::SYS_time,
libc::SYS_futex,
libc::SYS_sched_setaffinity,
libc::SYS_sched_getaffinity,
#[cfg(target_arch = "x86_64")]
libc::SYS_set_thread_area,
libc::SYS_io_setup,
libc::SYS_io_destroy,
libc::SYS_io_getevents,
libc::SYS_io_submit,
libc::SYS_io_cancel,
#[cfg(target_arch = "x86_64")]
libc::SYS_get_thread_area,
#[cfg(target_arch = "x86_64")]
libc::SYS_epoll_create,
#[cfg(target_arch = "x86_64")]
libc::SYS_epoll_ctl_old,
#[cfg(target_arch = "x86_64")]
libc::SYS_epoll_wait_old,
libc::SYS_remap_file_pages,
libc::SYS_getdents64,
libc::SYS_set_tid_address,
libc::SYS_restart_syscall,
libc::SYS_semtimedop,
#[cfg(target_arch = "x86_64")]
libc::SYS_fadvise64,
libc::SYS_timer_create,
libc::SYS_timer_settime,
libc::SYS_timer_gettime,
libc::SYS_timer_getoverrun,
libc::SYS_timer_delete,
libc::SYS_clock_gettime,
libc::SYS_clock_getres,
libc::SYS_clock_nanosleep,
libc::SYS_exit_group,
#[cfg(target_arch = "x86_64")]
libc::SYS_epoll_wait,
libc::SYS_epoll_ctl,
libc::SYS_tgkill,
#[cfg(target_arch = "x86_64")]
libc::SYS_utimes,
libc::SYS_mq_open,
libc::SYS_mq_unlink,
libc::SYS_mq_timedsend,
libc::SYS_mq_timedreceive,
libc::SYS_mq_notify,
libc::SYS_mq_getsetattr,
libc::SYS_waitid,
libc::SYS_ioprio_set,
libc::SYS_ioprio_get,
#[cfg(target_arch = "x86_64")]
libc::SYS_inotify_init,
libc::SYS_inotify_add_watch,
libc::SYS_inotify_rm_watch,
libc::SYS_migrate_pages,
libc::SYS_openat,
libc::SYS_mkdirat,
libc::SYS_mknodat,
libc::SYS_fchownat,
#[cfg(target_arch = "x86_64")]
libc::SYS_futimesat,
libc::SYS_newfstatat,
libc::SYS_unlinkat,
libc::SYS_renameat,
libc::SYS_linkat,
libc::SYS_symlinkat,
libc::SYS_readlinkat,
libc::SYS_fchmodat,
libc::SYS_faccessat,
libc::SYS_pselect6,
libc::SYS_ppoll,
libc::SYS_set_robust_list,
libc::SYS_get_robust_list,
libc::SYS_splice,
libc::SYS_tee,
libc::SYS_sync_file_range,
libc::SYS_vmsplice,
libc::SYS_utimensat,
libc::SYS_epoll_pwait,
#[cfg(target_arch = "x86_64")]
libc::SYS_signalfd,
libc::SYS_timerfd_create,
#[cfg(target_arch = "x86_64")]
libc::SYS_eventfd,
libc::SYS_fallocate,
libc::SYS_timerfd_settime,
libc::SYS_timerfd_gettime,
libc::SYS_accept4,
libc::SYS_signalfd4,
libc::SYS_eventfd2,
libc::SYS_epoll_create1,
libc::SYS_dup3,
libc::SYS_pipe2,
libc::SYS_inotify_init1,
libc::SYS_preadv,
libc::SYS_pwritev,
libc::SYS_rt_tgsigqueueinfo,
libc::SYS_recvmmsg,
libc::SYS_fanotify_mark,
libc::SYS_prlimit64,
libc::SYS_name_to_handle_at,
libc::SYS_syncfs,
libc::SYS_sendmmsg,
libc::SYS_getcpu,
libc::SYS_sched_setattr,
libc::SYS_sched_getattr,
libc::SYS_renameat2,
libc::SYS_seccomp,
libc::SYS_getrandom,
libc::SYS_memfd_create,
libc::SYS_execveat,
libc::SYS_membarrier,
libc::SYS_mlock2,
libc::SYS_copy_file_range,
libc::SYS_preadv2,
libc::SYS_pwritev2,
libc::SYS_pkey_mprotect,
libc::SYS_pkey_alloc,
libc::SYS_pkey_free,
libc::SYS_statx,
libc::SYS_rseq,
libc::SYS_pidfd_send_signal,
libc::SYS_pidfd_open,
libc::SYS_close_range,
libc::SYS_openat2,
libc::SYS_faccessat2,
libc::SYS_epoll_pwait2,
libc::SYS_landlock_create_ruleset,
libc::SYS_landlock_add_rule,
libc::SYS_landlock_restrict_self,
libc::SYS_memfd_secret,
libc::SYS_process_mrelease,
libc::SYS_futex_waitv,
libc::SYS_socketpair,
libc::SYS_socket,
libc::SYS_io_uring_enter,
libc::SYS_io_uring_register,
libc::SYS_io_uring_setup,
];
================================================
FILE: src/macos.rs
================================================
//! Linux sandboxing.
//!
//! This module implements sandboxing on macOS using `sandbox_init`.
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::io::{Result as IoResult, Write};
use std::path::{Path, PathBuf};
use std::{fs, ptr};
use bitflags::bitflags;
use crate::error::{Error, Result};
use crate::{Child, Command, Exception, Sandbox};
/// Deny-all fallback rule.
static DEFAULT_RULE: &[u8] = b"\
(version 1)
(import \"system.sb\")
(deny default)
(allow mach*)
(allow ipc*)
(allow signal (target others))
(allow process-fork)
(allow sysctl*)
(allow system*)
(allow file-read-metadata)
(system-network)
";
/// macOS sandboxing based on Seatbelt.
#[derive(Default)]
pub struct MacSandbox {
path_exceptions: HashMap<String, PathException>,
env_exceptions: Vec<String>,
net_exception: bool,
full_env: bool,
}
impl Sandbox for MacSandbox {
fn new() -> Self {
Self::default()
}
fn add_exception(&mut self, exception: Exception) -> Result<&mut Self> {
match exception {
Exception::Read(path) => self.update_path_exceptions(path, PathException::READ)?,
Exception::WriteAndRead(path) => {
self.update_path_exceptions(path, PathException::WRITE | PathException::READ)?
},
Exception::ExecuteAndRead(path) => {
self.update_path_exceptions(path, PathException::EXECUTE | PathException::READ)?
},
Exception::Networking => self.net_exception = true,
Exception::Environment(key) => {
self.env_exceptions.push(key);
return Ok(self);
},
Exception::FullEnvironment => {
self.full_env = true;
return Ok(self);
},
}
Ok(self)
}
fn spawn(self, mut sandboxee: Command) -> Result<Child> {
// Remove environment variables.
if !self.full_env {
crate::restrict_env_variables(&self.env_exceptions);
}
// Create the seatbelt sandbox profile.
let profile = self.create_profile()?;
let profile =
CString::new(profile).map_err(|_| Error::ActivationFailed("invalid profile".into()))?;
let mut error = ptr::null_mut();
let result = unsafe { sandbox_init(profile.as_ptr(), 0, &mut error) };
if result == 0 {
Ok(sandboxee.spawn()?)
} else {
unsafe {
let error_text = CStr::from_ptr(error)
.to_str()
.map_err(|_| Error::ActivationFailed("sandbox_init failed".into()))?
.to_owned();
sandbox_free_error(error);
Err(Error::ActivationFailed(error_text))
}
}
}
}
impl MacSandbox {
/// Add or modify a path's exceptions.
fn update_path_exceptions(&mut self, path: PathBuf, exceptions: PathException) -> Result<()> {
// Canonicalize all exception paths.
//
// Since the macOS sandbox only cares about permissions for symlink targets, due
// to the `(allow file-read-metadata)` rule, we don't need to bother with
// keeping the original paths.
let escaped_path = escape_path(&path)?;
let exception = self.path_exceptions.entry(escaped_path).or_insert(PathException::empty());
exception.insert(exceptions);
Ok(())
}
/// Create a seatbelt profile for the requested sandbox configuration.
fn create_profile(&self) -> Result<Vec<u8>> {
let mut profile = DEFAULT_RULE.to_vec();
// Sort by component count to ensure parent paths appear before descendants.
let mut path_exceptions: Vec<_> = self.path_exceptions.iter().collect();
path_exceptions.sort_unstable_by(|a, b| a.0.len().cmp(&b.0.len()));
for (path, exception) in path_exceptions {
// Deny all access to clear existing permission grants.
Self::revoke_path_access(&mut profile, path)?;
if exception.contains(PathException::READ) {
let rule = PathRule::new(RuleMode::Allow, "file-read*", path.into());
rule.write_to(&mut profile)?;
}
if exception.contains(PathException::WRITE) {
let rule = PathRule::new(RuleMode::Allow, "file-write*", path.into());
rule.write_to(&mut profile)?;
}
if exception.contains(PathException::EXECUTE) {
let rule = PathRule::new(RuleMode::Allow, "process-exec", path.into());
rule.write_to(&mut profile)?;
}
}
if self.net_exception {
profile.write_all(b"(allow network*)\n")?;
}
Ok(profile)
}
/// Revoke all access permisisons for a path.
///
/// This is necessary to grant more restrictive permissions to a child of a
/// directory which was previously granted permissions.
fn revoke_path_access(buffer: &mut Vec<u8>, path: &str) -> Result<()> {
let rule = PathRule::new(RuleMode::Deny, "file-read*", path.into());
rule.write_to(buffer)?;
let rule = PathRule::new(RuleMode::Deny, "file-write*", path.into());
rule.write_to(buffer)?;
let rule = PathRule::new(RuleMode::Deny, "process-exec", path.into());
rule.write_to(buffer)?;
Ok(())
}
}
struct PathRule {
mode: RuleMode,
access_type: &'static str,
path: String,
}
impl PathRule {
fn new(mode: RuleMode, access_type: &'static str, path: String) -> Self {
Self { mode, access_type, path }
}
/// Write this rule to a profile.
fn write_to(&self, buffer: &mut Vec<u8>) -> IoResult<()> {
buffer.write_all(b"(")?;
buffer.write_all(self.mode.as_str().as_bytes())?;
buffer.write_all(b" ")?;
buffer.write_all(self.access_type.as_bytes())?;
buffer.write_all(b" (subpath ")?;
buffer.write_all(self.path.as_bytes())?;
buffer.write_all(b"))\n")?;
Ok(())
}
}
/// Mode for a seatbelt rule.
enum RuleMode {
Allow,
Deny,
}
impl RuleMode {
fn as_str(&self) -> &str {
match self {
Self::Allow => "allow",
Self::Deny => "deny",
}
}
}
bitflags! {
/// Types of sandbox filesystem exceptions.
struct PathException: u8 {
const EXECUTE = 0b0001;
const WRITE = 0b0010;
const READ = 0b0100;
}
}
/// Escape a path: /tt/in\a"x -> "/tt/in\\a\"x"
fn escape_path(path: &Path) -> Result<String> {
// Canonicalize the incoming path to support relative paths.
// The `subpath` action only allows absolute paths.
let canonical_path =
fs::canonicalize(&path).map_err(|_| Error::InvalidPath(path.to_path_buf()))?;
let mut path_str = canonical_path
.into_os_string()
.into_string()
.map_err(|_| Error::InvalidPath(path.to_path_buf()))?;
// Paths in `subpath` expressions must not end with /.
while path_str.ends_with('/') && path_str != "/" {
String::pop(&mut path_str);
}
path_str = path_str.replace('"', r#"\""#);
path_str = path_str.replace('\\', r#"\\"#);
Ok(format!("\"{path_str}\""))
}
extern "C" {
fn sandbox_init(profile: *const i8, flags: u64, errorbuf: *mut *mut i8) -> i32;
fn sandbox_free_error(errorbuf: *mut i8);
}
================================================
FILE: src/process/linux.rs
================================================
//! Linux process implementation.
//!
//! Documentation in this module has been largely copied from [STD] and is
//! thus dual-licensed under MIT and Apache.
//!
//! [STD]: https://doc.rust-lang.org/std/process/index.html
use std::ffi::{OsStr, OsString};
use std::io::{self, Read, Write};
use std::mem;
use std::os::fd::{AsRawFd, OwnedFd, RawFd};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::process::ExitStatusExt;
pub use std::process::{ExitStatus, Output};
use rustix::fs::{Mode, OFlags};
use rustix::pipe::pipe;
use rustix::process::{Pid, Signal};
/// A process builder, providing fine-grained control
/// over how a new process should be spawned.
///
/// A default configuration can be generated using `Command::new(program)`,
/// where `program` gives a path to the program to be executed. Additional
/// builder methods allow the configuration to be changed (for example, by
/// adding arguments) prior to spawning:
///
/// ```no_run
/// use birdcage::process::Command;
///
/// Command::new("sh").arg("-c").arg("echo hello");
/// ```
pub struct Command {
program: OsString,
args: Vec<OsString>,
pub(crate) stdin: Stdio,
pub(crate) stdout: Stdio,
pub(crate) stderr: Stdio,
}
impl Command {
/// Constructs a new `Command` for launching the program at
/// path `program`, with the following default configuration:
///
/// * No arguments to the program
/// * Inherit the current process's working directory
/// * Inherit stdin/stdout/stderr
///
/// Builder methods are provided to change these defaults and
/// otherwise configure the process.
///
/// If `program` is not an absolute path, the `PATH` will be searched in
/// an OS-defined way.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use birdcage::process::Command;
///
/// Command::new("sh");
/// ```
pub fn new<S: AsRef<OsStr>>(program: S) -> Self {
let program = program.as_ref().to_os_string();
Self {
program,
stdout: Default::default(),
stderr: Default::default(),
stdin: Default::default(),
args: Default::default(),
}
}
/// Adds an argument to pass to the program.
///
/// Only one argument can be passed per use. So instead of:
///
/// ```no_run
/// # birdcage::process::Command::new("sh")
/// .arg("-C /path/to/repo")
/// # ;
/// ```
///
/// usage would be:
///
/// ```no_run
/// # birdcage::process::Command::new("sh")
/// .arg("-C")
/// .arg("/path/to/repo")
/// # ;
/// ```
///
/// To pass multiple arguments see [`args`].
///
/// [`args`]: Command::args
///
/// Note that the argument is not passed through a shell, but given
/// literally to the program. This means that shell syntax like quotes,
/// escaped characters, word splitting, glob patterns, variable
/// substitution, etc. have no effect.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use birdcage::process::Command;
///
/// Command::new("ls").arg("-l").arg("-a");
/// ```
pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
let arg = arg.as_ref().to_os_string();
self.args.push(arg);
self
}
/// Adds multiple arguments to pass to the program.
///
/// To pass a single argument see [`arg`].
///
/// [`arg`]: Command::arg
///
/// Note that the arguments are not passed through a shell, but given
/// literally to the program. This means that shell syntax like quotes,
/// escaped characters, word splitting, glob patterns, variable
/// substitution, etc. have no effect.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use birdcage::process::Command;
///
/// Command::new("ls").args(["-l", "-a"]);
/// ```
pub fn args<I, S>(&mut self, args: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
for arg in args {
let arg = arg.as_ref().to_os_string();
self.args.push(arg);
}
self
}
/// Configuration for the child process's standard input (stdin) handle.
///
/// Defaults to [`inherit`].
///
/// [`inherit`]: Stdio::inherit
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use birdcage::process::{Command, Stdio};
///
/// Command::new("ls").stdin(Stdio::null());
/// ```
pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
self.stdin = cfg.into();
self
}
/// Configuration for the child process's standard output (stdout) handle.
///
/// Defaults to [`inherit`].
///
/// [`inherit`]: Stdio::inherit
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use birdcage::process::{Command, Stdio};
///
/// Command::new("ls").stdout(Stdio::null());
/// ```
pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
self.stdout = cfg.into();
self
}
/// Configuration for the child process's standard error (stderr) handle.
///
/// Defaults to [`inherit`].
///
/// [`inherit`]: Stdio::inherit
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use birdcage::process::{Command, Stdio};
///
/// Command::new("ls").stderr(Stdio::null());
/// ```
pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
self.stderr = cfg.into();
self
}
/// Returns the path to the program that was given to [`Command::new`].
///
/// # Examples
///
/// ```
/// use birdcage::process::Command;
///
/// let cmd = Command::new("echo");
/// assert_eq!(cmd.get_program(), "echo");
/// ```
pub fn get_program(&self) -> &OsStr {
OsStr::from_bytes(self.program.as_bytes())
}
}
impl From<Command> for std::process::Command {
fn from(command: Command) -> Self {
let mut std_command = std::process::Command::new(command.program);
std_command.args(command.args);
let stdin: Option<std::process::Stdio> = command.stdin.into();
if let Some(stdin) = stdin {
std_command.stdin(stdin);
}
let stdout: Option<std::process::Stdio> = command.stdout.into();
if let Some(stdout) = stdout {
std_command.stdout(stdout);
}
let stderr: Option<std::process::Stdio> = command.stderr.into();
if let Some(stderr) = stderr {
std_command.stderr(stderr);
}
std_command
}
}
/// Representation of a running or exited child process.
///
/// This structure is used to represent and manage child processes. A child
/// process is created via the [`Command`] struct, which configures the
/// spawning process and can itself be constructed using a builder-style
/// interface.
///
/// There is no implementation of [`Drop`] for child processes,
/// so if you do not ensure the `Child` has exited then it will continue to
/// run, even after the `Child` handle to the child process has gone out of
/// scope.
///
/// Calling [`wait`] (or other functions that wrap around it) will make
/// the parent process wait until the child has actually exited before
/// continuing.
///
/// # Warning
///
/// On some systems, calling [`wait`] or similar is necessary for the OS to
/// release resources. A process that terminated but has not been waited on is
/// still around as a "zombie". Leaving too many zombies around may exhaust
/// global resources (for example process IDs).
///
/// Birdcage does *not* automatically wait on child processes (not even if the
/// `Child` is dropped), it is up to the application developer to do so. As a
/// consequence, dropping `Child` handles without waiting on them first is not
/// recommended in long-running applications.
///
/// # Examples
///
/// ```should_panic
/// use birdcage::process::Command;
/// use birdcage::{Birdcage, Sandbox};
///
/// let mut cmd = Command::new("/bin/cat");
/// cmd.arg("file.txt");
/// let mut child = Birdcage::new().spawn(cmd).expect("failed to execute child");
///
/// let ecode = child.wait().expect("failed to wait on child");
///
/// assert!(ecode.success());
/// ```
///
/// [`wait`]: Child::wait
pub struct Child {
/// The handle for writing to the child's standard input (stdin), if it
/// has been captured. You might find it helpful to do
///
/// ```compile_fail,E0425
/// let stdin = child.stdin.take().unwrap();
/// ```
///
/// to avoid partially moving the `child` and thus blocking yourself from
/// calling functions on `child` while using `stdin`.
pub stdin: Option<ChildStdin>,
/// The handle for reading from the child's standard output (stdout), if it
/// has been captured. You might find it helpful to do
///
/// ```compile_fail,E0425
/// let stdout = child.stdout.take().unwrap();
/// ```
///
/// to avoid partially moving the `child` and thus blocking yourself from
/// calling functions on `child` while using `stdout`.
pub stdout: Option<ChildStdout>,
/// The handle for reading from the child's standard error (stderr), if it
/// has been captured. You might find it helpful to do
///
/// ```compile_fail,E0425
/// let stderr = child.stderr.take().unwrap();
/// ```
///
/// to avoid partially moving the `child` and thus blocking yourself from
/// calling functions on `child` while using `stderr`.
pub stderr: Option<ChildStderr>,
exit_signal: OwnedFd,
pid: u32,
}
impl Child {
/// Create child from a process and its Stdio pipes.
pub(crate) fn new(
pid: i32,
exit_signal: OwnedFd,
stdin: Option<OwnedFd>,
stdout: Option<OwnedFd>,
stderr: Option<OwnedFd>,
) -> io::Result<Self> {
Ok(Self {
exit_signal,
pid: pid as u32,
stdin: stdin.map(ChildStdin::new).transpose()?,
stdout: stdout.map(ChildStdout::new).transpose()?,
stderr: stderr.map(ChildStderr::new).transpose()?,
})
}
/// Forces the child process to exit. If the child has already exited,
/// `Ok(())` is returned.
///
/// The mapping to [`ErrorKind`]s is not part of the compatibility contract
/// of the function.
///
/// This is equivalent to sending a SIGKILL.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use birdcage::process::Command;
/// use birdcage::{Birdcage, Sandbox};
///
/// let command = Command::new("yes");
/// if let Ok(mut child) = Birdcage::new().spawn(command) {
/// child.kill().expect("command couldn't be killed");
/// } else {
/// println!("yes command didn't start");
/// }
/// ```
///
/// [`ErrorKind`]: io::ErrorKind
/// [`InvalidInput`]: io::ErrorKind::InvalidInput
pub fn kill(&mut self) -> io::Result<()> {
let pid = Pid::from_raw(self.pid as i32).unwrap();
rustix::process::kill_process(pid, Signal::Kill)?;
Ok(())
}
/// Returns the OS-assigned process identifier associated with this child.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use birdcage::process::Command;
/// use birdcage::{Birdcage, Sandbox};
///
/// let command = Command::new("ls");
/// if let Ok(child) = Birdcage::new().spawn(command) {
/// println!("Child's ID is {}", child.id());
/// } else {
/// println!("ls command didn't start");
/// }
/// ```
pub fn id(&self) -> u32 {
self.pid
}
/// Waits for the child to exit completely, returning the status that it
/// exited with. This function will continue to have the same return value
/// after it has been called at least once.
///
/// The stdin handle to the child process, if any, will be closed
/// before waiting. This helps avoid deadlock: it ensures that the
/// child does not block waiting for input from the parent, while
/// the parent waits for the child to exit.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use birdcage::process::Command;
/// use birdcage::{Birdcage, Sandbox};
///
/// let mut command = Command::new("ls");
/// if let Ok(mut child) = Birdcage::new().spawn(command) {
/// child.wait().expect("command wasn't running");
/// println!("Child has finished its execution!");
/// } else {
/// println!("ls command didn't start");
/// }
/// ```
pub fn wait(&mut self) -> io::Result<ExitStatus> {
// Wait for child process to exit.
unsafe {
let mut status: libc::c_int = 0;
if libc::waitpid(self.pid as i32, &mut status, 0) == -1 {
Err(io::Error::last_os_error())
} else {
match self.exit_signal()? {
Some(exit_signal) => Ok(exit_signal),
None => Ok(ExitStatus::from_raw(status)),
}
}
}
}
/// Attempts to collect the exit status of the child if it has already
/// exited.
///
/// This function will not block the calling thread and will only
/// check to see if the child process has exited or not. If the child has
/// exited then on Unix the process ID is reaped. This function is
/// guaranteed to repeatedly return a successful exit status so long as the
/// child has already exited.
///
/// If the child has exited, then `Ok(Some(status))` is returned. If the
/// exit status is not available at this time then `Ok(None)` is returned.
/// If an error occurs, then that error is returned.
///
/// Note that unlike `wait`, this function will not attempt to drop stdin.
///
/// # Examples
///
/// Basic usage:
///
/// ```no_run
/// use birdcage::process::Command;
/// use birdcage::{Birdcage, Sandbox};
///
/// let cmd = Command::new("ls");
/// let mut child = Birdcage::new().spawn(cmd).unwrap();
///
/// match child.try_wait() {
/// Ok(Some(status)) => println!("exited with: {status}"),
/// Ok(None) => {
/// println!("status not ready yet, let's really wait");
/// let res = child.wait();
/// println!("result: {res:?}");
/// },
/// Err(e) => println!("error attempting to wait: {e}"),
/// }
/// ```
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
// Wait for child process to exit.
unsafe {
let mut status: libc::c_int = 0;
let pid = libc::waitpid(self.pid as i32, &mut status, libc::WNOHANG);
if pid == -1 {
Err(io::Error::last_os_error())
} else if pid == 0 {
Ok(None)
} else {
match self.exit_signal()? {
Some(exit_signal) => Ok(Some(exit_signal)),
None => Ok(Some(ExitStatus::from_raw(status))),
}
}
}
}
/// Simultaneously waits for the child to exit and collect all remaining
/// output on the stdout/stderr handles, returning an `Output`
/// instance.
///
/// The stdin handle to the child process, if any, will be closed
/// before waiting. This helps avoid deadlock: it ensures that the
/// child does not block waiting for input from the parent, while
/// the parent waits for the child to exit.
///
/// By default, stdin, stdout and stderr are inherited from the parent.
/// In order to capture the output into this `Result<Output>` it is
/// necessary to create new pipes between parent and child. Use
/// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.
///
/// # Examples
///
/// ```should_panic
/// use birdcage::process::{Command, Stdio};
/// use birdcage::{Birdcage, Sandbox};
///
/// let mut cmd = Command::new("/bin/cat");
/// cmd.arg("file.txt");
/// cmd.stdout(Stdio::piped());
/// let child = Birdcage::new().spawn(cmd).expect("failed to execute child");
///
/// let output = child.wait_with_output().expect("failed to wait on child");
///
/// assert!(output.status.success());
/// ```
pub fn wait_with_output(mut self) -> io::Result<Output> {
// Drop stdin, to avoid deadlocks.
let _ = self.stdin.take();
// Collect stdio buffers.
let reader = ChildReader::new(self.stdout.take(), self.stderr.take())?;
let (stdout, stderr) = reader.read()?;
// Wait for process termination.
let status = self.wait()?;
Ok(Output { status, stdout, stderr })
}
/// Get the child's exit signal.
fn exit_signal(&self) -> io::Result<Option<ExitStatus>> {
// Don't block when trying to read.
rustix::fs::fcntl_setfl(&self.exit_signal, OFlags::NONBLOCK)?;
// Read exit signal from pipe.
let mut bytes = [0; mem::size_of::<u32>()];
let read = match rustix::io::read(&self.exit_signal, &mut bytes) {
Ok(read) => read,
Err(err) if err.kind() == io::ErrorKind::WouldBlock => return Ok(None),
Err(err) => return Err(err.into()),
};
// Convert signal to exit status.
if read == mem::size_of::<u32>() {
let signal = u32::from_le_bytes(bytes);
// Exit signal are the lowest 7 bits of wstatus:
// https://github.com/torvalds/linux/blob/259f7d5e2baf87fcbb4fabc46526c9c47fed1914/tools/include/nolibc/types.h#L110
assert!(signal <= 0x7f);
Ok(Some(ExitStatus::from_raw(signal as i32)))
} else {
Ok(None)
}
}
}
/// Describes what to do with a standard I/O stream for a child process when
/// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].
///
/// [`stdin`]: Command::stdin
/// [`stdout`]: Command::stdout
/// [`stderr`]: Command::stderr
#[derive(Default)]
pub struct Stdio {
pub(crate) ty: StdioType,
}
impl Stdio {
/// A new pipe should be arranged to connect the parent and child processes.
///
/// # Examples
///
/// With stdout:
///
/// ```no_run
/// use birdcage::process::{Command, Stdio};
///
/// Command::new("echo").arg("Hello, world!").stdout(Stdio::piped());
/// ```
///
/// With stdin:
///
/// ```no_run
/// use std::io::Write;
///
/// use birdcage::process::{Command, Stdio};
/// use birdcage::{Birdcage, Sandbox};
///
/// let mut cmd = Command::new("rev");
/// cmd.stdin(Stdio::piped());
/// cmd.stdout(Stdio::piped());
/// let mut child = Birdcage::new().spawn(cmd).expect("Failed to spawn child process");
///
/// let mut stdin = child.stdin.take().expect("Failed to open stdin");
/// std::thread::spawn(move || {
/// stdin.write_all("Hello, world!".as_bytes()).expect("Failed to write to stdin");
/// });
///
/// let output = child.wait_with_output().expect("Failed to read stdout");
/// assert_eq!(String::from_utf8_lossy(&output.stdout), "!dlrow ,olleH");
/// ```
///
/// Writing more than a pipe buffer's worth of input to stdin without also
/// reading stdout and stderr at the same time may cause a deadlock.
/// This is an issue when running any program that doesn't guarantee that it
/// reads its entire stdin before writing more than a pipe buffer's
/// worth of output. The size of a pipe buffer varies on different
/// targets.
pub fn piped() -> Self {
Self { ty: StdioType::Piped }
}
/// The child inherits from the corresponding parent descriptor.
///
/// # Examples
///
/// ```no_run
/// use birdcage::process::{Command, Stdio};
///
/// let output = Command::new("echo").arg("Hello, world!").stdout(Stdio::inherit());
/// ```
pub fn inherit() -> Self {
Self { ty: StdioType::Inherit }
}
/// This stream will be ignored. This is the equivalent of attaching the
/// stream to `/dev/null`.
///
/// # Examples
///
/// ```no_run
/// use birdcage::process::{Command, Stdio};
///
/// let output = Command::new("echo").arg("Hello, world!").stdout(Stdio::null());
/// ```
pub fn null() -> Self {
Self { ty: StdioType::Null }
}
/// Create pipes necessary for the stdio type.
///
/// This will return the corresponding read and write FDs.
pub(crate) fn make_pipe(&self, stdin: bool) -> io::Result<(Option<OwnedFd>, Option<OwnedFd>)> {
match self.ty {
StdioType::Inherit | StdioType::Default => Ok((None, None)),
StdioType::Piped => {
let (rx, tx) = pipe()?;
Ok((Some(rx), Some(tx)))
},
StdioType::Null => {
let null_fd = rustix::fs::open("/dev/null", OFlags::RDWR, Mode::empty())?;
if stdin {
Ok((Some(null_fd), None))
} else {
Ok((None, Some(null_fd)))
}
},
}
}
}
impl From<Stdio> for Option<std::process::Stdio> {
fn from(stdio: Stdio) -> Option<std::process::Stdio> {
match stdio.ty {
StdioType::Default => None,
StdioType::Inherit => Some(std::process::Stdio::inherit()),
StdioType::Piped => Some(std::process::Stdio::piped()),
StdioType::Null => Some(std::process::Stdio::null()),
}
}
}
/// Type of parent/child I/O coupling.
#[derive(Default, Copy, Clone)]
pub(crate) enum StdioType {
#[default]
Default,
Piped,
Inherit,
Null,
}
/// A handle to a child process's standard input (stdin).
///
/// This struct is used in the [`stdin`] field on [`Child`].
///
/// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying
/// file handle will be closed. If the child process was blocked on input prior
/// to being dropped, it will become unblocked after dropping.
///
/// [`stdin`]: Child::stdin
/// [dropped]: Drop
pub struct ChildStdin {
fd: OwnedFd,
}
impl ChildStdin {
fn new(fd: OwnedFd) -> io::Result<Self> {
Ok(Self { fd })
}
}
impl Write for ChildStdin {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
rustix::io::write(&self.fd, buf).map_err(io::Error::from)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
/// A handle to a child process's standard output (stdout).
///
/// This struct is used in the [`stdout`] field on [`Child`].
///
/// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s
/// underlying file handle will be closed.
///
/// [`stdout`]: Child::stdout
/// [dropped]: Drop
pub struct ChildStdout {
fd: OwnedFd,
}
impl ChildStdout {
fn new(fd: OwnedFd) -> io::Result<Self> {
Ok(Self { fd })
}
}
impl Read for ChildStdout {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
rustix::io::read(&self.fd, buf).map_err(io::Error::from)
}
}
/// A handle to a child process's stderr.
///
/// This struct is used in the [`stderr`] field on [`Child`].
///
/// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s
/// underlying file handle will be closed.
///
/// [`stderr`]: Child::stderr
/// [dropped]: Drop
pub type ChildStderr = ChildStdout;
struct ChildReader {
poll_fds: Vec<libc::pollfd>,
stdout: Option<ChildStdout>,
stderr: Option<ChildStderr>,
stdout_buffer: Vec<u8>,
stderr_buffer: Vec<u8>,
}
impl ChildReader {
fn new(stdout: Option<ChildStdout>, stderr: Option<ChildStderr>) -> io::Result<Self> {
let mut poll_fds = Vec::new();
if let Some(stdout) = &stdout {
rustix::fs::fcntl_setfl(&stdout.fd, OFlags::NONBLOCK)?;
let fd = stdout.fd.as_raw_fd();
poll_fds.push(libc::pollfd { fd, events: libc::POLLIN, revents: 0 });
}
if let Some(stderr) = &stderr {
rustix::fs::fcntl_setfl(&stderr.fd, OFlags::NONBLOCK)?;
let fd = stderr.fd.as_raw_fd();
poll_fds.push(libc::pollfd { fd, events: libc::POLLIN, revents: 0 });
}
Ok(Self {
poll_fds,
stdout,
stderr,
stdout_buffer: Default::default(),
stderr_buffer: Default::default(),
})
}
/// Read stdout and stderr into buffers.
fn read(mut self) -> io::Result<(Vec<u8>, Vec<u8>)> {
while !self.poll_fds.is_empty() {
// Block for next FD readiness.
let result = unsafe { libc::poll(self.poll_fds.as_mut_ptr(), 2, -1) };
if result == -1 {
return Err(io::Error::last_os_error());
}
// Read from all FDs.
for i in (0..self.poll_fds.len()).rev() {
// Ignore FDs that aren't ready.
let poll_fd = &self.poll_fds[i];
if poll_fd.revents == 0 {
continue;
}
// Get stdio/buffer corresponding to the FD.
let (stdio, buffer) = self.stdio_from_fd(poll_fd.fd);
// Read all available data.
match stdio.read_to_end(buffer) {
Ok(_) => {
self.poll_fds.remove(i);
},
Err(err) if err.kind() == io::ErrorKind::WouldBlock => (),
Err(err) => return Err(err),
}
}
}
Ok((self.stdout_buffer, self.stderr_buffer))
}
/// Get the stdio handles corresponding to a FD.
fn stdio_from_fd(&mut self, fd: RawFd) -> (&mut ChildStdout, &mut Vec<u8>) {
match (self.stdout.as_mut(), self.stderr.as_mut()) {
(Some(stdout), _) if stdout.fd.as_raw_fd() == fd => (stdout, &mut self.stdout_buffer),
(_, Some(stderr)) if stderr.fd.as_raw_fd() == fd => (stderr, &mut self.stderr_buffer),
_ => unreachable!(),
}
}
}
================================================
FILE: src/process/macos.rs
================================================
//! macOS process implementation.
// We just re-export STD, since we can spawn this command directly.
pub use std::process::{
Child, ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus, Output, Stdio,
};
================================================
FILE: src/process/mod.rs
================================================
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "linux")]
pub use crate::process::linux::{
Child, ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus, Output, Stdio,
};
#[cfg(target_os = "macos")]
pub use crate::process::macos::{
Child, ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus, Output, Stdio,
};
gitextract_c3jrejhf/
├── .github/
│ ├── PULL_REQUEST_TEMPLATE.md
│ ├── dependabot.yml
│ └── workflows/
│ └── test.yml
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── Cargo.toml
├── LICENSE
├── README.md
├── SECURITY.md
├── examples/
│ └── sandbox.rs
├── integration/
│ ├── canonicalize.rs
│ ├── command_io.rs
│ ├── consistent_id_mappings.rs
│ ├── delete_before_lockdown.rs
│ ├── env.rs
│ ├── exec.rs
│ ├── exec_symlinked_dir.rs
│ ├── exec_symlinked_dirs_exec.rs
│ ├── exec_symlinked_file.rs
│ ├── fs.rs
│ ├── fs_broken_symlink.rs
│ ├── fs_null.rs
│ ├── fs_readonly.rs
│ ├── fs_restrict_child.rs
│ ├── fs_symlink.rs
│ ├── fs_symlink_dir.rs
│ ├── fs_symlink_dir_separate_perms.rs
│ ├── fs_write_also_read.rs
│ ├── full_env.rs
│ ├── full_sandbox.rs
│ ├── harness.rs
│ ├── missing_exception.rs
│ ├── net.rs
│ └── seccomp.rs
├── rustfmt.toml
└── src/
├── error.rs
├── lib.rs
├── linux/
│ ├── mod.rs
│ ├── namespaces.rs
│ └── seccomp.rs
├── macos.rs
└── process/
├── linux.rs
├── macos.rs
└── mod.rs
SYMBOL INDEX (176 symbols across 32 files)
FILE: examples/sandbox.rs
type Cli (line 12) | struct Cli {
function main (line 41) | fn main() -> Result<(), Box<dyn Error>> {
FILE: integration/canonicalize.rs
function setup (line 8) | pub fn setup(_tempdir: PathBuf) -> TestSetup {
function validate (line 15) | pub fn validate(_data: String) {
FILE: integration/command_io.rs
function main (line 11) | fn main() {}
function main (line 14) | fn main() {
function pipe_stdin_to_stdout (line 20) | fn pipe_stdin_to_stdout() {
function exit_signal (line 42) | fn exit_signal() {
FILE: integration/consistent_id_mappings.rs
type TestData (line 8) | struct TestData {
function setup (line 15) | pub fn setup(_tempdir: PathBuf) -> TestSetup {
function validate (line 30) | pub fn validate(data: String) {
FILE: integration/delete_before_lockdown.rs
function setup (line 8) | pub fn setup(_tempdir: PathBuf) -> TestSetup {
function validate (line 21) | pub fn validate(_data: String) {
FILE: integration/env.rs
function setup (line 8) | pub fn setup(_tempdir: PathBuf) -> TestSetup {
function validate (line 20) | pub fn validate(_data: String) {
FILE: integration/exec.rs
function setup (line 9) | pub fn setup(_tempdir: PathBuf) -> TestSetup {
function validate (line 16) | pub fn validate(_data: String) {
FILE: integration/exec_symlinked_dir.rs
type TestData (line 11) | struct TestData {
function setup (line 15) | pub fn setup(tempdir: PathBuf) -> TestSetup {
function validate (line 30) | pub fn validate(data: String) {
FILE: integration/exec_symlinked_dirs_exec.rs
type TestData (line 11) | struct TestData {
function setup (line 15) | pub fn setup(tempdir: PathBuf) -> TestSetup {
function validate (line 31) | pub fn validate(data: String) {
FILE: integration/exec_symlinked_file.rs
type TestData (line 12) | struct TestData {
function setup (line 16) | pub fn setup(tempdir: PathBuf) -> TestSetup {
function validate (line 33) | pub fn validate(data: String) {
FILE: integration/fs.rs
constant FILE_CONTENT (line 9) | const FILE_CONTENT: &str = "expected content";
type TestData (line 12) | struct TestData {
function setup (line 17) | pub fn setup(tempdir: PathBuf) -> TestSetup {
function validate (line 35) | pub fn validate(data: String) {
FILE: integration/fs_broken_symlink.rs
type TestData (line 12) | struct TestData {
function setup (line 16) | pub fn setup(tempdir: PathBuf) -> TestSetup {
function validate (line 42) | pub fn validate(data: String) {
FILE: integration/fs_null.rs
function setup (line 8) | pub fn setup(_tempdir: PathBuf) -> TestSetup {
function validate (line 16) | pub fn validate(_data: String) {
FILE: integration/fs_readonly.rs
constant FILE_CONTENT (line 9) | const FILE_CONTENT: &str = "expected content";
type TestData (line 12) | struct TestData {
function setup (line 16) | pub fn setup(tempdir: PathBuf) -> TestSetup {
function validate (line 32) | pub fn validate(data: String) {
FILE: integration/fs_restrict_child.rs
constant FILE_CONTENT (line 9) | const FILE_CONTENT: &str = "expected content";
type TestData (line 12) | struct TestData {
function setup (line 17) | pub fn setup(tempdir: PathBuf) -> TestSetup {
function validate (line 34) | pub fn validate(data: String) {
FILE: integration/fs_symlink.rs
constant FILE_CONTENT (line 10) | const FILE_CONTENT: &str = "expected content";
type TestData (line 13) | struct TestData {
function setup (line 18) | pub fn setup(tempdir: PathBuf) -> TestSetup {
function validate (line 44) | pub fn validate(data: String) {
FILE: integration/fs_symlink_dir.rs
constant FILE_CONTENT (line 10) | const FILE_CONTENT: &str = "expected content";
type TestData (line 13) | struct TestData {
function setup (line 17) | pub fn setup(tempdir: PathBuf) -> TestSetup {
function validate (line 35) | pub fn validate(data: String) {
FILE: integration/fs_symlink_dir_separate_perms.rs
constant FILE_CONTENT (line 10) | const FILE_CONTENT: &str = "expected content";
type TestData (line 13) | struct TestData {
function setup (line 17) | pub fn setup(tempdir: PathBuf) -> TestSetup {
function validate (line 36) | pub fn validate(data: String) {
FILE: integration/fs_write_also_read.rs
constant FILE_CONTENT (line 9) | const FILE_CONTENT: &str = "expected content";
type TestData (line 12) | struct TestData {
function setup (line 16) | pub fn setup(tempdir: PathBuf) -> TestSetup {
function validate (line 32) | pub fn validate(data: String) {
FILE: integration/full_env.rs
function setup (line 8) | pub fn setup(_tempdir: PathBuf) -> TestSetup {
function validate (line 19) | pub fn validate(_data: String) {
FILE: integration/full_sandbox.rs
type TestData (line 12) | struct TestData {
function setup (line 16) | pub fn setup(tempdir: PathBuf) -> TestSetup {
function validate (line 52) | pub fn validate(data: String) {
FILE: integration/harness.rs
constant TEST_DIR (line 34) | const TEST_DIR: &str = "integration";
type TestSetup (line 37) | pub struct TestSetup {
function main (line 42) | fn main() {
function spawn_tests (line 74) | fn spawn_tests() {
function run_setup (line 133) | fn run_setup(test_name: &str, tempdir: String, setup: &fn(PathBuf) -> Te...
FILE: integration/missing_exception.rs
function setup (line 8) | pub fn setup(_tempdir: PathBuf) -> TestSetup {
function validate (line 23) | pub fn validate(_data: String) {
FILE: integration/net.rs
function setup (line 8) | pub fn setup(_tempdir: PathBuf) -> TestSetup {
function validate (line 16) | pub fn validate(_data: String) {
FILE: integration/seccomp.rs
function setup (line 8) | pub fn setup(_tempdir: PathBuf) -> TestSetup {
function validate (line 12) | pub fn validate(_data: String) {
FILE: src/error.rs
type Result (line 15) | pub type Result<T> = StdResult<T, Error>;
type Error (line 19) | pub enum Error {
method from (line 59) | fn from(error: SeccompError) -> Self {
method from (line 66) | fn from(error: BackendError) -> Self {
method from (line 72) | fn from(error: IoError) -> Self {
method fmt (line 37) | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
FILE: src/lib.rs
type Birdcage (line 55) | pub type Birdcage = LinuxSandbox;
type Birdcage (line 62) | pub type Birdcage = MacSandbox;
type Sandbox (line 64) | pub trait Sandbox: Sized {
method new (line 66) | fn new() -> Self;
method add_exception (line 72) | fn add_exception(&mut self, exception: Exception) -> Result<&mut Self>;
method spawn (line 88) | fn spawn(self, sandboxee: Command) -> Result<Child>;
type Exception (line 96) | pub enum Exception {
function restrict_env_variables (line 120) | pub(crate) fn restrict_env_variables(exceptions: &[String]) {
FILE: src/linux/mod.rs
type LinuxSandbox (line 24) | pub struct LinuxSandbox {
method new (line 32) | fn new() -> Self {
method add_exception (line 36) | fn add_exception(&mut self, exception: Exception) -> Result<&mut Self> {
method spawn (line 49) | fn spawn(self, sandboxee: Command) -> Result<Child> {
function spawn_sandbox_init (line 114) | fn spawn_sandbox_init(init_arg: ProcessInitArg, allow_networking: bool) ...
function sandbox_init (line 158) | extern "C" fn sandbox_init(arg: *mut libc::c_void) -> libc::c_int {
function sandbox_init_inner (line 173) | fn sandbox_init_inner(mut init_arg: ProcessInitArg) -> io::Result<libc::...
type ProcessInitArg (line 244) | struct ProcessInitArg {
method new (line 268) | fn new(
type PathExceptions (line 300) | pub(crate) struct PathExceptions {
method update (line 313) | fn update(&mut self, path: PathBuf, write: bool, execute: bool) -> Res...
function absolute (line 360) | fn absolute(path: &Path) -> io::Result<PathBuf> {
function normalize_path (line 402) | fn normalize_path(path: &Path) -> PathBuf {
function path_has_symlinks (line 421) | fn path_has_symlinks(path: &Path) -> bool {
function thread_count (line 426) | fn thread_count() -> io::Result<usize> {
FILE: src/linux/namespaces.rs
constant NEW_ROOT (line 17) | const NEW_ROOT: &str = "/tmp/birdcage-root";
function setup_mount_namespace (line 23) | pub(crate) fn setup_mount_namespace(exceptions: PathExceptions) -> io::R...
function create_symlinks (line 99) | fn create_symlinks(new_root: &Path, symlinks: Vec<(PathBuf, PathBuf)>) -...
function copy_tree (line 129) | fn copy_tree(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> io::Result...
function mount_tmpfs (line 166) | fn mount_tmpfs(dst: &CStr) -> io::Result<()> {
function mount_proc (line 181) | pub fn mount_proc(dst: &CStr) -> io::Result<()> {
function bind_mount (line 196) | fn bind_mount(src: &CStr, dst: &CStr) -> io::Result<()> {
function update_mount_flags (line 209) | fn update_mount_flags(mount: &CStr, flags: MountAttrFlags) -> io::Result...
function deny_mount_propagation (line 231) | fn deny_mount_propagation() -> io::Result<()> {
function pivot_root (line 247) | fn pivot_root(new_root: &CStr, put_old: &CStr) -> io::Result<()> {
function umount (line 270) | fn umount(target: &CStr) -> io::Result<()> {
function create_user_namespace (line 283) | pub fn create_user_namespace(
function map_ids (line 305) | pub fn map_ids(
function unshare (line 320) | fn unshare(namespaces: Namespaces) -> io::Result<()> {
type MountAttr (line 355) | struct MountAttr {
FILE: src/linux/seccomp.rs
constant ARCH (line 13) | const ARCH: TargetArch = TargetArch::x86_64;
constant ARCH (line 15) | const ARCH: TargetArch = TargetArch::aarch64;
constant CLONE_NAMESPACE_FILTER (line 29) | const CLONE_NAMESPACE_FILTER: u32 = 0b01111110000000100000000000000000;
type SyscallFilter (line 36) | pub struct SyscallFilter;
method apply (line 40) | pub fn apply() -> Result<()> {
constant SYSCALL_WHITELIST (line 89) | const SYSCALL_WHITELIST: &[libc::c_long] = &[
FILE: src/macos.rs
type MacSandbox (line 34) | pub struct MacSandbox {
method update_path_exceptions (line 100) | fn update_path_exceptions(&mut self, path: PathBuf, exceptions: PathEx...
method create_profile (line 115) | fn create_profile(&self) -> Result<Vec<u8>> {
method revoke_path_access (line 151) | fn revoke_path_access(buffer: &mut Vec<u8>, path: &str) -> Result<()> {
method new (line 42) | fn new() -> Self {
method add_exception (line 46) | fn add_exception(&mut self, exception: Exception) -> Result<&mut Self> {
method spawn (line 68) | fn spawn(self, mut sandboxee: Command) -> Result<Child> {
type PathRule (line 165) | struct PathRule {
method new (line 172) | fn new(mode: RuleMode, access_type: &'static str, path: String) -> Self {
method write_to (line 177) | fn write_to(&self, buffer: &mut Vec<u8>) -> IoResult<()> {
type RuleMode (line 193) | enum RuleMode {
method as_str (line 199) | fn as_str(&self) -> &str {
function escape_path (line 217) | fn escape_path(path: &Path) -> Result<String> {
function sandbox_init (line 237) | fn sandbox_init(profile: *const i8, flags: u64, errorbuf: *mut *mut i8) ...
function sandbox_free_error (line 238) | fn sandbox_free_error(errorbuf: *mut i8);
FILE: src/process/linux.rs
type Command (line 33) | pub struct Command {
method new (line 64) | pub fn new<S: AsRef<OsStr>>(program: S) -> Self {
method arg (line 112) | pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
method args (line 138) | pub fn args<I, S>(&mut self, args: I) -> &mut Self
method stdin (line 165) | pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
method stdout (line 185) | pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
method stderr (line 205) | pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {
method get_program (line 220) | pub fn get_program(&self) -> &OsStr {
function from (line 226) | fn from(command: Command) -> Self {
type Child (line 293) | pub struct Child {
method new (line 333) | pub(crate) fn new(
method kill (line 375) | pub fn kill(&mut self) -> io::Result<()> {
method id (line 398) | pub fn id(&self) -> u32 {
method wait (line 427) | pub fn wait(&mut self) -> io::Result<ExitStatus> {
method try_wait (line 478) | pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
method wait_with_output (line 525) | pub fn wait_with_output(mut self) -> io::Result<Output> {
method exit_signal (line 540) | fn exit_signal(&self) -> io::Result<Option<ExitStatus>> {
type Stdio (line 574) | pub struct Stdio {
method piped (line 619) | pub fn piped() -> Self {
method inherit (line 632) | pub fn inherit() -> Self {
method null (line 646) | pub fn null() -> Self {
method make_pipe (line 653) | pub(crate) fn make_pipe(&self, stdin: bool) -> io::Result<(Option<Owne...
function from (line 673) | fn from(stdio: Stdio) -> Option<std::process::Stdio> {
type StdioType (line 685) | pub(crate) enum StdioType {
type ChildStdin (line 703) | pub struct ChildStdin {
method new (line 708) | fn new(fd: OwnedFd) -> io::Result<Self> {
method write (line 714) | fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
method flush (line 718) | fn flush(&mut self) -> io::Result<()> {
type ChildStdout (line 732) | pub struct ChildStdout {
method new (line 737) | fn new(fd: OwnedFd) -> io::Result<Self> {
method read (line 743) | fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
type ChildStderr (line 757) | pub type ChildStderr = ChildStdout;
type ChildReader (line 759) | struct ChildReader {
method new (line 768) | fn new(stdout: Option<ChildStdout>, stderr: Option<ChildStderr>) -> io...
method read (line 793) | fn read(mut self) -> io::Result<(Vec<u8>, Vec<u8>)> {
method stdio_from_fd (line 827) | fn stdio_from_fd(&mut self, fd: RawFd) -> (&mut ChildStdout, &mut Vec<...
Condensed preview — 45 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (171K chars).
[
{
"path": ".github/PULL_REQUEST_TEMPLATE.md",
"chars": 278,
"preview": "\n<!--\nBefore submitting a PR:\n\n1. Link the associated issue (i.e., `closes #<issueNum>` in description)\n2. Ensure that y"
},
{
"path": ".github/dependabot.yml",
"chars": 120,
"preview": "---\nversion: 2\nupdates:\n - package-ecosystem: \"github-actions\"\n directory: \"/\"\n schedule:\n interval: weekly\n"
},
{
"path": ".github/workflows/test.yml",
"chars": 2160,
"preview": "name: Test\n\non:\n # Allow running this workflow manually from the Actions tab\n workflow_dispatch:\n pull_request:\n pus"
},
{
"path": ".gitignore",
"chars": 20,
"preview": "/target\n/Cargo.lock\n"
},
{
"path": "CHANGELOG.md",
"chars": 2045,
"preview": "# Changelog\n\nNotable changes to Birdcage are documented in this file.\n\nThe sections should follow the order `Packaging`,"
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 5518,
"preview": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participa"
},
{
"path": "Cargo.toml",
"chars": 869,
"preview": "[package]\nname = \"birdcage\"\nversion = \"0.8.1\"\ndescription = \"Cross-platform embeddable sandbox\"\nauthors = [\"Phylum, Inc."
},
{
"path": "LICENSE",
"chars": 34369,
"preview": "GNU GENERAL PUBLIC LICENSE\nVersion 3, 29 June 2007\n\nCopyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>\n\nE"
},
{
"path": "README.md",
"chars": 2629,
"preview": "# Birdcage\n\n<div align=\"center\">\n\n[][license]\n[![Git"
},
{
"path": "SECURITY.md",
"chars": 419,
"preview": "# Security Policy\n\nPhylum was founded by a team of security researchers at heart, and we take the security of our toolin"
},
{
"path": "examples/sandbox.rs",
"chars": 1981,
"preview": "//! Sandbox arbitrary executables.\n\nuse std::error::Error;\nuse std::path::PathBuf;\n\nuse birdcage::process::Command;\nuse "
},
{
"path": "integration/canonicalize.rs",
"chars": 505,
"preview": "use std::fs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setup"
},
{
"path": "integration/command_io.rs",
"chars": 1714,
"preview": "use std::io::Write;\nuse std::os::unix::process::ExitStatusExt;\n\nuse birdcage::process::{Command, Stdio};\nuse birdcage::{"
},
{
"path": "integration/consistent_id_mappings.rs",
"chars": 997,
"preview": "use std::path::PathBuf;\nuse birdcage::{Birdcage, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\n"
},
{
"path": "integration/delete_before_lockdown.rs",
"chars": 572,
"preview": "use std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse tempfile::NamedTempFile;\n\nuse crate::TestSetu"
},
{
"path": "integration/env.rs",
"chars": 660,
"preview": "use std::path::PathBuf;\nuse std::env;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setu"
},
{
"path": "integration/exec.rs",
"chars": 664,
"preview": "use std::path::PathBuf;\nuse std::fs;\nuse std::process::Command;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crat"
},
{
"path": "integration/exec_symlinked_dir.rs",
"chars": 1207,
"preview": "use std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\nuse std::process::Command;\n\nuse birdcage::{Birdcage, Exception,"
},
{
"path": "integration/exec_symlinked_dirs_exec.rs",
"chars": 1222,
"preview": "use std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\nuse std::process::Command;\n\nuse birdcage::{Birdcage, Exception,"
},
{
"path": "integration/exec_symlinked_file.rs",
"chars": 1239,
"preview": "use std::fs;\nuse std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\nuse std::process::Command;\n\nuse birdcage::{Birdcag"
},
{
"path": "integration/fs.rs",
"chars": 1331,
"preview": "use std::fs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};"
},
{
"path": "integration/fs_broken_symlink.rs",
"chars": 1548,
"preview": "use std::fs::{self, File};\nuse std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\n\nuse birdcage::error::Error;\nuse bir"
},
{
"path": "integration/fs_null.rs",
"chars": 477,
"preview": "use std::path::PathBuf;\nuse std::fs;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setup"
},
{
"path": "integration/fs_readonly.rs",
"chars": 1135,
"preview": "use std::fs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};"
},
{
"path": "integration/fs_restrict_child.rs",
"chars": 1389,
"preview": "use std::fs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};"
},
{
"path": "integration/fs_symlink.rs",
"chars": 1714,
"preview": "use std::fs;\nuse std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse"
},
{
"path": "integration/fs_symlink_dir.rs",
"chars": 1250,
"preview": "use std::fs;\nuse std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse"
},
{
"path": "integration/fs_symlink_dir_separate_perms.rs",
"chars": 1376,
"preview": "use std::fs;\nuse std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse"
},
{
"path": "integration/fs_write_also_read.rs",
"chars": 1088,
"preview": "use std::fs::{self, File};\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserializ"
},
{
"path": "integration/full_env.rs",
"chars": 563,
"preview": "use std::path::PathBuf;\nuse std::env;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setu"
},
{
"path": "integration/full_sandbox.rs",
"chars": 2039,
"preview": "use std::net::TcpStream;\nuse std::path::PathBuf;\nuse std::process::Command;\nuse std::{env, fs};\n\nuse birdcage::{Birdcage"
},
{
"path": "integration/harness.rs",
"chars": 4904,
"preview": "use std::path::PathBuf;\nuse std::process::{self, Command, Stdio};\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\ntest_m"
},
{
"path": "integration/missing_exception.rs",
"chars": 697,
"preview": "use std::path::PathBuf;\n\nuse birdcage::error::Error;\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup"
},
{
"path": "integration/net.rs",
"chars": 465,
"preview": "use std::path::PathBuf;\nuse std::net::TcpStream;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup;\n\n"
},
{
"path": "integration/seccomp.rs",
"chars": 821,
"preview": "use std::path::PathBuf;\nuse std::ffi::CString;\n\nuse birdcage::{Birdcage, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setup("
},
{
"path": "rustfmt.toml",
"chars": 436,
"preview": "format_code_in_doc_comments = true\ngroup_imports = \"StdExternalCrate\"\nmatch_block_trailing_comma = true\ncondense_wildcar"
},
{
"path": "src/error.rs",
"chars": 1994,
"preview": "//! Sandboxing errors.\n\nuse std::error::Error as StdError;\nuse std::fmt::{self, Display, Formatter};\nuse std::io::Error "
},
{
"path": "src/lib.rs",
"chars": 3855,
"preview": "//! Birdcage sandbox.\n//!\n//! This crate provides a cross-platform API for an embedded sandbox for macOS\n//! and Linux.\n"
},
{
"path": "src/linux/mod.rs",
"chars": 14764,
"preview": "//! Linux sandboxing.\n\nuse std::collections::HashMap;\nuse std::ffi::CString;\nuse std::io::{Error as IoError, ErrorKind a"
},
{
"path": "src/linux/namespaces.rs",
"chars": 15756,
"preview": "//! Linux namespaces.\n\nuse std::cmp::Ordering;\nuse std::ffi::{CStr, CString};\nuse std::fs::{self, File};\nuse std::io::Er"
},
{
"path": "src/linux/seccomp.rs",
"chars": 11579,
"preview": "//! Seccomp system call filtering.\n\nuse std::collections::BTreeMap;\n\nuse seccompiler::{\n BpfProgram, SeccompAction, S"
},
{
"path": "src/macos.rs",
"chars": 7419,
"preview": "//! Linux sandboxing.\n//!\n//! This module implements sandboxing on macOS using `sandbox_init`.\n\nuse std::collections::Ha"
},
{
"path": "src/process/linux.rs",
"chars": 26448,
"preview": "//! Linux process implementation.\n//!\n//! Documentation in this module has been largely copied from [STD] and is\n//! thu"
},
{
"path": "src/process/macos.rs",
"chars": 215,
"preview": "//! macOS process implementation.\n\n// We just re-export STD, since we can spawn this command directly.\npub use std::proc"
},
{
"path": "src/process/mod.rs",
"chars": 377,
"preview": "#[cfg(target_os = \"linux\")]\nmod linux;\n#[cfg(target_os = \"macos\")]\nmod macos;\n\n#[cfg(target_os = \"linux\")]\npub use crate"
}
]
About this extraction
This page contains the full source code of the phylum-dev/birdcage GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 45 files (159.0 KB), approximately 40.2k tokens, and a symbol index with 176 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.