Metadata-Version: 2.4
Name: bandsox
Version: 2.8
Summary: Fast Firecracker microVM manager
Project-URL: Homepage, https://github.com/HACKE-RC/Bandsox/
Project-URL: Repository, https://github.com/HACKE-RC/Bandsox/
Author-email: rc <crretsim@gmail.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: cli,fastapi,firecracker,microvm,sandbox
Classifier: Environment :: Console
Classifier: Environment :: Web Environment
Classifier: Framework :: FastAPI
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Requires-Python: >=3.8
Requires-Dist: docker>=7.1.0
Requires-Dist: fastapi
Requires-Dist: pydantic
Requires-Dist: python-multipart
Requires-Dist: requests
Requires-Dist: requests-unixsocket
Requires-Dist: uvicorn
Requires-Dist: websockets
Description-Content-Type: text/markdown

# BandSox
<img width="100" height="200" alt="image" src="https://github.com/user-attachments/assets/d80944af-45ac-407d-b2f2-70c95d68be97"/>

Python library and CLI for managing Firecracker microVMs. Create, snapshot, and restore sandboxes from Docker images. Runs untrusted code or isolates workloads.

## Features

- Millisecond boot times via Firecracker
- Create VMs from Docker images (requires Python 3 in the image)
- Pause, resume, and snapshot VMs for instant restore
- Web dashboard with login, API key management, and terminal sessions
- CLI for all operations, including auth management
- Python API for scripting and integration
- TypeScript SDK for Node.js
- Vsock file transfers (100-10,000x faster than serial), with automatic serial fallback
- Optional authentication: API keys for programmatic access, session cookies for the dashboard. Off by default.

## Usage

### Quick start

Create a VM and run Python code:

```python
from bandsox.core import BandSox

bs = BandSox()
vm = bs.create_vm("python:3-alpine", enable_networking=False)

result = vm.exec_python_capture("print('Hello from VM!')")
print(result['stdout'])  # Hello from VM!

vm.stop()
```

### Python API

```python
from bandsox.core import BandSox

bs = BandSox()

# Create a VM from a Docker image (needs python preinstalled)
vm = bs.create_vm("python:3-alpine", name="test-vm")
print(f"VM started: {vm.vm_id}")

# Run a command
exit_code = vm.exec_command("echo Hello World > /root/hello.txt")

# Run Python code directly inside the VM
result = vm.exec_python_capture("print('Hello World')")
print(result['stdout'])  # Hello World

# Read a file
content = vm.get_file_contents("/root/hello.txt")
print(content)  # Hello World

vm.stop()
```

### Remote server usage

If the BandSox server is already running somewhere, point the Python client at it:

```python
from bandsox.core import BandSox

# With authentication
bs = BandSox("http://localhost:8000", headers={"Authorization": "Bearer bsx_your_key_here"})
vm = bs.create_vm("python:3-alpine", enable_networking=False)

result = vm.exec_python_capture("print('Hello from the server')")
print(result["stdout"])

vm.stop()
```

### Web dashboard

Start the server:

```bash
sudo python3 -m bandsox.cli serve --host 0.0.0.0 --port 8000
```

Visit `http://localhost:8000` to access the dashboard. Authentication is off by default -- see the [Authentication](#authentication) section to enable it.

### Authentication

Auth is off by default. All endpoints are open until you explicitly enable it.

To turn it on:

```bash
sudo bandsox auth init --storage /var/lib/sandbox
```

This creates `auth.json` in the storage directory and prints an admin password and API key. Save both -- the API key is only shown once. The CLI will offer to save the key to `~/.bandsox/credentials` for you.

Once enabled, BandSox uses two auth methods:

**API keys** for programmatic access (CLI, SDK, direct HTTP calls). Pass them as `Authorization: Bearer <key>` headers.

**Session cookies** for the browser dashboard. Log in with the admin password at `/login`. Sessions are signed tokens that survive server restarts.

To disable auth again, delete `auth.json` from the storage directory.

#### CLI auth commands

```bash
# Enable auth (generates password + API key)
sudo bandsox auth init --storage /var/lib/sandbox

# Set or reset the admin password
sudo bandsox auth set-password --storage /var/lib/sandbox

# Create a new API key
bandsox auth create-key my-key

# List and revoke keys
bandsox auth list-keys
bandsox auth revoke-key bsx_k_<id>
```

#### SDK auth

TypeScript:

```ts
const bs = new BandSox({
  baseUrl: "http://localhost:8000",
  headers: { Authorization: "Bearer bsx_your_key_here" },
});
```

Python:

```python
bs = BandSox("http://localhost:8000", headers={"Authorization": "Bearer bsx_your_key_here"})
```

### CLI

BandSox includes a CLI tool `bandsox` (or `python -m bandsox.cli`).

```bash
# Create a VM
sudo python3 -m bandsox.cli create ubuntu:latest --name my-vm

# Open a terminal
sudo python3 -m bandsox.cli terminal <vm_id>

# Start the server
sudo python3 -m bandsox.cli serve --host 0.0.0.0 --port 8000
```

## Vsock file transfers

BandSox uses vsock (Virtual Socket) for file transfers between host and guest.

### Performance

| File size | Speed    | Time   |
|-----------|----------|--------|
| 1 MB      | ~50 MB/s | < 0.1s |
| 10 MB     | ~80 MB/s | < 0.2s |
| 100 MB    | ~100 MB/s| < 1s   |
| 1 GB      | ~100 MB/s| < 10s  |

That's 100-10,000x faster than serial-based transfers.

### How it works

- Each VM gets a unique CID (Context ID) and port for vsock
- File operations use vsock when available, fall back to serial otherwise
- No VM pause required during transfers
- Vsock bridge is disconnected before snapshots; restores use per-VM isolation to avoid socket collisions

### Restore isolation

Restores mount per-VM vsock paths in a private mount namespace, so multiple restores from the same snapshot don't hit `EADDRINUSE`. The isolation root defaults to `/tmp/bsx` (override with `BANDSOX_VSOCK_ISOLATION_DIR`).

### Checking vsock status

In a running VM terminal:
```bash
# Check if vsock module is loaded
lsmod | grep vsock
# Should show: virtio_vsock

# Check kernel config
zcat /proc/config.gz | grep VSOCK
# Should see: CONFIG_VIRTIO_VSOCK=y or m
```

### Upgrading from older versions

VMs created before vsock support need to be recreated. See [`VSOCK_MIGRATION.md`](VSOCK_MIGRATION.md) for details.

## Prerequisites

- Linux with KVM support (bare metal or nested virtualization)
- [Firecracker](https://firecracker-microvm.github.io/) installed at `/usr/bin/firecracker`
- Python 3.8+
- `sudo` access (required for TAP device networking)
- Vsock kernel module (`virtio-vsock`) in the guest kernel for fast file transfers (optional, falls back to serial)

## Installation

### From PyPI

```bash
# Using pip
pip install bandsox

# Using uv
uv pip install bandsox
```

Then initialize the required artifacts:

```bash
bandsox init --rootfs-url ./bandsox-base.ext4
```

### From source

1. Clone the repo:

    ```bash
    git clone https://github.com/HACKE-RC/Bandsox.git
    cd bandsox
    ```

2. Install:

    ```bash
    pip install -e .
    ```

3. Initialize artifacts (kernel, CNI plugins, optional base rootfs):

    ```bash
    bandsox init --rootfs-url ./bandsox-base.ext4
    ```

    This downloads:
    - `vmlinux` (Firecracker kernel)
    - CNI plugins into `cni/bin/`
    - (Optional) a base rootfs `.ext4` into `storage/images/` when `--rootfs-url` is provided

    Default URLs are provided for kernel and CNI. For the rootfs, build one locally (instructions below) and point `--rootfs-url` to a local path or `file://` URL. Use `--skip-*` flags to omit specific downloads or `--force` to re-download.


## Web UI screenshots
#### Home page
<img width="1564" height="931" alt="image" src="https://github.com/user-attachments/assets/e3bba19c-dba5-4f5d-a5ef-e38df43bbee8" />

---

#### Details page
<img width="1446" height="852" alt="image" src="https://github.com/user-attachments/assets/135512d7-2212-49aa-9454-fa2ae2e918fc" />

##### File browser
###### Browse files inside the VM from the details page.
<img width="1618" height="852" alt="image" src="https://github.com/user-attachments/assets/13191fa2-5b2c-4935-a448-e5d8810a9a1e" />

##### Markdown viewer
###### Click the view button next to any `.md` file to open it in the viewer.
<img width="1261" height="369" alt="image" src="https://github.com/user-attachments/assets/54ca063a-9885-497c-b2be-83ef7180da52" />


---

#### Terminal
###### Open a terminal from the dashboard by clicking the terminal button.
<img width="613" height="219" alt="image" src="https://github.com/user-attachments/assets/2c0148bf-9820-431f-87c0-620c45d4bd03" />



## Architecture

BandSox has four main modules:

- `bandsox.core` -- manages VMs, snapshots, and CID/port allocation.
- `bandsox.vm` -- wraps the Firecracker process; handles config, networking, vsock bridge, and guest interaction.
- `bandsox.agent` -- a small Python agent injected into the VM that runs commands and transfers files (vsock or serial).
- `bandsox.server` -- FastAPI backend for the web dashboard and REST API, with built-in authentication.
- `bandsox.auth` -- optional authentication. When `auth.json` exists, enforces API key and session auth. Stores hashed keys and a signing secret. Sessions are HMAC-signed tokens (no server-side state). Rate-limits login attempts.

### Communication

Vsock (primary):
- VMs talk to the host via `AF_VSOCK` sockets
- Firecracker forwards vsock connections to Unix domain sockets

Serial (fallback):
- Used when vsock is unavailable (e.g., custom kernels without `virtio-vsock`)

### Storage layout

Default: `/var/lib/bandsox` (override with `BANDSOX_STORAGE` env var)

```
├── images/               # Rootfs ext4 images
├── snapshots/            # VM snapshots
├── sockets/              # Firecracker API sockets
├── metadata/             # VM metadata (including vsock_config)
├── auth.json             # API key hashes, admin password hash, session signing secret
├── cid_allocator.json    # CID allocation state
└── port_allocator.json   # Port allocation state
```

## Docs and API reference

- Full library, CLI, and HTTP endpoint reference: [`API_DOCUMENTATION.md`](API_DOCUMENTATION.md)
- Vsock migration guide: [`VSOCK_MIGRATION.md`](VSOCK_MIGRATION.md)
- Vsock restoration fix: [`VSOCK_RESTORATION_FIX.md`](VSOCK_RESTORATION_FIX.md)
- REST base path: `http://<host>:<port>/api` (all endpoints require auth -- see API docs)

## Building a local base rootfs

Build a minimal ext4 from a Docker image:

```bash
IMG=alpine:latest          # pick a base image with python if needed
OUT=bandsox-base.ext4
SIZE_MB=512                # increase for more disk
TMP=$(mktemp -d)

docker pull "$IMG"
CID=$(docker create "$IMG")
docker export "$CID" -o "$TMP/rootfs.tar"
docker rm "$CID"

dd if=/dev/zero of="$OUT" bs=1M count=$SIZE_MB
mkfs.ext4 -F "$OUT"
mkdir -p "$TMP/mnt"
sudo mount -o loop "$OUT" "$TMP/mnt"
sudo tar -xf "$TMP/rootfs.tar" -C "$TMP/mnt"

cat <<'EOF' | sudo tee "$TMP/mnt/init" >/dev/null
#!/bin/sh
export PATH=/usr/local/bin:/usr/bin:/bin:/sbin
mount -t proc proc /proc
mount -t sysfs sysfs /sys
mkdir -p /dev/pts
mount -t devpts devpts /dev/pts
P=$(command -v python3 || command -v python)
[ -z "$P" ] && exec /usr/local/bin/agent.py
exec "$P" /usr/local/bin/agent.py
EOF
sudo chmod +x "$TMP/mnt/init"

sudo mkdir -p "$TMP/mnt/usr/local/bin"
sudo cp bandsox/agent.py "$TMP/mnt/usr/local/bin/agent.py"
sudo chmod 755 "$TMP/mnt/usr/local/bin/agent.py"

sudo umount "$TMP/mnt"
sudo e2fsck -fy "$OUT"
sudo resize2fs -M "$OUT"   # optional: shrink to minimum
rm -rf "$TMP"
```

Use it with `bandsox init --rootfs-url ./bandsox-base.ext4`.

You can also skip the base rootfs entirely -- BandSox builds per-image rootfs on demand from Docker images when you call `bandsox create <image>`.

## Storage and artifacts

- Large artifacts (ext4 rootfs images, snapshots, `vmlinux`, CNI binaries) are not tracked in git. `bandsox init` downloads them into `storage/` and `cni/bin/`.
- Default storage path is `/var/lib/sandbox`; override with `BANDSOX_STORAGE` or `--storage`.
- You can pre-seed a base rootfs via `--rootfs-url file://...`, or let BandSox build per-image rootfs from Docker images on demand.

## Verification and testing

The `verification/` directory has smoke-test scripts:

- `verify_bandsox.py` -- general smoke test
- `verify_file_ops.py` -- file upload/download
- `verify_internet.py` -- network connectivity inside the VM

To run one:

```bash
sudo python3 verification/verify_bandsox.py
```

## License

Apache License 2.0



###### Note: This project wasn't supposed to be made public so it may have artifacts which make no sense. Please open issues so I can remove them.
