Compare commits
No commits in common. "master" and "v0.0.9" have entirely different histories.
@ -1,46 +0,0 @@
|
||||
name: Nix
|
||||
|
||||
on:
|
||||
- push
|
||||
- pull_request
|
||||
|
||||
jobs:
|
||||
tests:
|
||||
name: NixOS tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
|
||||
- name: Install Nix
|
||||
uses: cachix/install-nix-action@08dcb3a5e62fa31e2da3d490afc4176ef55ecd72 # v30
|
||||
with:
|
||||
# explicitly enable sandbox
|
||||
install_options: --daemon
|
||||
extra_nix_config: |
|
||||
sandbox = true
|
||||
system-features = nixos-test benchmark big-parallel kvm
|
||||
enable_kvm: true
|
||||
|
||||
- name: Ensure environment
|
||||
run: >-
|
||||
apt-get update && apt-get install -y sqlite3
|
||||
if: ${{ runner.os == 'Linux' }}
|
||||
|
||||
- name: Restore Nix store
|
||||
uses: nix-community/cache-nix-action@v5
|
||||
with:
|
||||
primary-key: nix-${{ runner.os }}-${{ hashFiles('**/*.nix') }}
|
||||
restore-prefixes-first-match: nix-${{ runner.os }}-
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
nix --print-build-logs --experimental-features 'nix-command flakes' flake check --all-systems
|
||||
nix build --out-link "result" --print-out-paths --print-build-logs .#checks.x86_64-linux.nixos-tests
|
||||
|
||||
- name: Upload test output
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: "result"
|
||||
path: result/*
|
||||
retention-days: 1
|
@ -1,4 +1,4 @@
|
||||
name: Create distribution
|
||||
name: release
|
||||
|
||||
on:
|
||||
push:
|
||||
@ -7,26 +7,8 @@ on:
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: node:16-bookworm-slim
|
||||
steps:
|
||||
- name: Get dependencies
|
||||
run: >-
|
||||
echo 'deb http://deb.debian.org/debian bookworm-backports main' >> /etc/apt/sources.list.d/backports.list &&
|
||||
apt-get update &&
|
||||
apt-get install -y
|
||||
acl
|
||||
git
|
||||
gcc
|
||||
pkg-config
|
||||
libwayland-dev
|
||||
wayland-protocols/bookworm-backports
|
||||
libxcb1-dev
|
||||
libacl1-dev
|
||||
if: ${{ runner.os == 'Linux' }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
@ -37,17 +19,24 @@ jobs:
|
||||
with:
|
||||
go-version: '>=1.23.0'
|
||||
|
||||
- name: Go generate
|
||||
- name: Get dependencies
|
||||
run: >-
|
||||
go generate ./...
|
||||
apt-get update &&
|
||||
apt-get install -y
|
||||
gcc
|
||||
pkg-config
|
||||
libacl1-dev
|
||||
if: ${{ runner.os == 'Linux' }}
|
||||
|
||||
- name: Build for release
|
||||
run: FORTIFY_VERSION='${{ github.ref_name }}' ./dist/release.sh
|
||||
- name: Build for Linux
|
||||
run: >-
|
||||
sh -c "go build -v -ldflags '-s -w -X main.Version=${{ github.ref_name }}' -o bin/fortify &&
|
||||
sha256sum --tag -b bin/fortify > bin/fortify.sha256"
|
||||
|
||||
- name: Release
|
||||
id: use-go-action
|
||||
uses: https://gitea.com/actions/release-action@main
|
||||
with:
|
||||
files: |-
|
||||
dist/fortify-**
|
||||
bin/**
|
||||
api_key: '${{secrets.RELEASE_TOKEN}}'
|
||||
|
@ -1,4 +1,4 @@
|
||||
name: Tests
|
||||
name: test
|
||||
|
||||
on:
|
||||
- push
|
||||
@ -6,29 +6,8 @@ on:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Go tests
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: node:16-bookworm-slim
|
||||
steps:
|
||||
- name: Enable backports
|
||||
run: >-
|
||||
echo 'deb http://deb.debian.org/debian bookworm-backports main' >> /etc/apt/sources.list.d/backports.list
|
||||
if: ${{ runner.os == 'Linux' }}
|
||||
|
||||
- name: Ensure environment
|
||||
run: >-
|
||||
apt-get update && apt-get install -y curl wget sudo libxml2
|
||||
if: ${{ runner.os == 'Linux' }}
|
||||
|
||||
- name: Get dependencies
|
||||
uses: awalsh128/cache-apt-pkgs-action@latest
|
||||
with:
|
||||
packages: acl git gcc pkg-config libwayland-dev wayland-protocols/bookworm-backports libxcb1-dev libacl1-dev
|
||||
version: 1.0
|
||||
#execute_install_scripts: true
|
||||
if: ${{ runner.os == 'Linux' }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
@ -39,24 +18,20 @@ jobs:
|
||||
with:
|
||||
go-version: '>=1.23.0'
|
||||
|
||||
- name: Go generate
|
||||
- name: Get dependencies
|
||||
run: >-
|
||||
go generate ./...
|
||||
apt-get update &&
|
||||
apt-get install -y
|
||||
gcc
|
||||
pkg-config
|
||||
libacl1-dev
|
||||
if: ${{ runner.os == 'Linux' }}
|
||||
|
||||
- name: Run tests
|
||||
run: >-
|
||||
go test ./...
|
||||
|
||||
- name: Build for test
|
||||
id: build-test
|
||||
- name: Build for Linux
|
||||
run: >-
|
||||
FORTIFY_VERSION="$(git rev-parse --short HEAD)"
|
||||
bash -c './dist/release.sh &&
|
||||
echo "rev=$FORTIFY_VERSION" >> $GITHUB_OUTPUT'
|
||||
|
||||
- name: Upload test build
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: "fortify-${{ steps.build-test.outputs.rev }}"
|
||||
path: dist/fortify-*
|
||||
retention-days: 1
|
||||
sh -c "go build -v -ldflags '-s -w -X main.Version=${{ github.ref_name }}' -o bin/fortify &&
|
||||
sha256sum --tag -b bin/fortify > bin/fortify.sha256"
|
||||
|
8
.gitignore
vendored
8
.gitignore
vendored
@ -22,10 +22,4 @@ go.work.sum
|
||||
# env file
|
||||
.env
|
||||
.idea
|
||||
.vscode
|
||||
|
||||
# go generate
|
||||
security-context-v1-protocol.*
|
||||
|
||||
# release
|
||||
/dist/fortify-*
|
||||
.vscode
|
183
README.md
183
README.md
@ -1,8 +1,7 @@
|
||||
Fortify
|
||||
=======
|
||||
|
||||
[![Go Reference](https://pkg.go.dev/badge/git.gensokyo.uk/security/fortify.svg)](https://pkg.go.dev/git.gensokyo.uk/security/fortify)
|
||||
[![Go Report Card](https://goreportcard.com/badge/git.gensokyo.uk/security/fortify)](https://goreportcard.com/report/git.gensokyo.uk/security/fortify)
|
||||
[![Go Reference](https://pkg.go.dev/badge/git.ophivana.moe/security/fortify.svg)](https://pkg.go.dev/git.ophivana.moe/security/fortify)
|
||||
|
||||
Lets you run graphical applications as another user in a confined environment with a nice NixOS
|
||||
module to configure target users and provide launchers and desktop files for your privileged user.
|
||||
@ -15,17 +14,24 @@ Why would you want this?
|
||||
|
||||
- It provides UID isolation on top of the standard application sandbox.
|
||||
|
||||
There are a few different things to set up for this to work:
|
||||
|
||||
- A set of users, each for a group of applications that should be allowed access to each other
|
||||
|
||||
- A tool to switch users, currently sudo and machinectl are supported.
|
||||
|
||||
- If you are running NixOS, the module in this repository can take care of launchers and desktop files in the privileged
|
||||
user's environment, as well as packages and extra home-manager configuration for target users.
|
||||
|
||||
If you have a flakes-enabled nix environment, you can try out the tool by running:
|
||||
|
||||
```shell
|
||||
nix run git+https://git.gensokyo.uk/security/fortify -- help
|
||||
nix run git+https://git.ophivana.moe/security/fortify -- -h
|
||||
```
|
||||
|
||||
## Module usage
|
||||
|
||||
The NixOS module currently requires home-manager to function correctly.
|
||||
|
||||
Full module documentation can be found [here](options.md).
|
||||
The NixOS module currently requires home-manager and impermanence to function correctly.
|
||||
|
||||
To use the module, import it into your configuration with
|
||||
|
||||
@ -35,7 +41,7 @@ To use the module, import it into your configuration with
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
|
||||
|
||||
fortify = {
|
||||
url = "git+https://git.gensokyo.uk/security/fortify";
|
||||
url = "git+https://git.ophivana.moe/security/fortify";
|
||||
|
||||
# Optional but recommended to limit the size of your system closure.
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
@ -62,101 +68,112 @@ This adds the `environment.fortify` option:
|
||||
{
|
||||
environment.fortify = {
|
||||
enable = true;
|
||||
stateDir = "/var/lib/persist/module/fortify";
|
||||
users = {
|
||||
alice = 0;
|
||||
nixos = 10;
|
||||
};
|
||||
user = "nixos";
|
||||
stateDir = "/var/lib/persist/module";
|
||||
target = {
|
||||
chronos = {
|
||||
launchers = {
|
||||
weechat.method = "sudo";
|
||||
claws-mail.capability.pulse = false;
|
||||
|
||||
apps = [
|
||||
{
|
||||
name = "chromium";
|
||||
id = "org.chromium.Chromium";
|
||||
packages = [ pkgs.chromium ];
|
||||
userns = true;
|
||||
mapRealUid = true;
|
||||
dbus = {
|
||||
system = {
|
||||
filter = true;
|
||||
talk = [
|
||||
"org.bluez"
|
||||
"org.freedesktop.Avahi"
|
||||
"org.freedesktop.UPower"
|
||||
];
|
||||
discord = {
|
||||
command = "vesktop --ozone-platform-hint=wayland";
|
||||
share = pkgs.vesktop;
|
||||
};
|
||||
session =
|
||||
f:
|
||||
f {
|
||||
|
||||
chromium.dbus = {
|
||||
configSystem = {
|
||||
filter = true;
|
||||
talk = [
|
||||
"org.bluez"
|
||||
"org.freedesktop.Avahi"
|
||||
"org.freedesktop.UPower"
|
||||
];
|
||||
};
|
||||
config = {
|
||||
filter = true;
|
||||
talk = [
|
||||
"org.freedesktop.DBus"
|
||||
"org.freedesktop.FileManager1"
|
||||
"org.freedesktop.Notifications"
|
||||
"org.freedesktop.ScreenSaver"
|
||||
"org.freedesktop.secrets"
|
||||
"org.kde.kwalletd5"
|
||||
"org.kde.kwalletd5"
|
||||
"org.kde.kwalletd6"
|
||||
];
|
||||
];
|
||||
own = [
|
||||
"org.chromium.Chromium.*"
|
||||
"org.mpris.MediaPlayer2.org.chromium.Chromium.*"
|
||||
"org.mpris.MediaPlayer2.chromium.*"
|
||||
];
|
||||
call = { };
|
||||
broadcast = { };
|
||||
call = {
|
||||
"org.freedesktop.portal.*" = "*";
|
||||
};
|
||||
broadcast = {
|
||||
"org.freedesktop.portal.*" = "@/org/freedesktop/portal/*";
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
{
|
||||
name = "claws-mail";
|
||||
id = "org.claws_mail.Claws-Mail";
|
||||
packages = [ pkgs.claws-mail ];
|
||||
gpu = false;
|
||||
capability.pulse = false;
|
||||
}
|
||||
{
|
||||
name = "weechat";
|
||||
packages = [ pkgs.weechat ];
|
||||
capability = {
|
||||
wayland = false;
|
||||
x11 = false;
|
||||
dbus = true;
|
||||
pulse = false;
|
||||
};
|
||||
}
|
||||
{
|
||||
name = "discord";
|
||||
id = "dev.vencord.Vesktop";
|
||||
packages = [ pkgs.vesktop ];
|
||||
share = pkgs.vesktop;
|
||||
command = "vesktop --ozone-platform-hint=wayland";
|
||||
userns = true;
|
||||
mapRealUid = true;
|
||||
capability.x11 = true;
|
||||
dbus = {
|
||||
session =
|
||||
f:
|
||||
f {
|
||||
talk = [ "org.kde.StatusNotifierWatcher" ];
|
||||
own = [ ];
|
||||
call = { };
|
||||
broadcast = { };
|
||||
};
|
||||
system.filter = true;
|
||||
};
|
||||
}
|
||||
{
|
||||
name = "looking-glass-client";
|
||||
groups = [ "plugdev" ];
|
||||
extraPaths = [
|
||||
{
|
||||
src = "/dev/shm/looking-glass";
|
||||
write = true;
|
||||
}
|
||||
packages = with pkgs; [
|
||||
weechat
|
||||
claws-mail
|
||||
vesktop
|
||||
chromium
|
||||
];
|
||||
persistence.directories = [
|
||||
".config/weechat"
|
||||
".claws-mail"
|
||||
".config/vesktop"
|
||||
];
|
||||
extraConfig = {
|
||||
programs.looking-glass-client.enable = true;
|
||||
};
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
* `enable` determines whether the module should be enabled or not. Useful when sharing configurations between graphical
|
||||
and headless systems. Defaults to `false`.
|
||||
|
||||
* `user` specifies the privileged user with access to fortified applications.
|
||||
|
||||
* `stateDir` is the path to your persistent storage location. It is directly passed through to the impermanence module.
|
||||
|
||||
* `target` is an attribute set of submodules, where the attribute name is the username of the unprivileged target user.
|
||||
|
||||
The available options are:
|
||||
|
||||
* `packages`, the list of packages to make available in the target user's environment.
|
||||
|
||||
* `persistence`, user persistence attribute set passed to impermanence.
|
||||
|
||||
* `extraConfig`, extra home-manager configuration for the target user.
|
||||
|
||||
* `launchers`, attribute set where the attribute name is the name of the launcher.
|
||||
|
||||
The available options are:
|
||||
|
||||
* `command`, the command to run as the target user. Defaults to launcher name.
|
||||
|
||||
* `dbus.config`, D-Bus proxy custom configuration.
|
||||
|
||||
* `dbus.configSystem`, D-Bus system bus custom configuration, null to disable.
|
||||
|
||||
* `dbus.id`, D-Bus application id, has no effect if `dbus.config` is set.
|
||||
|
||||
* `dbus.mpris`, whether to enable MPRIS defaults, has no effect if `dbus.config` is set.
|
||||
|
||||
* `capability.wayland`, whether to share the Wayland socket.
|
||||
|
||||
* `capability.x11`, whether to share the X11 socket and allow connection.
|
||||
|
||||
* `capability.dbus`, whether to proxy D-Bus.
|
||||
|
||||
* `capability.pulse`, whether to share the PulseAudio socket and cookie.
|
||||
|
||||
* `share`, package containing desktop/icon files. Defaults to launcher name.
|
||||
|
||||
* `method`, the launch method for the sandboxed program, can be `"fortify"`, `"fortify-sudo"`, `"sudo"`.
|
||||
|
19
acl/acl.go
19
acl/acl.go
@ -1,19 +0,0 @@
|
||||
// Package acl implements simple ACL manipulation via libacl.
|
||||
package acl
|
||||
|
||||
type Perms []Perm
|
||||
|
||||
func (ps Perms) String() string {
|
||||
var s = []byte("---")
|
||||
for _, p := range ps {
|
||||
switch p {
|
||||
case Read:
|
||||
s[0] = 'r'
|
||||
case Write:
|
||||
s[1] = 'w'
|
||||
case Execute:
|
||||
s[2] = 'x'
|
||||
}
|
||||
}
|
||||
return string(s)
|
||||
}
|
@ -1,156 +0,0 @@
|
||||
package acl_test
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type (
|
||||
getFAclInvocation struct {
|
||||
cmd *exec.Cmd
|
||||
val []*getFAclResp
|
||||
pe []error
|
||||
}
|
||||
|
||||
getFAclResp struct {
|
||||
typ fAclType
|
||||
cred int32
|
||||
val fAclPerm
|
||||
|
||||
raw []byte
|
||||
}
|
||||
|
||||
fAclPerm uintptr
|
||||
fAclType uint8
|
||||
)
|
||||
|
||||
const fAclBufSize = 16
|
||||
|
||||
const (
|
||||
fAclPermRead fAclPerm = 1 << iota
|
||||
fAclPermWrite
|
||||
fAclPermExecute
|
||||
)
|
||||
|
||||
const (
|
||||
fAclTypeUser fAclType = iota
|
||||
fAclTypeGroup
|
||||
fAclTypeMask
|
||||
fAclTypeOther
|
||||
)
|
||||
|
||||
func (c *getFAclInvocation) run(name string) error {
|
||||
if c.cmd != nil {
|
||||
panic("attempted to run twice")
|
||||
}
|
||||
|
||||
c.cmd = exec.Command("getfacl", "--omit-header", "--absolute-names", "--numeric", name)
|
||||
|
||||
scanErr := make(chan error, 1)
|
||||
if p, err := c.cmd.StdoutPipe(); err != nil {
|
||||
return err
|
||||
} else {
|
||||
go c.parse(p, scanErr)
|
||||
}
|
||||
|
||||
if err := c.cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return errors.Join(<-scanErr, c.cmd.Wait())
|
||||
}
|
||||
|
||||
func (c *getFAclInvocation) parse(pipe io.Reader, scanErr chan error) {
|
||||
c.val = make([]*getFAclResp, 0, 4+fAclBufSize)
|
||||
|
||||
s := bufio.NewScanner(pipe)
|
||||
for s.Scan() {
|
||||
fields := bytes.SplitN(s.Bytes(), []byte{':'}, 3)
|
||||
if len(fields) != 3 {
|
||||
continue
|
||||
}
|
||||
|
||||
resp := getFAclResp{}
|
||||
|
||||
switch string(fields[0]) {
|
||||
case "user":
|
||||
resp.typ = fAclTypeUser
|
||||
case "group":
|
||||
resp.typ = fAclTypeGroup
|
||||
case "mask":
|
||||
resp.typ = fAclTypeMask
|
||||
case "other":
|
||||
resp.typ = fAclTypeOther
|
||||
default:
|
||||
c.pe = append(c.pe, fmt.Errorf("unknown type %s", string(fields[0])))
|
||||
continue
|
||||
}
|
||||
|
||||
if len(fields[1]) == 0 {
|
||||
resp.cred = -1
|
||||
} else {
|
||||
if cred, err := strconv.Atoi(string(fields[1])); err != nil {
|
||||
c.pe = append(c.pe, err)
|
||||
continue
|
||||
} else {
|
||||
resp.cred = int32(cred)
|
||||
if resp.cred < 0 {
|
||||
c.pe = append(c.pe, fmt.Errorf("credential %d out of range", resp.cred))
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(fields[2]) != 3 {
|
||||
c.pe = append(c.pe, fmt.Errorf("invalid perm length %d", len(fields[2])))
|
||||
continue
|
||||
} else {
|
||||
switch fields[2][0] {
|
||||
case 'r':
|
||||
resp.val |= fAclPermRead
|
||||
case '-':
|
||||
default:
|
||||
c.pe = append(c.pe, fmt.Errorf("invalid perm %v", fields[2][0]))
|
||||
continue
|
||||
}
|
||||
switch fields[2][1] {
|
||||
case 'w':
|
||||
resp.val |= fAclPermWrite
|
||||
case '-':
|
||||
default:
|
||||
c.pe = append(c.pe, fmt.Errorf("invalid perm %v", fields[2][1]))
|
||||
continue
|
||||
}
|
||||
switch fields[2][2] {
|
||||
case 'x':
|
||||
resp.val |= fAclPermExecute
|
||||
case '-':
|
||||
default:
|
||||
c.pe = append(c.pe, fmt.Errorf("invalid perm %v", fields[2][2]))
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
resp.raw = make([]byte, len(s.Bytes()))
|
||||
copy(resp.raw, s.Bytes())
|
||||
c.val = append(c.val, &resp)
|
||||
}
|
||||
scanErr <- s.Err()
|
||||
}
|
||||
|
||||
func (r *getFAclResp) String() string {
|
||||
if r.raw != nil && len(r.raw) > 0 {
|
||||
return string(r.raw)
|
||||
}
|
||||
|
||||
return "(user-initialised resp value)"
|
||||
}
|
||||
|
||||
func (r *getFAclResp) equals(typ fAclType, cred int32, val fAclPerm) bool {
|
||||
return r.typ == typ && r.cred == cred && r.val == val
|
||||
}
|
125
acl/acl_test.go
125
acl/acl_test.go
@ -1,125 +0,0 @@
|
||||
package acl_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
)
|
||||
|
||||
const testFileName = "acl.test"
|
||||
|
||||
var (
|
||||
uid = os.Geteuid()
|
||||
cred = int32(os.Geteuid())
|
||||
)
|
||||
|
||||
func TestUpdatePerm(t *testing.T) {
|
||||
if os.Getenv("GO_TEST_SKIP_ACL") == "1" {
|
||||
t.Log("acl test skipped")
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
testFilePath := path.Join(t.TempDir(), testFileName)
|
||||
|
||||
if f, err := os.Create(testFilePath); err != nil {
|
||||
t.Fatalf("Create: error = %v", err)
|
||||
} else {
|
||||
if err = f.Close(); err != nil {
|
||||
t.Fatalf("Close: error = %v", err)
|
||||
}
|
||||
}
|
||||
defer func() {
|
||||
if err := os.Remove(testFilePath); err != nil {
|
||||
t.Fatalf("Remove: error = %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
cur := getfacl(t, testFilePath)
|
||||
|
||||
t.Run("default entry count", func(t *testing.T) {
|
||||
if len(cur) != 3 {
|
||||
t.Fatalf("unexpected test file acl length %d", len(cur))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("default clear mask", func(t *testing.T) {
|
||||
if err := acl.UpdatePerm(testFilePath, uid); err != nil {
|
||||
t.Fatalf("UpdatePerm: error = %v", err)
|
||||
}
|
||||
if cur = getfacl(t, testFilePath); len(cur) != 4 {
|
||||
t.Fatalf("UpdatePerm: %v", cur)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("default clear consistency", func(t *testing.T) {
|
||||
if err := acl.UpdatePerm(testFilePath, uid); err != nil {
|
||||
t.Fatalf("UpdatePerm: error = %v", err)
|
||||
}
|
||||
if val := getfacl(t, testFilePath); !reflect.DeepEqual(val, cur) {
|
||||
t.Fatalf("UpdatePerm: %v, want %v", val, cur)
|
||||
}
|
||||
})
|
||||
|
||||
testUpdate(t, testFilePath, "r--", cur, fAclPermRead, acl.Read)
|
||||
testUpdate(t, testFilePath, "-w-", cur, fAclPermWrite, acl.Write)
|
||||
testUpdate(t, testFilePath, "--x", cur, fAclPermExecute, acl.Execute)
|
||||
testUpdate(t, testFilePath, "-wx", cur, fAclPermWrite|fAclPermExecute, acl.Write, acl.Execute)
|
||||
testUpdate(t, testFilePath, "r-x", cur, fAclPermRead|fAclPermExecute, acl.Read, acl.Execute)
|
||||
testUpdate(t, testFilePath, "rw-", cur, fAclPermRead|fAclPermWrite, acl.Read, acl.Write)
|
||||
testUpdate(t, testFilePath, "rwx", cur, fAclPermRead|fAclPermWrite|fAclPermExecute, acl.Read, acl.Write, acl.Execute)
|
||||
}
|
||||
|
||||
func testUpdate(t *testing.T, testFilePath, name string, cur []*getFAclResp, val fAclPerm, perms ...acl.Perm) {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Cleanup(func() {
|
||||
if err := acl.UpdatePerm(testFilePath, uid); err != nil {
|
||||
t.Fatalf("UpdatePerm: error = %v", err)
|
||||
}
|
||||
if v := getfacl(t, testFilePath); !reflect.DeepEqual(v, cur) {
|
||||
t.Fatalf("UpdatePerm: %v, want %v", v, cur)
|
||||
}
|
||||
})
|
||||
|
||||
if err := acl.UpdatePerm(testFilePath, uid, perms...); err != nil {
|
||||
t.Fatalf("UpdatePerm: error = %v", err)
|
||||
}
|
||||
r := respByCred(getfacl(t, testFilePath), fAclTypeUser, cred)
|
||||
if r == nil {
|
||||
t.Fatalf("UpdatePerm did not add an ACL entry")
|
||||
}
|
||||
if !r.equals(fAclTypeUser, cred, val) {
|
||||
t.Fatalf("UpdatePerm(%s) = %s", name, r)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func getfacl(t *testing.T, name string) []*getFAclResp {
|
||||
c := new(getFAclInvocation)
|
||||
if err := c.run(name); err != nil {
|
||||
t.Fatalf("getfacl: error = %v", err)
|
||||
}
|
||||
if len(c.pe) != 0 {
|
||||
t.Errorf("errors encountered parsing getfacl output\n%s", errors.Join(c.pe...).Error())
|
||||
}
|
||||
return c.val
|
||||
}
|
||||
|
||||
func respByCred(v []*getFAclResp, typ fAclType, cred int32) *getFAclResp {
|
||||
j := -1
|
||||
for i, r := range v {
|
||||
if r.typ == typ && r.cred == cred {
|
||||
if j != -1 {
|
||||
panic("invalid acl")
|
||||
}
|
||||
j = i
|
||||
}
|
||||
}
|
||||
if j == -1 {
|
||||
return nil
|
||||
}
|
||||
return v[j]
|
||||
}
|
163
acl/c.go
163
acl/c.go
@ -1,95 +1,50 @@
|
||||
package acl
|
||||
|
||||
import "C"
|
||||
import (
|
||||
"errors"
|
||||
"runtime"
|
||||
"fmt"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
/*
|
||||
#cgo linux pkg-config: libacl
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <sys/acl.h>
|
||||
#include <acl/libacl.h>
|
||||
|
||||
static acl_t _go_acl_get_file(const char *path_p, acl_type_t type) {
|
||||
acl_t acl = acl_get_file(path_p, type);
|
||||
free((void *)path_p);
|
||||
return acl;
|
||||
}
|
||||
|
||||
static int _go_acl_set_file(const char *path_p, acl_type_t type, acl_t acl) {
|
||||
if (acl_valid(acl) != 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
int ret = acl_set_file(path_p, type, acl);
|
||||
free((void *)path_p);
|
||||
return ret;
|
||||
}
|
||||
*/
|
||||
//#include <stdlib.h>
|
||||
//#include <sys/acl.h>
|
||||
//#include <acl/libacl.h>
|
||||
//#cgo linux LDFLAGS: -lacl
|
||||
import "C"
|
||||
|
||||
func getFile(name string, t C.acl_type_t) (*ACL, error) {
|
||||
a, err := C._go_acl_get_file(C.CString(name), t)
|
||||
type acl struct {
|
||||
val C.acl_t
|
||||
freed bool
|
||||
}
|
||||
|
||||
func aclGetFile(path string, t C.acl_type_t) (*acl, error) {
|
||||
p := C.CString(path)
|
||||
a, err := C.acl_get_file(p, t)
|
||||
C.free(unsafe.Pointer(p))
|
||||
|
||||
if errors.Is(err, syscall.ENODATA) {
|
||||
err = nil
|
||||
}
|
||||
|
||||
return newACL(a), err
|
||||
return &acl{val: a, freed: false}, err
|
||||
}
|
||||
|
||||
func (acl *ACL) setFile(name string, t C.acl_type_t) error {
|
||||
_, err := C._go_acl_set_file(C.CString(name), t, acl.acl)
|
||||
func (a *acl) setFile(path string, t C.acl_type_t) error {
|
||||
if C.acl_valid(a.val) != 0 {
|
||||
return fmt.Errorf("invalid acl")
|
||||
}
|
||||
|
||||
p := C.CString(path)
|
||||
_, err := C.acl_set_file(p, t, a.val)
|
||||
C.free(unsafe.Pointer(p))
|
||||
return err
|
||||
}
|
||||
|
||||
func newACL(a C.acl_t) *ACL {
|
||||
acl := &ACL{a}
|
||||
runtime.SetFinalizer(acl, (*ACL).free)
|
||||
return acl
|
||||
}
|
||||
|
||||
type ACL struct {
|
||||
acl C.acl_t
|
||||
}
|
||||
|
||||
func (acl *ACL) free() {
|
||||
C.acl_free(unsafe.Pointer(acl.acl))
|
||||
|
||||
// no need for a finalizer anymore
|
||||
runtime.SetFinalizer(acl, nil)
|
||||
}
|
||||
|
||||
const (
|
||||
Read = C.ACL_READ
|
||||
Write = C.ACL_WRITE
|
||||
Execute = C.ACL_EXECUTE
|
||||
|
||||
TypeDefault = C.ACL_TYPE_DEFAULT
|
||||
TypeAccess = C.ACL_TYPE_ACCESS
|
||||
|
||||
UndefinedTag = C.ACL_UNDEFINED_TAG
|
||||
UserObj = C.ACL_USER_OBJ
|
||||
User = C.ACL_USER
|
||||
GroupObj = C.ACL_GROUP_OBJ
|
||||
Group = C.ACL_GROUP
|
||||
Mask = C.ACL_MASK
|
||||
Other = C.ACL_OTHER
|
||||
)
|
||||
|
||||
type (
|
||||
Perm C.acl_perm_t
|
||||
)
|
||||
|
||||
func (acl *ACL) removeEntry(tt C.acl_tag_t, tq int) error {
|
||||
func (a *acl) removeEntry(tt C.acl_tag_t, tq int) error {
|
||||
var e C.acl_entry_t
|
||||
|
||||
// get first entry
|
||||
if r, err := C.acl_get_entry(acl.acl, C.ACL_FIRST_ENTRY, &e); err != nil {
|
||||
if r, err := C.acl_get_entry(a.val, C.ACL_FIRST_ENTRY, &e); err != nil {
|
||||
return err
|
||||
} else if r == 0 {
|
||||
// return on acl with no entries
|
||||
@ -97,7 +52,7 @@ func (acl *ACL) removeEntry(tt C.acl_tag_t, tq int) error {
|
||||
}
|
||||
|
||||
for {
|
||||
if r, err := C.acl_get_entry(acl.acl, C.ACL_NEXT_ENTRY, &e); err != nil {
|
||||
if r, err := C.acl_get_entry(a.val, C.ACL_NEXT_ENTRY, &e); err != nil {
|
||||
return err
|
||||
} else if r == 0 {
|
||||
// return on drained acl
|
||||
@ -129,68 +84,16 @@ func (acl *ACL) removeEntry(tt C.acl_tag_t, tq int) error {
|
||||
|
||||
// delete on match
|
||||
if t == tt && q == tq {
|
||||
_, err := C.acl_delete_entry(acl.acl, e)
|
||||
_, err := C.acl_delete_entry(a.val, e)
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func UpdatePerm(name string, uid int, perms ...Perm) error {
|
||||
// read acl from file
|
||||
a, err := getFile(name, TypeAccess)
|
||||
if err != nil {
|
||||
return err
|
||||
func (a *acl) free() {
|
||||
if a.freed {
|
||||
panic("acl already freed")
|
||||
}
|
||||
// free acl on return if get is successful
|
||||
defer a.free()
|
||||
|
||||
// remove existing entry
|
||||
if err = a.removeEntry(User, uid); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// create new entry if perms are passed
|
||||
if len(perms) > 0 {
|
||||
// create new acl entry
|
||||
var e C.acl_entry_t
|
||||
if _, err = C.acl_create_entry(&a.acl, &e); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// get perm set of new entry
|
||||
var p C.acl_permset_t
|
||||
if _, err = C.acl_get_permset(e, &p); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// add target perms
|
||||
for _, perm := range perms {
|
||||
if _, err = C.acl_add_perm(p, C.acl_perm_t(perm)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// set perm set to new entry
|
||||
if _, err = C.acl_set_permset(e, p); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// set user tag to new entry
|
||||
if _, err = C.acl_set_tag_type(e, User); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// set qualifier (uid) to new entry
|
||||
if _, err = C.acl_set_qualifier(e, unsafe.Pointer(&uid)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// calculate mask after update
|
||||
if _, err = C.acl_calc_mask(&a.acl); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// write acl to file
|
||||
return a.setFile(name, TypeAccess)
|
||||
C.acl_free(unsafe.Pointer(a.val))
|
||||
a.freed = true
|
||||
}
|
||||
|
106
acl/export.go
Normal file
106
acl/export.go
Normal file
@ -0,0 +1,106 @@
|
||||
package acl
|
||||
|
||||
import "unsafe"
|
||||
|
||||
//#include <stdlib.h>
|
||||
//#include <sys/acl.h>
|
||||
//#include <acl/libacl.h>
|
||||
//#cgo linux LDFLAGS: -lacl
|
||||
import "C"
|
||||
|
||||
const (
|
||||
Read = C.ACL_READ
|
||||
Write = C.ACL_WRITE
|
||||
Execute = C.ACL_EXECUTE
|
||||
|
||||
TypeDefault = C.ACL_TYPE_DEFAULT
|
||||
TypeAccess = C.ACL_TYPE_ACCESS
|
||||
|
||||
UndefinedTag = C.ACL_UNDEFINED_TAG
|
||||
UserObj = C.ACL_USER_OBJ
|
||||
User = C.ACL_USER
|
||||
GroupObj = C.ACL_GROUP_OBJ
|
||||
Group = C.ACL_GROUP
|
||||
Mask = C.ACL_MASK
|
||||
Other = C.ACL_OTHER
|
||||
)
|
||||
|
||||
type (
|
||||
Perm C.acl_perm_t
|
||||
Perms []Perm
|
||||
)
|
||||
|
||||
func (ps Perms) String() string {
|
||||
var s = []byte("---")
|
||||
for _, p := range ps {
|
||||
switch p {
|
||||
case Read:
|
||||
s[0] = 'r'
|
||||
case Write:
|
||||
s[1] = 'w'
|
||||
case Execute:
|
||||
s[2] = 'x'
|
||||
}
|
||||
}
|
||||
return string(s)
|
||||
}
|
||||
|
||||
func UpdatePerm(path string, uid int, perms ...Perm) error {
|
||||
// read acl from file
|
||||
a, err := aclGetFile(path, TypeAccess)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// free acl on return if get is successful
|
||||
defer a.free()
|
||||
|
||||
// remove existing entry
|
||||
if err = a.removeEntry(User, uid); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// create new entry if perms are passed
|
||||
if len(perms) > 0 {
|
||||
// create new acl entry
|
||||
var e C.acl_entry_t
|
||||
if _, err = C.acl_create_entry(&a.val, &e); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// get perm set of new entry
|
||||
var p C.acl_permset_t
|
||||
if _, err = C.acl_get_permset(e, &p); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// add target perms
|
||||
for _, perm := range perms {
|
||||
if _, err = C.acl_add_perm(p, C.acl_perm_t(perm)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// set perm set to new entry
|
||||
if _, err = C.acl_set_permset(e, p); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// set user tag to new entry
|
||||
if _, err = C.acl_set_tag_type(e, User); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// set qualifier (uid) to new entry
|
||||
if _, err = C.acl_set_qualifier(e, unsafe.Pointer(&uid)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// calculate mask after update
|
||||
if _, err = C.acl_calc_mask(&a.val); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// write acl to file
|
||||
return a.setFile(path, TypeAccess)
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
package shim0
|
||||
|
||||
import (
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
)
|
||||
|
||||
const Env = "FORTIFY_SHIM"
|
||||
|
||||
type Payload struct {
|
||||
// child full argv
|
||||
Argv []string
|
||||
// bwrap, target full exec path
|
||||
Exec [2]string
|
||||
// bwrap config
|
||||
Bwrap *bwrap.Config
|
||||
// sync fd
|
||||
Sync *uintptr
|
||||
|
||||
// verbosity pass through
|
||||
Verbose bool
|
||||
}
|
@ -1,137 +0,0 @@
|
||||
package shim
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
shim0 "git.gensokyo.uk/security/fortify/cmd/fshim/ipc"
|
||||
"git.gensokyo.uk/security/fortify/internal"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/proc"
|
||||
)
|
||||
|
||||
const shimSetupTimeout = 5 * time.Second
|
||||
|
||||
// used by the parent process
|
||||
|
||||
type Shim struct {
|
||||
// user switcher process
|
||||
cmd *exec.Cmd
|
||||
// uid of shim target user
|
||||
uid uint32
|
||||
// string representation of application id
|
||||
aid string
|
||||
// string representation of supplementary group ids
|
||||
supp []string
|
||||
// fallback exit notifier with error returned killing the process
|
||||
killFallback chan error
|
||||
// shim setup payload
|
||||
payload *shim0.Payload
|
||||
}
|
||||
|
||||
func New(uid uint32, aid string, supp []string, payload *shim0.Payload) *Shim {
|
||||
return &Shim{uid: uid, aid: aid, supp: supp, payload: payload}
|
||||
}
|
||||
|
||||
func (s *Shim) String() string {
|
||||
if s.cmd == nil {
|
||||
return "(unused shim manager)"
|
||||
}
|
||||
return s.cmd.String()
|
||||
}
|
||||
|
||||
func (s *Shim) Unwrap() *exec.Cmd {
|
||||
return s.cmd
|
||||
}
|
||||
|
||||
func (s *Shim) WaitFallback() chan error {
|
||||
return s.killFallback
|
||||
}
|
||||
|
||||
func (s *Shim) Start() (*time.Time, error) {
|
||||
// start user switcher process and save time
|
||||
var fsu string
|
||||
if p, ok := internal.Check(internal.Fsu); !ok {
|
||||
fmsg.Fatal("invalid fsu path, this copy of fshim is not compiled correctly")
|
||||
panic("unreachable")
|
||||
} else {
|
||||
fsu = p
|
||||
}
|
||||
s.cmd = exec.Command(fsu)
|
||||
|
||||
var encoder *gob.Encoder
|
||||
if fd, e, err := proc.Setup(&s.cmd.ExtraFiles); err != nil {
|
||||
return nil, fmsg.WrapErrorSuffix(err,
|
||||
"cannot create shim setup pipe:")
|
||||
} else {
|
||||
encoder = e
|
||||
s.cmd.Env = []string{
|
||||
shim0.Env + "=" + strconv.Itoa(fd),
|
||||
"FORTIFY_APP_ID=" + s.aid,
|
||||
}
|
||||
}
|
||||
|
||||
if len(s.supp) > 0 {
|
||||
fmsg.VPrintf("attaching supplementary group ids %s", s.supp)
|
||||
s.cmd.Env = append(s.cmd.Env, "FORTIFY_GROUPS="+strings.Join(s.supp, " "))
|
||||
}
|
||||
s.cmd.Stdin, s.cmd.Stdout, s.cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
s.cmd.Dir = "/"
|
||||
|
||||
// pass sync fd if set
|
||||
if s.payload.Bwrap.Sync() != nil {
|
||||
fd := proc.ExtraFile(s.cmd, s.payload.Bwrap.Sync())
|
||||
s.payload.Sync = &fd
|
||||
}
|
||||
|
||||
fmsg.VPrintln("starting shim via fsu:", s.cmd)
|
||||
fmsg.Suspend() // withhold messages to stderr
|
||||
if err := s.cmd.Start(); err != nil {
|
||||
return nil, fmsg.WrapErrorSuffix(err,
|
||||
"cannot start fsu:")
|
||||
}
|
||||
startTime := time.Now().UTC()
|
||||
|
||||
// kill shim if something goes wrong and an error is returned
|
||||
s.killFallback = make(chan error, 1)
|
||||
killShim := func() {
|
||||
if err := s.cmd.Process.Signal(os.Interrupt); err != nil {
|
||||
s.killFallback <- err
|
||||
}
|
||||
}
|
||||
defer func() { killShim() }()
|
||||
|
||||
// take alternative exit path on signal
|
||||
sig := make(chan os.Signal, 2)
|
||||
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
||||
go func() {
|
||||
v := <-sig
|
||||
fmsg.Printf("got %s after program start", v)
|
||||
s.killFallback <- nil
|
||||
signal.Ignore(syscall.SIGINT, syscall.SIGTERM)
|
||||
}()
|
||||
|
||||
shimErr := make(chan error)
|
||||
go func() { shimErr <- encoder.Encode(s.payload) }()
|
||||
|
||||
select {
|
||||
case err := <-shimErr:
|
||||
if err != nil {
|
||||
return &startTime, fmsg.WrapErrorSuffix(err,
|
||||
"cannot transmit shim config:")
|
||||
}
|
||||
killShim = func() {}
|
||||
case <-time.After(shimSetupTimeout):
|
||||
return &startTime, fmsg.WrapError(errors.New("timed out waiting for shim"),
|
||||
"timed out waiting for shim")
|
||||
}
|
||||
|
||||
return &startTime, nil
|
||||
}
|
@ -1,145 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"syscall"
|
||||
|
||||
init0 "git.gensokyo.uk/security/fortify/cmd/finit/ipc"
|
||||
shim "git.gensokyo.uk/security/fortify/cmd/fshim/ipc"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/internal"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/proc"
|
||||
)
|
||||
|
||||
// everything beyond this point runs as unconstrained target user
|
||||
// proceed with caution!
|
||||
|
||||
func main() {
|
||||
// sharing stdout with fortify
|
||||
// USE WITH CAUTION
|
||||
fmsg.SetPrefix("shim")
|
||||
|
||||
// setting this prevents ptrace
|
||||
if err := internal.PR_SET_DUMPABLE__SUID_DUMP_DISABLE(); err != nil {
|
||||
fmsg.Fatalf("cannot set SUID_DUMP_DISABLE: %s", err)
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
// re-exec
|
||||
if len(os.Args) > 0 && (os.Args[0] != "fshim" || len(os.Args) != 1) && path.IsAbs(os.Args[0]) {
|
||||
if err := syscall.Exec(os.Args[0], []string{"fshim"}, os.Environ()); err != nil {
|
||||
fmsg.Println("cannot re-exec self:", err)
|
||||
// continue anyway
|
||||
}
|
||||
}
|
||||
|
||||
// check path to finit
|
||||
var finitPath string
|
||||
if p, ok := internal.Path(internal.Finit); !ok {
|
||||
fmsg.Fatal("invalid finit path, this copy of fshim is not compiled correctly")
|
||||
} else {
|
||||
finitPath = p
|
||||
}
|
||||
|
||||
// receive setup payload
|
||||
var (
|
||||
payload shim.Payload
|
||||
closeSetup func() error
|
||||
)
|
||||
if f, err := proc.Receive(shim.Env, &payload); err != nil {
|
||||
if errors.Is(err, proc.ErrInvalid) {
|
||||
fmsg.Fatal("invalid config descriptor")
|
||||
}
|
||||
if errors.Is(err, proc.ErrNotSet) {
|
||||
fmsg.Fatal("FORTIFY_SHIM not set")
|
||||
}
|
||||
|
||||
fmsg.Fatalf("cannot decode shim setup payload: %v", err)
|
||||
panic("unreachable")
|
||||
} else {
|
||||
fmsg.SetVerbose(payload.Verbose)
|
||||
closeSetup = f
|
||||
}
|
||||
|
||||
if payload.Bwrap == nil {
|
||||
fmsg.Fatal("bwrap config not supplied")
|
||||
}
|
||||
|
||||
// restore bwrap sync fd
|
||||
if payload.Sync != nil {
|
||||
payload.Bwrap.SetSync(os.NewFile(*payload.Sync, "sync"))
|
||||
}
|
||||
|
||||
// close setup socket
|
||||
if err := closeSetup(); err != nil {
|
||||
fmsg.Println("cannot close setup pipe:", err)
|
||||
// not fatal
|
||||
}
|
||||
|
||||
var ic init0.Payload
|
||||
|
||||
// resolve argv0
|
||||
ic.Argv = payload.Argv
|
||||
if len(ic.Argv) > 0 {
|
||||
// looked up from $PATH by parent
|
||||
ic.Argv0 = payload.Exec[1]
|
||||
} else {
|
||||
// no argv, look up shell instead
|
||||
var ok bool
|
||||
if payload.Bwrap.SetEnv == nil {
|
||||
fmsg.Fatal("no command was specified and environment is unset")
|
||||
}
|
||||
if ic.Argv0, ok = payload.Bwrap.SetEnv["SHELL"]; !ok {
|
||||
fmsg.Fatal("no command was specified and $SHELL was unset")
|
||||
}
|
||||
|
||||
ic.Argv = []string{ic.Argv0}
|
||||
}
|
||||
|
||||
conf := payload.Bwrap
|
||||
|
||||
var extraFiles []*os.File
|
||||
|
||||
// serve setup payload
|
||||
if fd, encoder, err := proc.Setup(&extraFiles); err != nil {
|
||||
fmsg.Fatalf("cannot pipe: %v", err)
|
||||
} else {
|
||||
conf.SetEnv[init0.Env] = strconv.Itoa(fd)
|
||||
go func() {
|
||||
fmsg.VPrintln("transmitting config to init")
|
||||
if err = encoder.Encode(&ic); err != nil {
|
||||
fmsg.Fatalf("cannot transmit init config: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
helper.BubblewrapName = payload.Exec[0] // resolved bwrap path by parent
|
||||
if b, err := helper.NewBwrap(conf, nil, finitPath,
|
||||
func(int, int) []string { return make([]string, 0) }); err != nil {
|
||||
fmsg.Fatalf("malformed sandbox config: %v", err)
|
||||
} else {
|
||||
cmd := b.Unwrap()
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
cmd.ExtraFiles = extraFiles
|
||||
|
||||
if fmsg.Verbose() {
|
||||
fmsg.VPrintln("bwrap args:", conf.Args())
|
||||
}
|
||||
|
||||
// run and pass through exit code
|
||||
if err = b.Start(); err != nil {
|
||||
fmsg.Fatalf("cannot start target process: %v", err)
|
||||
} else if err = b.Wait(); err != nil {
|
||||
fmsg.VPrintln("wait:", err)
|
||||
}
|
||||
if b.Unwrap().ProcessState != nil {
|
||||
fmsg.Exit(b.Unwrap().ProcessState.ExitCode())
|
||||
} else {
|
||||
fmsg.Exit(127)
|
||||
}
|
||||
}
|
||||
}
|
154
cmd/fsu/main.go
154
cmd/fsu/main.go
@ -1,154 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
const (
|
||||
compPoison = "INVALIDINVALIDINVALIDINVALIDINVALID"
|
||||
fsuConfFile = "/etc/fsurc"
|
||||
envShim = "FORTIFY_SHIM"
|
||||
envAID = "FORTIFY_APP_ID"
|
||||
envGroups = "FORTIFY_GROUPS"
|
||||
|
||||
PR_SET_NO_NEW_PRIVS = 0x26
|
||||
)
|
||||
|
||||
var (
|
||||
Fmain = compPoison
|
||||
Fshim = compPoison
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.SetFlags(0)
|
||||
log.SetPrefix("fsu: ")
|
||||
log.SetOutput(os.Stderr)
|
||||
|
||||
if os.Geteuid() != 0 {
|
||||
log.Fatal("this program must be owned by uid 0 and have the setuid bit set")
|
||||
}
|
||||
|
||||
puid := os.Getuid()
|
||||
if puid == 0 {
|
||||
log.Fatal("this program must not be started by root")
|
||||
}
|
||||
|
||||
var fmain, fshim string
|
||||
if p, ok := checkPath(Fmain); !ok {
|
||||
log.Fatal("invalid fortify path, this copy of fsu is not compiled correctly")
|
||||
} else {
|
||||
fmain = p
|
||||
}
|
||||
if p, ok := checkPath(Fshim); !ok {
|
||||
log.Fatal("invalid fshim path, this copy of fsu is not compiled correctly")
|
||||
} else {
|
||||
fshim = p
|
||||
}
|
||||
|
||||
pexe := path.Join("/proc", strconv.Itoa(os.Getppid()), "exe")
|
||||
if p, err := os.Readlink(pexe); err != nil {
|
||||
log.Fatalf("cannot read parent executable path: %v", err)
|
||||
} else if strings.HasSuffix(p, " (deleted)") {
|
||||
log.Fatal("fortify executable has been deleted")
|
||||
} else if p != fmain {
|
||||
log.Fatal("this program must be started by fortify")
|
||||
}
|
||||
|
||||
// uid = 1000000 +
|
||||
// fid * 10000 +
|
||||
// aid
|
||||
uid := 1000000
|
||||
|
||||
// authenticate before accepting user input
|
||||
if fid, ok := parseConfig(fsuConfFile, puid); !ok {
|
||||
log.Fatalf("uid %d is not in the fsurc file", puid)
|
||||
} else {
|
||||
uid += fid * 10000
|
||||
}
|
||||
|
||||
// allowed aid range 0 to 9999
|
||||
if as, ok := os.LookupEnv(envAID); !ok {
|
||||
log.Fatal("FORTIFY_APP_ID not set")
|
||||
} else if aid, err := parseUint32Fast(as); err != nil || aid < 0 || aid > 9999 {
|
||||
log.Fatal("invalid aid")
|
||||
} else {
|
||||
uid += aid
|
||||
}
|
||||
|
||||
// pass through setup fd to shim
|
||||
var shimSetupFd string
|
||||
if s, ok := os.LookupEnv(envShim); !ok {
|
||||
// fortify requests target uid
|
||||
// print resolved uid and exit
|
||||
fmt.Print(uid)
|
||||
os.Exit(0)
|
||||
} else if len(s) != 1 || s[0] > '9' || s[0] < '3' {
|
||||
log.Fatal("FORTIFY_SHIM holds an invalid value")
|
||||
} else {
|
||||
shimSetupFd = s
|
||||
}
|
||||
|
||||
// supplementary groups
|
||||
var suppGroups, suppCurrent []int
|
||||
|
||||
if gs, ok := os.LookupEnv(envGroups); ok {
|
||||
if cur, err := os.Getgroups(); err != nil {
|
||||
log.Fatalf("cannot get groups: %v", err)
|
||||
} else {
|
||||
suppCurrent = cur
|
||||
}
|
||||
|
||||
// parse space-separated list of group ids
|
||||
gss := bytes.Split([]byte(gs), []byte{' '})
|
||||
suppGroups = make([]int, len(gss)+1)
|
||||
for i, s := range gss {
|
||||
if gid, err := strconv.Atoi(string(s)); err != nil {
|
||||
log.Fatalf("cannot parse %q: %v", string(s), err)
|
||||
} else if gid > 0 && gid != uid && gid != os.Getgid() && slices.Contains(suppCurrent, gid) {
|
||||
suppGroups[i] = gid
|
||||
} else {
|
||||
log.Fatalf("invalid gid %d", gid)
|
||||
}
|
||||
}
|
||||
suppGroups[len(suppGroups)-1] = uid
|
||||
} else {
|
||||
suppGroups = []int{uid}
|
||||
}
|
||||
|
||||
// final bounds check to catch any bugs
|
||||
if uid < 1000000 || uid >= 2000000 {
|
||||
panic("uid out of bounds")
|
||||
}
|
||||
|
||||
// careful! users in the allowlist is effectively allowed to drop groups via fsu
|
||||
|
||||
if err := syscall.Setresgid(uid, uid, uid); err != nil {
|
||||
log.Fatalf("cannot set gid: %v", err)
|
||||
}
|
||||
if err := syscall.Setgroups(suppGroups); err != nil {
|
||||
log.Fatalf("cannot set supplementary groups: %v", err)
|
||||
}
|
||||
if err := syscall.Setresuid(uid, uid, uid); err != nil {
|
||||
log.Fatalf("cannot set uid: %v", err)
|
||||
}
|
||||
if _, _, errno := syscall.AllThreadsSyscall(syscall.SYS_PRCTL, PR_SET_NO_NEW_PRIVS, 1, 0); errno != 0 {
|
||||
log.Fatalf("cannot set no_new_privs flag: %s", errno.Error())
|
||||
}
|
||||
if err := syscall.Exec(fshim, []string{"fshim"}, []string{envShim + "=" + shimSetupFd}); err != nil {
|
||||
log.Fatalf("cannot start shim: %v", err)
|
||||
}
|
||||
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
func checkPath(p string) (string, bool) {
|
||||
return p, p != compPoison && p != "" && path.IsAbs(p)
|
||||
}
|
@ -1,77 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func parseUint32Fast(s string) (int, error) {
|
||||
sLen := len(s)
|
||||
if sLen < 1 {
|
||||
return -1, errors.New("zero length string")
|
||||
}
|
||||
if sLen > 10 {
|
||||
return -1, errors.New("string too long")
|
||||
}
|
||||
|
||||
n := 0
|
||||
for i, ch := range []byte(s) {
|
||||
ch -= '0'
|
||||
if ch > 9 {
|
||||
return -1, fmt.Errorf("invalid character '%s' at index %d", string([]byte{ch}), i)
|
||||
}
|
||||
n = n*10 + int(ch)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func parseConfig(p string, puid int) (fid int, ok bool) {
|
||||
// refuse to run if fsurc is not protected correctly
|
||||
if s, err := os.Stat(p); err != nil {
|
||||
log.Fatal(err)
|
||||
} else if s.Mode().Perm() != 0400 {
|
||||
log.Fatal("bad fsurc perm")
|
||||
} else if st := s.Sys().(*syscall.Stat_t); st.Uid != 0 || st.Gid != 0 {
|
||||
log.Fatal("fsurc must be owned by uid 0")
|
||||
}
|
||||
|
||||
if r, err := os.Open(p); err != nil {
|
||||
log.Fatal(err)
|
||||
return -1, false
|
||||
} else {
|
||||
s := bufio.NewScanner(r)
|
||||
var line int
|
||||
for s.Scan() {
|
||||
line++
|
||||
|
||||
// <puid> <fid>
|
||||
lf := strings.SplitN(s.Text(), " ", 2)
|
||||
if len(lf) != 2 {
|
||||
log.Fatalf("invalid entry on line %d", line)
|
||||
}
|
||||
|
||||
var puid0 int
|
||||
if puid0, err = parseUint32Fast(lf[0]); err != nil || puid0 < 1 {
|
||||
log.Fatalf("invalid parent uid on line %d", line)
|
||||
}
|
||||
|
||||
ok = puid0 == puid
|
||||
if ok {
|
||||
// allowed fid range 0 to 99
|
||||
if fid, err = parseUint32Fast(lf[1]); err != nil || fid < 0 || fid > 99 {
|
||||
log.Fatalf("invalid fortify uid on line %d", line)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
if err = s.Err(); err != nil {
|
||||
log.Fatalf("cannot read fsurc: %v", err)
|
||||
}
|
||||
return -1, false
|
||||
}
|
||||
}
|
@ -1,69 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmsg.SetPrefix("fuserdb")
|
||||
|
||||
const varEmpty = "/var/empty"
|
||||
|
||||
out := flag.String("o", "userdb", "output directory")
|
||||
homeDir := flag.String("d", varEmpty, "parent of home directories")
|
||||
shell := flag.String("s", "/sbin/nologin", "absolute path to subordinate user shell")
|
||||
flag.Parse()
|
||||
|
||||
type user struct {
|
||||
name string
|
||||
fid int
|
||||
}
|
||||
|
||||
users := make([]user, len(flag.Args()))
|
||||
for i, s := range flag.Args() {
|
||||
f := bytes.SplitN([]byte(s), []byte{':'}, 2)
|
||||
if len(f) != 2 {
|
||||
fmsg.Fatalf("invalid entry at index %d", i)
|
||||
}
|
||||
users[i].name = string(f[0])
|
||||
if fid, err := strconv.Atoi(string(f[1])); err != nil {
|
||||
fmsg.Fatal(err.Error())
|
||||
} else {
|
||||
users[i].fid = fid
|
||||
}
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(*out, 0755); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
fmsg.Fatalf("cannot create output: %v", err)
|
||||
}
|
||||
|
||||
for _, u := range users {
|
||||
fidString := strconv.Itoa(u.fid)
|
||||
for aid := 0; aid < 10000; aid++ {
|
||||
userName := fmt.Sprintf("u%d_a%d", u.fid, aid)
|
||||
uid := 1000000 + u.fid*10000 + aid
|
||||
us := strconv.Itoa(uid)
|
||||
realName := fmt.Sprintf("Fortify subordinate user %d (%s)", aid, u.name)
|
||||
var homeDirectory string
|
||||
if *homeDir != varEmpty {
|
||||
homeDirectory = path.Join(*homeDir, "u"+fidString, "a"+strconv.Itoa(aid))
|
||||
} else {
|
||||
homeDirectory = varEmpty
|
||||
}
|
||||
|
||||
writeUser(userName, uid, us, realName, homeDirectory, *shell, *out)
|
||||
writeGroup(userName, uid, us, nil, *out)
|
||||
}
|
||||
}
|
||||
|
||||
fmsg.Printf("created %d entries", len(users)*2*10000)
|
||||
fmsg.Exit(0)
|
||||
}
|
@ -1,64 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
type payloadU struct {
|
||||
UserName string `json:"userName"`
|
||||
Uid int `json:"uid"`
|
||||
Gid int `json:"gid"`
|
||||
MemberOf []string `json:"memberOf,omitempty"`
|
||||
RealName string `json:"realName"`
|
||||
HomeDirectory string `json:"homeDirectory"`
|
||||
Shell string `json:"shell"`
|
||||
}
|
||||
|
||||
func writeUser(userName string, uid int, us string, realName, homeDirectory, shell string, out string) {
|
||||
userFileName := userName + ".user"
|
||||
if f, err := os.OpenFile(path.Join(out, userFileName), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
|
||||
fmsg.Fatalf("cannot create %s: %v", userName, err)
|
||||
} else if err = json.NewEncoder(f).Encode(&payloadU{
|
||||
UserName: userName,
|
||||
Uid: uid,
|
||||
Gid: uid,
|
||||
RealName: realName,
|
||||
HomeDirectory: homeDirectory,
|
||||
Shell: shell,
|
||||
}); err != nil {
|
||||
fmsg.Fatalf("cannot serialise %s: %v", userName, err)
|
||||
} else if err = f.Close(); err != nil {
|
||||
fmsg.Printf("cannot close %s: %v", userName, err)
|
||||
}
|
||||
if err := os.Symlink(userFileName, path.Join(out, us+".user")); err != nil {
|
||||
fmsg.Fatalf("cannot link %s: %v", userName, err)
|
||||
}
|
||||
}
|
||||
|
||||
type payloadG struct {
|
||||
GroupName string `json:"groupName"`
|
||||
Gid int `json:"gid"`
|
||||
Members []string `json:"members,omitempty"`
|
||||
}
|
||||
|
||||
func writeGroup(groupName string, gid int, gs string, members []string, out string) {
|
||||
groupFileName := groupName + ".group"
|
||||
if f, err := os.OpenFile(path.Join(out, groupFileName), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
|
||||
fmsg.Fatalf("cannot create %s: %v", groupName, err)
|
||||
} else if err = json.NewEncoder(f).Encode(&payloadG{
|
||||
GroupName: groupName,
|
||||
Gid: gid,
|
||||
Members: members,
|
||||
}); err != nil {
|
||||
fmsg.Fatalf("cannot serialise %s: %v", groupName, err)
|
||||
} else if err = f.Close(); err != nil {
|
||||
fmsg.Printf("cannot close %s: %v", groupName, err)
|
||||
}
|
||||
if err := os.Symlink(groupFileName, path.Join(out, gs+".group")); err != nil {
|
||||
fmsg.Fatalf("cannot link %s: %v", groupName, err)
|
||||
}
|
||||
}
|
@ -1,51 +0,0 @@
|
||||
#compdef fortify
|
||||
|
||||
_fortify_app() {
|
||||
_path_files -g "*.(json|ftfy)"
|
||||
}
|
||||
|
||||
_fortify_run() {
|
||||
_arguments \
|
||||
'--id[App ID, leave empty to disable security context app_id]:id' \
|
||||
'-a[Fortify application ID]: :_numbers' \
|
||||
'-g[Groups inherited by the app process]: :_groups' \
|
||||
'-d[Application home directory]: :_files -/' \
|
||||
'-u[Passwd name within sandbox]: :_users' \
|
||||
'--wayland[Share Wayland socket]' \
|
||||
'-X[Share X11 socket and allow connection]' \
|
||||
'--dbus[Proxy D-Bus connection]' \
|
||||
'--pulse[Share PulseAudio socket and cookie]' \
|
||||
'--dbus-config[Path to D-Bus proxy config file]: :_files -g "*.json"' \
|
||||
'--dbus-system[Path to system D-Bus proxy config file]: :_files -g "*.json"' \
|
||||
'--mpris[Allow owning MPRIS D-Bus path]' \
|
||||
'--dbus-log[Force logging in the D-Bus proxy]'
|
||||
}
|
||||
|
||||
(( $+functions[_fortify_commands] )) || _fortify_commands()
|
||||
{
|
||||
local -a _fortify_cmds
|
||||
_fortify_cmds=(
|
||||
"app:Launch app defined by the specified config file"
|
||||
"run:Configure and start a permissive default sandbox"
|
||||
"ps:List active apps and their state"
|
||||
"version:Show fortify version"
|
||||
"license:Show full license text"
|
||||
"template:Produce a config template"
|
||||
"help:Show help message"
|
||||
)
|
||||
if (( CURRENT == 1 )); then
|
||||
_describe -t commands 'fortify command' _fortify_cmds || compadd "$@"
|
||||
else
|
||||
local curcontext="$curcontext"
|
||||
cmd="${${_fortify_cmds[(r)$words[1]:*]%%:*}}"
|
||||
if (( $+functions[_fortify_$cmd] )); then
|
||||
_fortify_$cmd
|
||||
else
|
||||
_message "no more options"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
_arguments -C \
|
||||
'-v[Verbose output]' \
|
||||
'*::fortify command:_fortify_commands'
|
136
config.go
Normal file
136
config.go
Normal file
@ -0,0 +1,136 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/app"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
var (
|
||||
printTemplate bool
|
||||
|
||||
confPath string
|
||||
|
||||
dbusConfigSession string
|
||||
dbusConfigSystem string
|
||||
dbusID string
|
||||
mpris bool
|
||||
dbusVerbose bool
|
||||
|
||||
userName string
|
||||
enablements [system.ELen]bool
|
||||
|
||||
launchMethodText string
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.BoolVar(&printTemplate, "template", false, "Print a full config template and exit")
|
||||
|
||||
// config file, disables every other flag here
|
||||
flag.StringVar(&confPath, "c", "nil", "Path to full app configuration, or \"nil\" to configure from flags")
|
||||
|
||||
flag.StringVar(&dbusConfigSession, "dbus-config", "builtin", "Path to D-Bus proxy config file, or \"builtin\" for defaults")
|
||||
flag.StringVar(&dbusConfigSystem, "dbus-system", "nil", "Path to system D-Bus proxy config file, or \"nil\" to disable")
|
||||
flag.StringVar(&dbusID, "dbus-id", "", "D-Bus ID of application, leave empty to disable own paths, has no effect if custom config is available")
|
||||
flag.BoolVar(&mpris, "mpris", false, "Allow owning MPRIS D-Bus path, has no effect if custom config is available")
|
||||
flag.BoolVar(&dbusVerbose, "dbus-log", false, "Force logging in the D-Bus proxy")
|
||||
|
||||
flag.StringVar(&userName, "u", "chronos", "Passwd name of user to run as")
|
||||
flag.BoolVar(&enablements[system.EWayland], "wayland", false, "Share Wayland socket")
|
||||
flag.BoolVar(&enablements[system.EX11], "X", false, "Share X11 socket and allow connection")
|
||||
flag.BoolVar(&enablements[system.EDBus], "dbus", false, "Proxy D-Bus connection")
|
||||
flag.BoolVar(&enablements[system.EPulse], "pulse", false, "Share PulseAudio socket and cookie")
|
||||
}
|
||||
|
||||
func init() {
|
||||
methodHelpString := "Method of launching the child process, can be one of \"sudo\""
|
||||
if internal.SdBootedV {
|
||||
methodHelpString += ", \"systemd\""
|
||||
}
|
||||
|
||||
flag.StringVar(&launchMethodText, "method", "sudo", methodHelpString)
|
||||
}
|
||||
|
||||
func tryTemplate() {
|
||||
if printTemplate {
|
||||
if s, err := json.MarshalIndent(app.Template(), "", " "); err != nil {
|
||||
fmsg.Fatalf("cannot generate template: %v", err)
|
||||
panic("unreachable")
|
||||
} else {
|
||||
fmt.Println(string(s))
|
||||
}
|
||||
fmsg.Exit(0)
|
||||
}
|
||||
}
|
||||
|
||||
func loadConfig() *app.Config {
|
||||
if confPath == "nil" {
|
||||
// config from flags
|
||||
return configFromFlags()
|
||||
} else {
|
||||
// config from file
|
||||
c := new(app.Config)
|
||||
if f, err := os.Open(confPath); err != nil {
|
||||
fmsg.Fatalf("cannot access config file %q: %s", confPath, err)
|
||||
panic("unreachable")
|
||||
} else if err = json.NewDecoder(f).Decode(&c); err != nil {
|
||||
fmsg.Fatalf("cannot parse config file %q: %s", confPath, err)
|
||||
panic("unreachable")
|
||||
} else {
|
||||
return c
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func configFromFlags() (config *app.Config) {
|
||||
// initialise config from flags
|
||||
config = &app.Config{
|
||||
ID: dbusID,
|
||||
User: userName,
|
||||
Command: flag.Args(),
|
||||
Method: launchMethodText,
|
||||
}
|
||||
|
||||
// enablements from flags
|
||||
for i := system.Enablement(0); i < system.Enablement(system.ELen); i++ {
|
||||
if enablements[i] {
|
||||
config.Confinement.Enablements.Set(i)
|
||||
}
|
||||
}
|
||||
|
||||
// parse D-Bus config file from flags if applicable
|
||||
if enablements[system.EDBus] {
|
||||
if dbusConfigSession == "builtin" {
|
||||
config.Confinement.SessionBus = dbus.NewConfig(dbusID, true, mpris)
|
||||
} else {
|
||||
if c, err := dbus.NewConfigFromFile(dbusConfigSession); err != nil {
|
||||
fmsg.Fatalf("cannot load session bus proxy config from %q: %s", dbusConfigSession, err)
|
||||
} else {
|
||||
config.Confinement.SessionBus = c
|
||||
}
|
||||
}
|
||||
|
||||
// system bus proxy is optional
|
||||
if dbusConfigSystem != "nil" {
|
||||
if c, err := dbus.NewConfigFromFile(dbusConfigSystem); err != nil {
|
||||
fmsg.Fatalf("cannot load system bus proxy config from %q: %s", dbusConfigSystem, err)
|
||||
} else {
|
||||
config.Confinement.SystemBus = c
|
||||
}
|
||||
}
|
||||
|
||||
// override log from configuration
|
||||
if dbusVerbose {
|
||||
config.Confinement.SessionBus.Log = true
|
||||
config.Confinement.SystemBus.Log = true
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
@ -9,7 +9,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
)
|
||||
|
||||
func TestConfig_Args(t *testing.T) {
|
||||
|
@ -1,4 +1,3 @@
|
||||
// Package dbus wraps xdg-dbus-proxy and implements configuration and sandboxing of the underlying helper process.
|
||||
package dbus
|
||||
|
||||
import (
|
||||
|
@ -5,8 +5,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
)
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
|
@ -6,8 +6,8 @@ import (
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
)
|
||||
|
||||
// ProxyName is the file name or path to the proxy program.
|
||||
|
@ -9,9 +9,9 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/ldd"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/ldd"
|
||||
)
|
||||
|
||||
// Start launches the D-Bus proxy and sets up the Wait method.
|
||||
|
@ -3,7 +3,7 @@ package dbus_test
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
)
|
||||
|
||||
var samples = []dbusTestCase{
|
||||
|
@ -3,7 +3,7 @@ package dbus_test
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
)
|
||||
|
||||
func TestHelperChildStub(t *testing.T) {
|
||||
|
1
dist/fsurc.default
vendored
1
dist/fsurc.default
vendored
@ -1 +0,0 @@
|
||||
1000 0
|
10
dist/install.sh
vendored
10
dist/install.sh
vendored
@ -1,10 +0,0 @@
|
||||
#!/bin/sh
|
||||
cd "$(dirname -- "$0")" || exit 1
|
||||
|
||||
install -vDm0755 "bin/fortify" "${FORTIFY_INSTALL_PREFIX}/usr/bin/fortify"
|
||||
install -vDm0755 "bin/fshim" "${FORTIFY_INSTALL_PREFIX}/usr/libexec/fortify/fshim"
|
||||
install -vDm0755 "bin/finit" "${FORTIFY_INSTALL_PREFIX}/usr/libexec/fortify/finit"
|
||||
install -vDm0755 "bin/fuserdb" "${FORTIFY_INSTALL_PREFIX}/usr/libexec/fortify/fuserdb"
|
||||
|
||||
install -vDm6511 "bin/fsu" "${FORTIFY_INSTALL_PREFIX}/usr/bin/fsu"
|
||||
install -vDm0400 "fsurc.default" "${FORTIFY_INSTALL_PREFIX}/etc/fsurc"
|
19
dist/release.sh
vendored
19
dist/release.sh
vendored
@ -1,19 +0,0 @@
|
||||
#!/bin/sh -e
|
||||
cd "$(dirname -- "$0")/.."
|
||||
VERSION="${FORTIFY_VERSION:-untagged}"
|
||||
pname="fortify-${VERSION}"
|
||||
out="dist/${pname}"
|
||||
|
||||
mkdir -p "${out}"
|
||||
cp "README.md" "dist/fsurc.default" "dist/install.sh" "${out}"
|
||||
|
||||
go build -v -o "${out}/bin/" -ldflags "-s -w
|
||||
-X git.gensokyo.uk/security/fortify/internal.Version=${VERSION}
|
||||
-X git.gensokyo.uk/security/fortify/internal.Fsu=/usr/bin/fsu
|
||||
-X git.gensokyo.uk/security/fortify/internal.Finit=/usr/libexec/fortify/finit
|
||||
-X main.Fmain=/usr/bin/fortify
|
||||
-X main.Fshim=/usr/libexec/fortify/fshim" ./...
|
||||
|
||||
rm -f "./${out}.tar.gz" && tar -C dist -czf "${out}.tar.gz" "${pname}"
|
||||
rm -rf "./${out}"
|
||||
sha512sum "${out}.tar.gz" > "${out}.tar.gz.sha512"
|
4
error.go
4
error.go
@ -3,8 +3,8 @@ package main
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/app"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/app"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
func logWaitError(err error) {
|
||||
|
30
flake.lock
generated
30
flake.lock
generated
@ -1,45 +1,23 @@
|
||||
{
|
||||
"nodes": {
|
||||
"home-manager": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1733951536,
|
||||
"narHash": "sha256-Zb5ZCa7Xj+0gy5XVXINTSr71fCfAv+IKtmIXNrykT54=",
|
||||
"owner": "nix-community",
|
||||
"repo": "home-manager",
|
||||
"rev": "1318c3f3b068cdcea922fa7c1a0a1f0c96c22f5f",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-community",
|
||||
"ref": "release-24.11",
|
||||
"repo": "home-manager",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1734298236,
|
||||
"narHash": "sha256-aWhhqY44xBjMoO9r5fyPp5u8tqUNWRZ/m/P+abMSs5c=",
|
||||
"lastModified": 1725361206,
|
||||
"narHash": "sha256-/HTUg+kMaqBPGrcQBYboAMsQHIWIkuKRDldss/035Hc=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "eb919d9300b6a18f8583f58aef16db458fbd7bec",
|
||||
"rev": "2830c7c930311397d94c0b86a359c865c081c875",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-24.11-small",
|
||||
"ref": "nixos-unstable-small",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"home-manager": "home-manager",
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
}
|
||||
|
113
flake.nix
113
flake.nix
@ -2,20 +2,11 @@
|
||||
description = "fortify sandbox tool and nixos module";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11-small";
|
||||
|
||||
home-manager = {
|
||||
url = "github:nix-community/home-manager/release-24.11";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable-small";
|
||||
};
|
||||
|
||||
outputs =
|
||||
{
|
||||
self,
|
||||
nixpkgs,
|
||||
home-manager,
|
||||
}:
|
||||
{ self, nixpkgs }:
|
||||
let
|
||||
supportedSystems = [
|
||||
"aarch64-linux"
|
||||
@ -29,55 +20,6 @@
|
||||
{
|
||||
nixosModules.fortify = import ./nixos.nix;
|
||||
|
||||
checks = forAllSystems (
|
||||
system:
|
||||
let
|
||||
pkgs = nixpkgsFor.${system};
|
||||
|
||||
inherit (pkgs)
|
||||
runCommandLocal
|
||||
callPackage
|
||||
nixfmt-rfc-style
|
||||
deadnix
|
||||
statix
|
||||
;
|
||||
in
|
||||
{
|
||||
check-formatting =
|
||||
runCommandLocal "check-formatting" { nativeBuildInputs = [ nixfmt-rfc-style ]; }
|
||||
''
|
||||
cd ${./.}
|
||||
|
||||
echo "running nixfmt..."
|
||||
nixfmt --check .
|
||||
|
||||
touch $out
|
||||
'';
|
||||
|
||||
check-lint =
|
||||
runCommandLocal "check-lint"
|
||||
{
|
||||
nativeBuildInputs = [
|
||||
deadnix
|
||||
statix
|
||||
];
|
||||
}
|
||||
''
|
||||
cd ${./.}
|
||||
|
||||
echo "running deadnix..."
|
||||
deadnix --fail
|
||||
|
||||
echo "running statix..."
|
||||
statix check .
|
||||
|
||||
touch $out
|
||||
'';
|
||||
|
||||
nixos-tests = callPackage ./test.nix { inherit system self home-manager; };
|
||||
}
|
||||
);
|
||||
|
||||
packages = forAllSystems (
|
||||
system:
|
||||
let
|
||||
@ -92,27 +34,9 @@
|
||||
|
||||
devShells = forAllSystems (system: {
|
||||
default = nixpkgsFor.${system}.mkShell {
|
||||
buildInputs = with nixpkgsFor.${system}; self.packages.${system}.fortify.buildInputs;
|
||||
};
|
||||
|
||||
fhs = nixpkgsFor.${system}.buildFHSEnv {
|
||||
pname = "fortify-fhs";
|
||||
inherit (self.packages.${system}.fortify) version;
|
||||
targetPkgs =
|
||||
pkgs: with pkgs; [
|
||||
go
|
||||
gcc
|
||||
pkg-config
|
||||
acl
|
||||
wayland
|
||||
wayland-scanner
|
||||
wayland-protocols
|
||||
xorg.libxcb
|
||||
];
|
||||
extraOutputsToInstall = [ "dev" ];
|
||||
profile = ''
|
||||
export PKG_CONFIG_PATH="/usr/share/pkgconfig:$PKG_CONFIG_PATH"
|
||||
'';
|
||||
buildInputs =
|
||||
with nixpkgsFor.${system};
|
||||
self.packages.${system}.fortify.buildInputs;
|
||||
};
|
||||
|
||||
withPackage = nixpkgsFor.${system}.mkShell {
|
||||
@ -120,33 +44,6 @@
|
||||
with nixpkgsFor.${system};
|
||||
self.packages.${system}.fortify.buildInputs ++ [ self.packages.${system}.fortify ];
|
||||
};
|
||||
|
||||
generateDoc =
|
||||
let
|
||||
pkgs = nixpkgsFor.${system};
|
||||
inherit (pkgs) lib;
|
||||
|
||||
doc =
|
||||
let
|
||||
eval = lib.evalModules {
|
||||
specialArgs = {
|
||||
inherit pkgs;
|
||||
};
|
||||
modules = [ ./options.nix ];
|
||||
};
|
||||
cleanEval = lib.filterAttrsRecursive (n: _: n != "_module") eval;
|
||||
in
|
||||
pkgs.nixosOptionsDoc { inherit (cleanEval) options; };
|
||||
docText = pkgs.runCommand "fortify-module-docs.md" { } ''
|
||||
cat ${doc.optionsCommonMark} > $out
|
||||
sed -i '/*Declared by:*/,+1 d' $out
|
||||
'';
|
||||
in
|
||||
nixpkgsFor.${system}.mkShell {
|
||||
shellHook = ''
|
||||
exec cat ${docText} > options.md
|
||||
'';
|
||||
};
|
||||
});
|
||||
};
|
||||
}
|
||||
|
48
fst/id.go
48
fst/id.go
@ -1,48 +0,0 @@
|
||||
package fst
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type ID [16]byte
|
||||
|
||||
var (
|
||||
ErrInvalidLength = errors.New("string representation must have a length of 32")
|
||||
)
|
||||
|
||||
func (a *ID) String() string {
|
||||
return hex.EncodeToString(a[:])
|
||||
}
|
||||
|
||||
func NewAppID(id *ID) error {
|
||||
_, err := rand.Read(id[:])
|
||||
return err
|
||||
}
|
||||
|
||||
func ParseAppID(id *ID, s string) error {
|
||||
if len(s) != 32 {
|
||||
return ErrInvalidLength
|
||||
}
|
||||
|
||||
for i, b := range s {
|
||||
if b < '0' || b > 'f' {
|
||||
return fmt.Errorf("invalid char %q at byte %d", b, i)
|
||||
}
|
||||
|
||||
v := uint8(b)
|
||||
if v > '9' {
|
||||
v = 10 + v - 'a'
|
||||
} else {
|
||||
v -= '0'
|
||||
}
|
||||
if i%2 == 0 {
|
||||
v <<= 4
|
||||
}
|
||||
id[i/2] += v
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
@ -1,63 +0,0 @@
|
||||
package fst_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
)
|
||||
|
||||
func TestParseAppID(t *testing.T) {
|
||||
t.Run("bad length", func(t *testing.T) {
|
||||
if err := fst.ParseAppID(new(fst.ID), "meow"); !errors.Is(err, fst.ErrInvalidLength) {
|
||||
t.Errorf("ParseAppID: error = %v, wantErr = %v", err, fst.ErrInvalidLength)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("bad byte", func(t *testing.T) {
|
||||
wantErr := "invalid char '\\n' at byte 15"
|
||||
if err := fst.ParseAppID(new(fst.ID), "02bc7f8936b2af6\n\ne2535cd71ef0bb7"); err == nil || err.Error() != wantErr {
|
||||
t.Errorf("ParseAppID: error = %v, wantErr = %v", err, wantErr)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fuzz 16 iterations", func(t *testing.T) {
|
||||
for i := 0; i < 16; i++ {
|
||||
testParseAppIDWithRandom(t)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzParseAppID(f *testing.F) {
|
||||
for i := 0; i < 16; i++ {
|
||||
id := new(fst.ID)
|
||||
if err := fst.NewAppID(id); err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
f.Add(id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11], id[12], id[13], id[14], id[15])
|
||||
}
|
||||
|
||||
f.Fuzz(func(t *testing.T, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15 byte) {
|
||||
testParseAppID(t, &fst.ID{b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15})
|
||||
})
|
||||
}
|
||||
|
||||
func testParseAppIDWithRandom(t *testing.T) {
|
||||
id := new(fst.ID)
|
||||
if err := fst.NewAppID(id); err != nil {
|
||||
t.Fatalf("cannot generate app ID: %v", err)
|
||||
}
|
||||
testParseAppID(t, id)
|
||||
}
|
||||
|
||||
func testParseAppID(t *testing.T, id *fst.ID) {
|
||||
s := id.String()
|
||||
got := new(fst.ID)
|
||||
if err := fst.ParseAppID(got, s); err != nil {
|
||||
t.Fatalf("cannot parse app ID: %v", err)
|
||||
}
|
||||
|
||||
if *got != *id {
|
||||
t.Fatalf("ParseAppID(%#v) = \n%#v, want \n%#v", s, got, id)
|
||||
}
|
||||
}
|
@ -1,2 +0,0 @@
|
||||
// Package fst exports shared fortify types.
|
||||
package fst
|
2
go.mod
2
go.mod
@ -1,3 +1,3 @@
|
||||
module git.gensokyo.uk/security/fortify
|
||||
module git.ophivana.moe/security/fortify
|
||||
|
||||
go 1.22
|
||||
|
@ -6,7 +6,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
)
|
||||
|
||||
func Test_argsFD_String(t *testing.T) {
|
||||
|
@ -3,13 +3,11 @@ package helper
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/internal/proc"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
)
|
||||
|
||||
// BubblewrapName is the file name or path to bubblewrap.
|
||||
@ -21,8 +19,6 @@ type bubblewrap struct {
|
||||
|
||||
// bwrap pipes
|
||||
p *pipes
|
||||
// sync pipe
|
||||
sync *os.File
|
||||
// returns an array of arguments passed directly
|
||||
// to the child process spawned by bwrap
|
||||
argF func(argsFD, statFD int) []string
|
||||
@ -76,10 +72,6 @@ func (b *bubblewrap) StartNotify(ready chan error) error {
|
||||
b.Cmd.Env = append(b.Cmd.Env, FortifyHelper+"=1", FortifyStatus+"=-1")
|
||||
}
|
||||
|
||||
if b.sync != nil {
|
||||
b.Cmd.Args = append(b.Cmd.Args, "--sync-fd", strconv.Itoa(int(proc.ExtraFile(b.Cmd, b.sync))))
|
||||
}
|
||||
|
||||
if err := b.Cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
@ -139,7 +131,6 @@ func NewBwrap(conf *bwrap.Config, wt io.WriterTo, name string, argF func(argsFD,
|
||||
b.p = &pipes{args: args}
|
||||
}
|
||||
|
||||
b.sync = conf.Sync()
|
||||
b.argF = argF
|
||||
b.name = name
|
||||
if wt != nil {
|
||||
|
@ -68,16 +68,13 @@ type Config struct {
|
||||
// (--as-pid-1)
|
||||
AsInit bool `json:"as_init"`
|
||||
|
||||
// keep this fd open while sandbox is running
|
||||
// (--sync-fd FD)
|
||||
sync *os.File
|
||||
|
||||
/* unmapped options include:
|
||||
--unshare-user-try Create new user namespace if possible else continue by skipping it
|
||||
--unshare-cgroup-try Create new cgroup namespace if possible else continue by skipping it
|
||||
--userns FD Use this user namespace (cannot combine with --unshare-user)
|
||||
--userns2 FD After setup switch to this user namespace, only useful with --userns
|
||||
--pidns FD Use this pid namespace (as parent namespace if using --unshare-pid)
|
||||
--sync-fd FD Keep this fd open while sandbox is running
|
||||
--exec-label LABEL Exec label for the sandbox
|
||||
--file-label LABEL File label for temporary sandbox content
|
||||
--file FD DEST Copy from FD to destination DEST
|
||||
@ -95,12 +92,6 @@ type Config struct {
|
||||
among which --args is used internally for passing arguments */
|
||||
}
|
||||
|
||||
// Sync keep this fd open while sandbox is running
|
||||
// (--sync-fd FD)
|
||||
func (c *Config) Sync() *os.File {
|
||||
return c.sync
|
||||
}
|
||||
|
||||
type UnshareConfig struct {
|
||||
// (--unshare-user)
|
||||
// create new user namespace
|
||||
|
@ -136,10 +136,3 @@ func (c *Config) SetGID(gid int) *Config {
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// SetSync sets the sync pipe kept open while sandbox is running
|
||||
// (--sync-fd FD)
|
||||
func (c *Config) SetSync(s *os.File) *Config {
|
||||
c.sync = s
|
||||
return c
|
||||
}
|
||||
|
@ -7,8 +7,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
)
|
||||
|
||||
func TestBwrap(t *testing.T) {
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
)
|
||||
|
||||
func TestDirect(t *testing.T) {
|
||||
|
@ -1,4 +1,6 @@
|
||||
// Package helper runs external helpers with optional sandboxing and manages their status/args pipes.
|
||||
/*
|
||||
Package helper runs external helpers and manages their status and args FDs.
|
||||
*/
|
||||
package helper
|
||||
|
||||
import (
|
||||
|
@ -6,7 +6,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
)
|
||||
|
||||
var (
|
||||
|
@ -5,8 +5,6 @@ import (
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/proc"
|
||||
)
|
||||
|
||||
type pipes struct {
|
||||
@ -49,21 +47,24 @@ func (p *pipes) pipe() error {
|
||||
}
|
||||
|
||||
// calls pipe to create pipes and sets them up as ExtraFiles, returning their fd
|
||||
func (p *pipes) prepareCmd(cmd *exec.Cmd) (argsFd, statFd int, err error) {
|
||||
argsFd, statFd = -1, -1
|
||||
if err = p.pipe(); err != nil {
|
||||
return
|
||||
func (p *pipes) prepareCmd(cmd *exec.Cmd) (int, int, error) {
|
||||
if err := p.pipe(); err != nil {
|
||||
return -1, -1, err
|
||||
}
|
||||
|
||||
// save a reference of cmd for future use
|
||||
p.cmd = cmd
|
||||
|
||||
argsFd = int(proc.ExtraFile(cmd, p.argsP[0]))
|
||||
if p.ready != nil {
|
||||
statFd = int(proc.ExtraFile(cmd, p.statP[1]))
|
||||
}
|
||||
// ExtraFiles: If non-nil, entry i becomes file descriptor 3+i.
|
||||
argsFd := 3 + len(cmd.ExtraFiles)
|
||||
cmd.ExtraFiles = append(cmd.ExtraFiles, p.argsP[0])
|
||||
|
||||
return
|
||||
if p.ready != nil {
|
||||
cmd.ExtraFiles = append(cmd.ExtraFiles, p.statP[1])
|
||||
return argsFd, argsFd + 1, nil
|
||||
} else {
|
||||
return argsFd, -1, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p *pipes) readyWriteArgs() error {
|
||||
|
@ -10,8 +10,8 @@ import (
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// InternalChildStub is an internal function but exported because it is cross-package;
|
||||
|
@ -3,7 +3,7 @@ package helper_test
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
)
|
||||
|
||||
func TestHelperChildStub(t *testing.T) {
|
||||
|
@ -2,16 +2,14 @@ package app
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/cmd/fshim/ipc/shim"
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/shim"
|
||||
)
|
||||
|
||||
type App interface {
|
||||
// ID returns a copy of App's unique ID.
|
||||
ID() fst.ID
|
||||
ID() ID
|
||||
// Start sets up the system and starts the App.
|
||||
Start() error
|
||||
// Wait waits for App's process to exit and reverts system setup.
|
||||
@ -19,18 +17,15 @@ type App interface {
|
||||
// WaitErr returns error returned by the underlying wait syscall.
|
||||
WaitErr() error
|
||||
|
||||
Seal(config *fst.Config) error
|
||||
Seal(config *Config) error
|
||||
String() string
|
||||
}
|
||||
|
||||
type app struct {
|
||||
// single-use config reference
|
||||
ct *appCt
|
||||
|
||||
// application unique identifier
|
||||
id *fst.ID
|
||||
id *ID
|
||||
// operating system interface
|
||||
os linux.System
|
||||
os internal.System
|
||||
// shim process manager
|
||||
shim *shim.Shim
|
||||
// child process related information
|
||||
@ -41,7 +36,7 @@ type app struct {
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
func (a *app) ID() fst.ID {
|
||||
func (a *app) ID() ID {
|
||||
return *a.id
|
||||
}
|
||||
|
||||
@ -58,7 +53,7 @@ func (a *app) String() string {
|
||||
}
|
||||
|
||||
if a.seal != nil {
|
||||
return "(sealed fortified app as uid " + a.seal.sys.user.us + ")"
|
||||
return "(sealed fortified app as uid " + a.seal.sys.user.Uid + ")"
|
||||
}
|
||||
|
||||
return "(unsealed fortified app)"
|
||||
@ -68,30 +63,9 @@ func (a *app) WaitErr() error {
|
||||
return a.waitErr
|
||||
}
|
||||
|
||||
func New(os linux.System) (App, error) {
|
||||
func New(os internal.System) (App, error) {
|
||||
a := new(app)
|
||||
a.id = new(fst.ID)
|
||||
a.id = new(ID)
|
||||
a.os = os
|
||||
return a, fst.NewAppID(a.id)
|
||||
}
|
||||
|
||||
// appCt ensures its wrapped val is only accessed once
|
||||
type appCt struct {
|
||||
val *fst.Config
|
||||
done *atomic.Bool
|
||||
}
|
||||
|
||||
func (a *appCt) Unwrap() *fst.Config {
|
||||
if !a.done.Load() {
|
||||
defer a.done.Store(true)
|
||||
return a.val
|
||||
}
|
||||
panic("attempted to access config reference twice")
|
||||
}
|
||||
|
||||
func newAppCt(config *fst.Config) (ct *appCt) {
|
||||
ct = new(appCt)
|
||||
ct.done = new(atomic.Bool)
|
||||
ct.val = config
|
||||
return ct
|
||||
return a, newAppID(a.id)
|
||||
}
|
||||
|
@ -1,225 +1,313 @@
|
||||
package app_test
|
||||
|
||||
import (
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os/user"
|
||||
"strconv"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/app"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
var testCasesNixos = []sealTestCase{
|
||||
{
|
||||
"nixos chromium direct wayland", new(stubNixOS),
|
||||
&fst.Config{
|
||||
ID: "org.chromium.Chromium",
|
||||
Command: []string{"/nix/store/yqivzpzzn7z5x0lq9hmbzygh45d8rhqd-chromium-start"},
|
||||
Confinement: fst.ConfinementConfig{
|
||||
AppID: 1, Groups: []string{}, Username: "u0_a1",
|
||||
Outer: "/var/lib/persist/module/fortify/0/1",
|
||||
Sandbox: &fst.SandboxConfig{
|
||||
UserNS: true, Net: true, MapRealUID: true, DirectWayland: true, Env: nil,
|
||||
Filesystem: []*fst.FilesystemConfig{
|
||||
{Src: "/bin", Must: true}, {Src: "/usr/bin", Must: true},
|
||||
{Src: "/nix/store", Must: true}, {Src: "/run/current-system", Must: true},
|
||||
{Src: "/sys/block"}, {Src: "/sys/bus"}, {Src: "/sys/class"}, {Src: "/sys/dev"}, {Src: "/sys/devices"},
|
||||
{Src: "/run/opengl-driver", Must: true}, {Src: "/dev/dri", Device: true},
|
||||
}, AutoEtc: true,
|
||||
Override: []string{"/var/run/nscd"},
|
||||
},
|
||||
SystemBus: &dbus.Config{
|
||||
Talk: []string{"org.bluez", "org.freedesktop.Avahi", "org.freedesktop.UPower"},
|
||||
Filter: true,
|
||||
},
|
||||
SessionBus: &dbus.Config{
|
||||
Talk: []string{
|
||||
"org.freedesktop.FileManager1", "org.freedesktop.Notifications",
|
||||
"org.freedesktop.ScreenSaver", "org.freedesktop.secrets",
|
||||
"org.kde.kwalletd5", "org.kde.kwalletd6",
|
||||
},
|
||||
Own: []string{
|
||||
"org.chromium.Chromium.*",
|
||||
"org.mpris.MediaPlayer2.org.chromium.Chromium.*",
|
||||
"org.mpris.MediaPlayer2.chromium.*",
|
||||
},
|
||||
Call: map[string]string{}, Broadcast: map[string]string{},
|
||||
Filter: true,
|
||||
},
|
||||
Enablements: system.EWayland.Mask() | system.EDBus.Mask() | system.EPulse.Mask(),
|
||||
},
|
||||
"nixos permissive defaults no enablements", new(stubNixOS),
|
||||
&app.Config{
|
||||
User: "chronos",
|
||||
Command: make([]string, 0),
|
||||
Method: "sudo",
|
||||
},
|
||||
fst.ID{
|
||||
0x8e, 0x2c, 0x76, 0xb0,
|
||||
0x66, 0xda, 0xbe, 0x57,
|
||||
0x4c, 0xf0, 0x73, 0xbd,
|
||||
0xb4, 0x6e, 0xb5, 0xc1,
|
||||
app.ID{
|
||||
0x4a, 0x45, 0x0b, 0x65,
|
||||
0x96, 0xd7, 0xbc, 0x15,
|
||||
0xbd, 0x01, 0x78, 0x0e,
|
||||
0xb9, 0xa6, 0x07, 0xac,
|
||||
},
|
||||
system.New(1000001).
|
||||
Ensure("/tmp/fortify.1971", 0711).
|
||||
Ephemeral(system.Process, "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1", 0711).
|
||||
system.New(150).
|
||||
Ensure("/tmp/fortify.1971", 0701).
|
||||
Ephemeral(system.Process, "/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac", 0701).
|
||||
Ensure("/tmp/fortify.1971/tmpdir", 0700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir", acl.Execute).
|
||||
Ensure("/tmp/fortify.1971/tmpdir/1", 01700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir/1", acl.Read, acl.Write, acl.Execute).
|
||||
Ensure("/tmp/fortify.1971/tmpdir/150", 01700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir/150", acl.Read, acl.Write, acl.Execute).
|
||||
Ensure("/run/user/1971/fortify", 0700).UpdatePermType(system.User, "/run/user/1971/fortify", acl.Execute).
|
||||
Ensure("/run/user/1971", 0700).UpdatePermType(system.User, "/run/user/1971", acl.Execute). // this is ordered as is because the previous Ensure only calls mkdir if XDG_RUNTIME_DIR is unset
|
||||
Ephemeral(system.Process, "/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1", 0700).UpdatePermType(system.Process, "/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1", acl.Execute).
|
||||
WriteType(system.Process, "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/passwd", "u0_a1:x:1971:1971:Fortify:/var/lib/persist/module/fortify/0/1:/run/current-system/sw/bin/zsh\n").
|
||||
WriteType(system.Process, "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/group", "fortify:x:1971:\n").
|
||||
Link("/run/user/1971/wayland-0", "/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1/wayland").
|
||||
UpdatePermType(system.EWayland, "/run/user/1971/wayland-0", acl.Read, acl.Write, acl.Execute).
|
||||
Link("/run/user/1971/pulse/native", "/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1/pulse").
|
||||
CopyFile("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/pulse-cookie", "/home/ophestra/xdg/config/pulse/cookie").
|
||||
MustProxyDBus("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/bus", &dbus.Config{
|
||||
Talk: []string{
|
||||
"org.freedesktop.FileManager1", "org.freedesktop.Notifications",
|
||||
"org.freedesktop.ScreenSaver", "org.freedesktop.secrets",
|
||||
"org.kde.kwalletd5", "org.kde.kwalletd6",
|
||||
},
|
||||
Own: []string{
|
||||
"org.chromium.Chromium.*",
|
||||
"org.mpris.MediaPlayer2.org.chromium.Chromium.*",
|
||||
"org.mpris.MediaPlayer2.chromium.*",
|
||||
},
|
||||
Call: map[string]string{}, Broadcast: map[string]string{},
|
||||
Filter: true,
|
||||
}, "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/system_bus_socket", &dbus.Config{
|
||||
Talk: []string{
|
||||
"org.bluez",
|
||||
"org.freedesktop.Avahi",
|
||||
"org.freedesktop.UPower",
|
||||
},
|
||||
Filter: true,
|
||||
}).
|
||||
UpdatePerm("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/bus", acl.Read, acl.Write).
|
||||
UpdatePerm("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/system_bus_socket", acl.Read, acl.Write),
|
||||
Ephemeral(system.Process, "/run/user/1971/fortify/4a450b6596d7bc15bd01780eb9a607ac", 0700).UpdatePermType(system.Process, "/run/user/1971/fortify/4a450b6596d7bc15bd01780eb9a607ac", acl.Execute).
|
||||
WriteType(system.Process, "/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac/passwd", "chronos:x:65534:65534:Fortify:/home/chronos:/run/current-system/sw/bin/zsh\n").
|
||||
WriteType(system.Process, "/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac/group", "fortify:x:65534:\n"),
|
||||
(&bwrap.Config{
|
||||
Net: true,
|
||||
UserNS: true,
|
||||
Chdir: "/var/lib/persist/module/fortify/0/1",
|
||||
Clearenv: true,
|
||||
SetEnv: map[string]string{
|
||||
"DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/1971/bus",
|
||||
"DBUS_SYSTEM_BUS_ADDRESS": "unix:path=/run/dbus/system_bus_socket",
|
||||
"HOME": "/var/lib/persist/module/fortify/0/1",
|
||||
"PULSE_COOKIE": "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/pulse-cookie",
|
||||
"PULSE_SERVER": "unix:/run/user/1971/pulse/native",
|
||||
"SHELL": "/run/current-system/sw/bin/zsh",
|
||||
"TERM": "xterm-256color",
|
||||
"USER": "u0_a1",
|
||||
"WAYLAND_DISPLAY": "/run/user/1971/wayland-0",
|
||||
"XDG_RUNTIME_DIR": "/run/user/1971",
|
||||
"XDG_SESSION_CLASS": "user",
|
||||
"XDG_SESSION_TYPE": "tty",
|
||||
},
|
||||
"HOME": "/home/chronos",
|
||||
"SHELL": "/run/current-system/sw/bin/zsh",
|
||||
"TERM": "xterm-256color",
|
||||
"USER": "chronos",
|
||||
"XDG_RUNTIME_DIR": "/run/user/150",
|
||||
"XDG_SESSION_CLASS": "user",
|
||||
"XDG_SESSION_TYPE": "tty"},
|
||||
Chmod: make(bwrap.ChmodConfig),
|
||||
NewSession: true,
|
||||
DieWithParent: true,
|
||||
AsInit: true,
|
||||
}).SetUID(1971).SetGID(1971).
|
||||
Procfs("/proc").
|
||||
Tmpfs("/fortify", 4096).
|
||||
DevTmpfs("/dev").Mqueue("/dev/mqueue").
|
||||
Bind("/bin", "/bin").
|
||||
Bind("/usr/bin", "/usr/bin").
|
||||
Bind("/nix/store", "/nix/store").
|
||||
Bind("/run/current-system", "/run/current-system").
|
||||
Bind("/sys/block", "/sys/block", true).
|
||||
Bind("/sys/bus", "/sys/bus", true).
|
||||
Bind("/sys/class", "/sys/class", true).
|
||||
Bind("/sys/dev", "/sys/dev", true).
|
||||
Bind("/sys/devices", "/sys/devices", true).
|
||||
Bind("/run/opengl-driver", "/run/opengl-driver").
|
||||
Bind("/dev/dri", "/dev/dri", true, true, true).
|
||||
Bind("/etc", "/fortify/etc").
|
||||
Symlink("/fortify/etc/alsa", "/etc/alsa").
|
||||
Symlink("/fortify/etc/bashrc", "/etc/bashrc").
|
||||
Symlink("/fortify/etc/binfmt.d", "/etc/binfmt.d").
|
||||
Symlink("/fortify/etc/dbus-1", "/etc/dbus-1").
|
||||
Symlink("/fortify/etc/default", "/etc/default").
|
||||
Symlink("/fortify/etc/ethertypes", "/etc/ethertypes").
|
||||
Symlink("/fortify/etc/fonts", "/etc/fonts").
|
||||
Symlink("/fortify/etc/fstab", "/etc/fstab").
|
||||
Symlink("/fortify/etc/fuse.conf", "/etc/fuse.conf").
|
||||
Symlink("/fortify/etc/host.conf", "/etc/host.conf").
|
||||
Symlink("/fortify/etc/hostid", "/etc/hostid").
|
||||
Symlink("/fortify/etc/hostname", "/etc/hostname").
|
||||
Symlink("/fortify/etc/hostname.CHECKSUM", "/etc/hostname.CHECKSUM").
|
||||
Symlink("/fortify/etc/hosts", "/etc/hosts").
|
||||
Symlink("/fortify/etc/inputrc", "/etc/inputrc").
|
||||
Symlink("/fortify/etc/ipsec.d", "/etc/ipsec.d").
|
||||
Symlink("/fortify/etc/issue", "/etc/issue").
|
||||
Symlink("/fortify/etc/kbd", "/etc/kbd").
|
||||
Symlink("/fortify/etc/libblockdev", "/etc/libblockdev").
|
||||
Symlink("/fortify/etc/locale.conf", "/etc/locale.conf").
|
||||
Symlink("/fortify/etc/localtime", "/etc/localtime").
|
||||
Symlink("/fortify/etc/login.defs", "/etc/login.defs").
|
||||
Symlink("/fortify/etc/lsb-release", "/etc/lsb-release").
|
||||
Symlink("/fortify/etc/lvm", "/etc/lvm").
|
||||
Symlink("/fortify/etc/machine-id", "/etc/machine-id").
|
||||
Symlink("/fortify/etc/man_db.conf", "/etc/man_db.conf").
|
||||
Symlink("/fortify/etc/modprobe.d", "/etc/modprobe.d").
|
||||
Symlink("/fortify/etc/modules-load.d", "/etc/modules-load.d").
|
||||
}).SetUID(65534).SetGID(65534).
|
||||
Procfs("/proc").DevTmpfs("/dev").Mqueue("/dev/mqueue").
|
||||
Tmpfs("/dev/fortify", 4096).
|
||||
Bind("/bin", "/bin", false, true).
|
||||
Bind("/boot", "/boot", false, true).
|
||||
Bind("/etc", "/dev/fortify/etc").
|
||||
Bind("/home", "/home", false, true).
|
||||
Bind("/lib", "/lib", false, true).
|
||||
Bind("/lib64", "/lib64", false, true).
|
||||
Bind("/nix", "/nix", false, true).
|
||||
Bind("/root", "/root", false, true).
|
||||
Bind("/srv", "/srv", false, true).
|
||||
Bind("/sys", "/sys", false, true).
|
||||
Bind("/usr", "/usr", false, true).
|
||||
Bind("/var", "/var", false, true).
|
||||
Bind("/run/agetty.reload", "/run/agetty.reload", false, true).
|
||||
Bind("/run/binfmt", "/run/binfmt", false, true).
|
||||
Bind("/run/booted-system", "/run/booted-system", false, true).
|
||||
Bind("/run/credentials", "/run/credentials", false, true).
|
||||
Bind("/run/cryptsetup", "/run/cryptsetup", false, true).
|
||||
Bind("/run/current-system", "/run/current-system", false, true).
|
||||
Bind("/run/host", "/run/host", false, true).
|
||||
Bind("/run/keys", "/run/keys", false, true).
|
||||
Bind("/run/libvirt", "/run/libvirt", false, true).
|
||||
Bind("/run/libvirtd.pid", "/run/libvirtd.pid", false, true).
|
||||
Bind("/run/lock", "/run/lock", false, true).
|
||||
Bind("/run/log", "/run/log", false, true).
|
||||
Bind("/run/lvm", "/run/lvm", false, true).
|
||||
Bind("/run/mount", "/run/mount", false, true).
|
||||
Bind("/run/NetworkManager", "/run/NetworkManager", false, true).
|
||||
Bind("/run/nginx", "/run/nginx", false, true).
|
||||
Bind("/run/nixos", "/run/nixos", false, true).
|
||||
Bind("/run/nscd", "/run/nscd", false, true).
|
||||
Bind("/run/opengl-driver", "/run/opengl-driver", false, true).
|
||||
Bind("/run/pppd", "/run/pppd", false, true).
|
||||
Bind("/run/resolvconf", "/run/resolvconf", false, true).
|
||||
Bind("/run/sddm", "/run/sddm", false, true).
|
||||
Bind("/run/store", "/run/store", false, true).
|
||||
Bind("/run/syncoid", "/run/syncoid", false, true).
|
||||
Bind("/run/system", "/run/system", false, true).
|
||||
Bind("/run/systemd", "/run/systemd", false, true).
|
||||
Bind("/run/tmpfiles.d", "/run/tmpfiles.d", false, true).
|
||||
Bind("/run/udev", "/run/udev", false, true).
|
||||
Bind("/run/udisks2", "/run/udisks2", false, true).
|
||||
Bind("/run/utmp", "/run/utmp", false, true).
|
||||
Bind("/run/virtlogd.pid", "/run/virtlogd.pid", false, true).
|
||||
Bind("/run/wrappers", "/run/wrappers", false, true).
|
||||
Bind("/run/zed.pid", "/run/zed.pid", false, true).
|
||||
Bind("/run/zed.state", "/run/zed.state", false, true).
|
||||
Symlink("/dev/fortify/etc/alsa", "/etc/alsa").
|
||||
Symlink("/dev/fortify/etc/bashrc", "/etc/bashrc").
|
||||
Symlink("/dev/fortify/etc/binfmt.d", "/etc/binfmt.d").
|
||||
Symlink("/dev/fortify/etc/dbus-1", "/etc/dbus-1").
|
||||
Symlink("/dev/fortify/etc/default", "/etc/default").
|
||||
Symlink("/dev/fortify/etc/ethertypes", "/etc/ethertypes").
|
||||
Symlink("/dev/fortify/etc/fonts", "/etc/fonts").
|
||||
Symlink("/dev/fortify/etc/fstab", "/etc/fstab").
|
||||
Symlink("/dev/fortify/etc/fuse.conf", "/etc/fuse.conf").
|
||||
Symlink("/dev/fortify/etc/host.conf", "/etc/host.conf").
|
||||
Symlink("/dev/fortify/etc/hostid", "/etc/hostid").
|
||||
Symlink("/dev/fortify/etc/hostname", "/etc/hostname").
|
||||
Symlink("/dev/fortify/etc/hostname.CHECKSUM", "/etc/hostname.CHECKSUM").
|
||||
Symlink("/dev/fortify/etc/hosts", "/etc/hosts").
|
||||
Symlink("/dev/fortify/etc/inputrc", "/etc/inputrc").
|
||||
Symlink("/dev/fortify/etc/ipsec.d", "/etc/ipsec.d").
|
||||
Symlink("/dev/fortify/etc/issue", "/etc/issue").
|
||||
Symlink("/dev/fortify/etc/kbd", "/etc/kbd").
|
||||
Symlink("/dev/fortify/etc/libblockdev", "/etc/libblockdev").
|
||||
Symlink("/dev/fortify/etc/locale.conf", "/etc/locale.conf").
|
||||
Symlink("/dev/fortify/etc/localtime", "/etc/localtime").
|
||||
Symlink("/dev/fortify/etc/login.defs", "/etc/login.defs").
|
||||
Symlink("/dev/fortify/etc/lsb-release", "/etc/lsb-release").
|
||||
Symlink("/dev/fortify/etc/lvm", "/etc/lvm").
|
||||
Symlink("/dev/fortify/etc/machine-id", "/etc/machine-id").
|
||||
Symlink("/dev/fortify/etc/man_db.conf", "/etc/man_db.conf").
|
||||
Symlink("/dev/fortify/etc/modprobe.d", "/etc/modprobe.d").
|
||||
Symlink("/dev/fortify/etc/modules-load.d", "/etc/modules-load.d").
|
||||
Symlink("/proc/mounts", "/etc/mtab").
|
||||
Symlink("/fortify/etc/nanorc", "/etc/nanorc").
|
||||
Symlink("/fortify/etc/netgroup", "/etc/netgroup").
|
||||
Symlink("/fortify/etc/NetworkManager", "/etc/NetworkManager").
|
||||
Symlink("/fortify/etc/nix", "/etc/nix").
|
||||
Symlink("/fortify/etc/nixos", "/etc/nixos").
|
||||
Symlink("/fortify/etc/NIXOS", "/etc/NIXOS").
|
||||
Symlink("/fortify/etc/nscd.conf", "/etc/nscd.conf").
|
||||
Symlink("/fortify/etc/nsswitch.conf", "/etc/nsswitch.conf").
|
||||
Symlink("/fortify/etc/opensnitchd", "/etc/opensnitchd").
|
||||
Symlink("/fortify/etc/os-release", "/etc/os-release").
|
||||
Symlink("/fortify/etc/pam", "/etc/pam").
|
||||
Symlink("/fortify/etc/pam.d", "/etc/pam.d").
|
||||
Symlink("/fortify/etc/pipewire", "/etc/pipewire").
|
||||
Symlink("/fortify/etc/pki", "/etc/pki").
|
||||
Symlink("/fortify/etc/polkit-1", "/etc/polkit-1").
|
||||
Symlink("/fortify/etc/profile", "/etc/profile").
|
||||
Symlink("/fortify/etc/protocols", "/etc/protocols").
|
||||
Symlink("/fortify/etc/qemu", "/etc/qemu").
|
||||
Symlink("/fortify/etc/resolv.conf", "/etc/resolv.conf").
|
||||
Symlink("/fortify/etc/resolvconf.conf", "/etc/resolvconf.conf").
|
||||
Symlink("/fortify/etc/rpc", "/etc/rpc").
|
||||
Symlink("/fortify/etc/samba", "/etc/samba").
|
||||
Symlink("/fortify/etc/sddm.conf", "/etc/sddm.conf").
|
||||
Symlink("/fortify/etc/secureboot", "/etc/secureboot").
|
||||
Symlink("/fortify/etc/services", "/etc/services").
|
||||
Symlink("/fortify/etc/set-environment", "/etc/set-environment").
|
||||
Symlink("/fortify/etc/shadow", "/etc/shadow").
|
||||
Symlink("/fortify/etc/shells", "/etc/shells").
|
||||
Symlink("/fortify/etc/ssh", "/etc/ssh").
|
||||
Symlink("/fortify/etc/ssl", "/etc/ssl").
|
||||
Symlink("/fortify/etc/static", "/etc/static").
|
||||
Symlink("/fortify/etc/subgid", "/etc/subgid").
|
||||
Symlink("/fortify/etc/subuid", "/etc/subuid").
|
||||
Symlink("/fortify/etc/sudoers", "/etc/sudoers").
|
||||
Symlink("/fortify/etc/sysctl.d", "/etc/sysctl.d").
|
||||
Symlink("/fortify/etc/systemd", "/etc/systemd").
|
||||
Symlink("/fortify/etc/terminfo", "/etc/terminfo").
|
||||
Symlink("/fortify/etc/tmpfiles.d", "/etc/tmpfiles.d").
|
||||
Symlink("/fortify/etc/udev", "/etc/udev").
|
||||
Symlink("/fortify/etc/udisks2", "/etc/udisks2").
|
||||
Symlink("/fortify/etc/UPower", "/etc/UPower").
|
||||
Symlink("/fortify/etc/vconsole.conf", "/etc/vconsole.conf").
|
||||
Symlink("/fortify/etc/X11", "/etc/X11").
|
||||
Symlink("/fortify/etc/zfs", "/etc/zfs").
|
||||
Symlink("/fortify/etc/zinputrc", "/etc/zinputrc").
|
||||
Symlink("/fortify/etc/zoneinfo", "/etc/zoneinfo").
|
||||
Symlink("/fortify/etc/zprofile", "/etc/zprofile").
|
||||
Symlink("/fortify/etc/zshenv", "/etc/zshenv").
|
||||
Symlink("/fortify/etc/zshrc", "/etc/zshrc").
|
||||
Bind("/tmp/fortify.1971/tmpdir/1", "/tmp", false, true).
|
||||
Symlink("/dev/fortify/etc/nanorc", "/etc/nanorc").
|
||||
Symlink("/dev/fortify/etc/netgroup", "/etc/netgroup").
|
||||
Symlink("/dev/fortify/etc/NetworkManager", "/etc/NetworkManager").
|
||||
Symlink("/dev/fortify/etc/nix", "/etc/nix").
|
||||
Symlink("/dev/fortify/etc/nixos", "/etc/nixos").
|
||||
Symlink("/dev/fortify/etc/NIXOS", "/etc/NIXOS").
|
||||
Symlink("/dev/fortify/etc/nscd.conf", "/etc/nscd.conf").
|
||||
Symlink("/dev/fortify/etc/nsswitch.conf", "/etc/nsswitch.conf").
|
||||
Symlink("/dev/fortify/etc/opensnitchd", "/etc/opensnitchd").
|
||||
Symlink("/dev/fortify/etc/os-release", "/etc/os-release").
|
||||
Symlink("/dev/fortify/etc/pam", "/etc/pam").
|
||||
Symlink("/dev/fortify/etc/pam.d", "/etc/pam.d").
|
||||
Symlink("/dev/fortify/etc/pipewire", "/etc/pipewire").
|
||||
Symlink("/dev/fortify/etc/pki", "/etc/pki").
|
||||
Symlink("/dev/fortify/etc/polkit-1", "/etc/polkit-1").
|
||||
Symlink("/dev/fortify/etc/profile", "/etc/profile").
|
||||
Symlink("/dev/fortify/etc/protocols", "/etc/protocols").
|
||||
Symlink("/dev/fortify/etc/qemu", "/etc/qemu").
|
||||
Symlink("/dev/fortify/etc/resolv.conf", "/etc/resolv.conf").
|
||||
Symlink("/dev/fortify/etc/resolvconf.conf", "/etc/resolvconf.conf").
|
||||
Symlink("/dev/fortify/etc/rpc", "/etc/rpc").
|
||||
Symlink("/dev/fortify/etc/samba", "/etc/samba").
|
||||
Symlink("/dev/fortify/etc/sddm.conf", "/etc/sddm.conf").
|
||||
Symlink("/dev/fortify/etc/secureboot", "/etc/secureboot").
|
||||
Symlink("/dev/fortify/etc/services", "/etc/services").
|
||||
Symlink("/dev/fortify/etc/set-environment", "/etc/set-environment").
|
||||
Symlink("/dev/fortify/etc/shadow", "/etc/shadow").
|
||||
Symlink("/dev/fortify/etc/shells", "/etc/shells").
|
||||
Symlink("/dev/fortify/etc/ssh", "/etc/ssh").
|
||||
Symlink("/dev/fortify/etc/ssl", "/etc/ssl").
|
||||
Symlink("/dev/fortify/etc/static", "/etc/static").
|
||||
Symlink("/dev/fortify/etc/subgid", "/etc/subgid").
|
||||
Symlink("/dev/fortify/etc/subuid", "/etc/subuid").
|
||||
Symlink("/dev/fortify/etc/sudoers", "/etc/sudoers").
|
||||
Symlink("/dev/fortify/etc/sysctl.d", "/etc/sysctl.d").
|
||||
Symlink("/dev/fortify/etc/systemd", "/etc/systemd").
|
||||
Symlink("/dev/fortify/etc/terminfo", "/etc/terminfo").
|
||||
Symlink("/dev/fortify/etc/tmpfiles.d", "/etc/tmpfiles.d").
|
||||
Symlink("/dev/fortify/etc/udev", "/etc/udev").
|
||||
Symlink("/dev/fortify/etc/udisks2", "/etc/udisks2").
|
||||
Symlink("/dev/fortify/etc/UPower", "/etc/UPower").
|
||||
Symlink("/dev/fortify/etc/vconsole.conf", "/etc/vconsole.conf").
|
||||
Symlink("/dev/fortify/etc/X11", "/etc/X11").
|
||||
Symlink("/dev/fortify/etc/zfs", "/etc/zfs").
|
||||
Symlink("/dev/fortify/etc/zinputrc", "/etc/zinputrc").
|
||||
Symlink("/dev/fortify/etc/zoneinfo", "/etc/zoneinfo").
|
||||
Symlink("/dev/fortify/etc/zprofile", "/etc/zprofile").
|
||||
Symlink("/dev/fortify/etc/zshenv", "/etc/zshenv").
|
||||
Symlink("/dev/fortify/etc/zshrc", "/etc/zshrc").
|
||||
Bind("/tmp/fortify.1971/tmpdir/150", "/tmp", false, true).
|
||||
Tmpfs("/tmp/fortify.1971", 1048576).
|
||||
Tmpfs("/run/user", 1048576).
|
||||
Tmpfs("/run/user/1971", 8388608).
|
||||
Bind("/var/lib/persist/module/fortify/0/1", "/var/lib/persist/module/fortify/0/1", false, true).
|
||||
Bind("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/passwd", "/etc/passwd").
|
||||
Bind("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/group", "/etc/group").
|
||||
Bind("/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1/wayland", "/run/user/1971/wayland-0").
|
||||
Bind("/run/user/1971/fortify/8e2c76b066dabe574cf073bdb46eb5c1/pulse", "/run/user/1971/pulse/native").
|
||||
Bind("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/pulse-cookie", "/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/pulse-cookie").
|
||||
Bind("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/bus", "/run/user/1971/bus").
|
||||
Bind("/tmp/fortify.1971/8e2c76b066dabe574cf073bdb46eb5c1/system_bus_socket", "/run/dbus/system_bus_socket").
|
||||
Tmpfs("/run/user/150", 8388608).
|
||||
Bind("/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac/passwd", "/etc/passwd").
|
||||
Bind("/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac/group", "/etc/group").
|
||||
Tmpfs("/var/run/nscd", 8192),
|
||||
},
|
||||
}
|
||||
|
||||
// fs methods are not implemented using a real FS
|
||||
// to help better understand filesystem access behaviour
|
||||
type stubNixOS struct {
|
||||
lookPathErr map[string]error
|
||||
usernameErr map[string]error
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Geteuid() int {
|
||||
return 1971
|
||||
}
|
||||
|
||||
func (s *stubNixOS) LookupEnv(key string) (string, bool) {
|
||||
switch key {
|
||||
case "SHELL":
|
||||
return "/run/current-system/sw/bin/zsh", true
|
||||
case "TERM":
|
||||
return "xterm-256color", true
|
||||
default:
|
||||
panic(fmt.Sprintf("attempted to access unexpected environment variable %q", key))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) TempDir() string {
|
||||
return "/tmp"
|
||||
}
|
||||
|
||||
func (s *stubNixOS) LookPath(file string) (string, error) {
|
||||
if s.lookPathErr != nil {
|
||||
if err, ok := s.lookPathErr[file]; ok {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
switch file {
|
||||
case "sudo":
|
||||
return "/run/wrappers/bin/sudo", nil
|
||||
default:
|
||||
panic(fmt.Sprintf("attempted to look up unexpected executable %q", file))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Executable() (string, error) {
|
||||
return "/home/ophestra/.nix-profile/bin/fortify", nil
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Lookup(username string) (*user.User, error) {
|
||||
if s.usernameErr != nil {
|
||||
if err, ok := s.usernameErr[username]; ok {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
switch username {
|
||||
case "chronos":
|
||||
return &user.User{
|
||||
Uid: "150",
|
||||
Gid: "101",
|
||||
Username: "chronos",
|
||||
HomeDir: "/home/chronos",
|
||||
}, nil
|
||||
default:
|
||||
return nil, user.UnknownUserError(username)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) ReadDir(name string) ([]fs.DirEntry, error) {
|
||||
switch name {
|
||||
case "/":
|
||||
return stubDirEntries("bin", "boot", "dev", "etc", "home", "lib",
|
||||
"lib64", "nix", "proc", "root", "run", "srv", "sys", "tmp", "usr", "var")
|
||||
case "/run":
|
||||
return stubDirEntries("agetty.reload", "binfmt", "booted-system",
|
||||
"credentials", "cryptsetup", "current-system", "dbus", "host", "keys",
|
||||
"libvirt", "libvirtd.pid", "lock", "log", "lvm", "mount", "NetworkManager",
|
||||
"nginx", "nixos", "nscd", "opengl-driver", "pppd", "resolvconf", "sddm",
|
||||
"store", "syncoid", "system", "systemd", "tmpfiles.d", "udev", "udisks2",
|
||||
"user", "utmp", "virtlogd.pid", "wrappers", "zed.pid", "zed.state")
|
||||
case "/etc":
|
||||
return stubDirEntries("alsa", "bashrc", "binfmt.d", "dbus-1", "default",
|
||||
"ethertypes", "fonts", "fstab", "fuse.conf", "group", "host.conf", "hostid",
|
||||
"hostname", "hostname.CHECKSUM", "hosts", "inputrc", "ipsec.d", "issue", "kbd",
|
||||
"libblockdev", "locale.conf", "localtime", "login.defs", "lsb-release", "lvm",
|
||||
"machine-id", "man_db.conf", "modprobe.d", "modules-load.d", "mtab", "nanorc",
|
||||
"netgroup", "NetworkManager", "nix", "nixos", "NIXOS", "nscd.conf", "nsswitch.conf",
|
||||
"opensnitchd", "os-release", "pam", "pam.d", "passwd", "pipewire", "pki", "polkit-1",
|
||||
"profile", "protocols", "qemu", "resolv.conf", "resolvconf.conf", "rpc", "samba",
|
||||
"sddm.conf", "secureboot", "services", "set-environment", "shadow", "shells", "ssh",
|
||||
"ssl", "static", "subgid", "subuid", "sudoers", "sysctl.d", "systemd", "terminfo",
|
||||
"tmpfiles.d", "udev", "udisks2", "UPower", "vconsole.conf", "X11", "zfs", "zinputrc",
|
||||
"zoneinfo", "zprofile", "zshenv", "zshrc")
|
||||
default:
|
||||
panic(fmt.Sprintf("attempted to read unexpected directory %q", name))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Stat(name string) (fs.FileInfo, error) {
|
||||
switch name {
|
||||
case "/var/run/nscd":
|
||||
return nil, nil
|
||||
default:
|
||||
panic(fmt.Sprintf("attempted to stat unexpected path %q", name))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Open(name string) (fs.File, error) {
|
||||
switch name {
|
||||
default:
|
||||
panic(fmt.Sprintf("attempted to open unexpected file %q", name))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Exit(code int) {
|
||||
panic("called exit on stub with code " + strconv.Itoa(code))
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Paths() internal.Paths {
|
||||
return internal.Paths{
|
||||
SharePath: "/tmp/fortify.1971",
|
||||
RuntimePath: "/run/user/1971",
|
||||
RunDirPath: "/run/user/1971/fortify",
|
||||
}
|
||||
}
|
||||
|
@ -1,452 +0,0 @@
|
||||
package app_test
|
||||
|
||||
import (
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
var testCasesPd = []sealTestCase{
|
||||
{
|
||||
"nixos permissive defaults no enablements", new(stubNixOS),
|
||||
&fst.Config{
|
||||
Command: make([]string, 0),
|
||||
Confinement: fst.ConfinementConfig{
|
||||
AppID: 0,
|
||||
Username: "chronos",
|
||||
Outer: "/home/chronos",
|
||||
},
|
||||
},
|
||||
fst.ID{
|
||||
0x4a, 0x45, 0x0b, 0x65,
|
||||
0x96, 0xd7, 0xbc, 0x15,
|
||||
0xbd, 0x01, 0x78, 0x0e,
|
||||
0xb9, 0xa6, 0x07, 0xac,
|
||||
},
|
||||
system.New(1000000).
|
||||
Ensure("/tmp/fortify.1971", 0711).
|
||||
Ephemeral(system.Process, "/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac", 0711).
|
||||
Ensure("/tmp/fortify.1971/tmpdir", 0700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir", acl.Execute).
|
||||
Ensure("/tmp/fortify.1971/tmpdir/0", 01700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir/0", acl.Read, acl.Write, acl.Execute).
|
||||
Ensure("/run/user/1971/fortify", 0700).UpdatePermType(system.User, "/run/user/1971/fortify", acl.Execute).
|
||||
Ensure("/run/user/1971", 0700).UpdatePermType(system.User, "/run/user/1971", acl.Execute). // this is ordered as is because the previous Ensure only calls mkdir if XDG_RUNTIME_DIR is unset
|
||||
Ephemeral(system.Process, "/run/user/1971/fortify/4a450b6596d7bc15bd01780eb9a607ac", 0700).UpdatePermType(system.Process, "/run/user/1971/fortify/4a450b6596d7bc15bd01780eb9a607ac", acl.Execute).
|
||||
WriteType(system.Process, "/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac/passwd", "chronos:x:65534:65534:Fortify:/home/chronos:/run/current-system/sw/bin/zsh\n").
|
||||
WriteType(system.Process, "/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac/group", "fortify:x:65534:\n"),
|
||||
(&bwrap.Config{
|
||||
Net: true,
|
||||
UserNS: true,
|
||||
Clearenv: true,
|
||||
Chdir: "/home/chronos",
|
||||
SetEnv: map[string]string{
|
||||
"HOME": "/home/chronos",
|
||||
"SHELL": "/run/current-system/sw/bin/zsh",
|
||||
"TERM": "xterm-256color",
|
||||
"USER": "chronos",
|
||||
"XDG_RUNTIME_DIR": "/run/user/65534",
|
||||
"XDG_SESSION_CLASS": "user",
|
||||
"XDG_SESSION_TYPE": "tty"},
|
||||
Chmod: make(bwrap.ChmodConfig),
|
||||
DieWithParent: true,
|
||||
AsInit: true,
|
||||
}).SetUID(65534).SetGID(65534).
|
||||
Procfs("/proc").
|
||||
Tmpfs("/fortify", 4096).
|
||||
DevTmpfs("/dev").Mqueue("/dev/mqueue").
|
||||
Bind("/bin", "/bin", false, true).
|
||||
Bind("/boot", "/boot", false, true).
|
||||
Bind("/home", "/home", false, true).
|
||||
Bind("/lib", "/lib", false, true).
|
||||
Bind("/lib64", "/lib64", false, true).
|
||||
Bind("/nix", "/nix", false, true).
|
||||
Bind("/root", "/root", false, true).
|
||||
Bind("/srv", "/srv", false, true).
|
||||
Bind("/sys", "/sys", false, true).
|
||||
Bind("/usr", "/usr", false, true).
|
||||
Bind("/var", "/var", false, true).
|
||||
Bind("/run/agetty.reload", "/run/agetty.reload", false, true).
|
||||
Bind("/run/binfmt", "/run/binfmt", false, true).
|
||||
Bind("/run/booted-system", "/run/booted-system", false, true).
|
||||
Bind("/run/credentials", "/run/credentials", false, true).
|
||||
Bind("/run/cryptsetup", "/run/cryptsetup", false, true).
|
||||
Bind("/run/current-system", "/run/current-system", false, true).
|
||||
Bind("/run/host", "/run/host", false, true).
|
||||
Bind("/run/keys", "/run/keys", false, true).
|
||||
Bind("/run/libvirt", "/run/libvirt", false, true).
|
||||
Bind("/run/libvirtd.pid", "/run/libvirtd.pid", false, true).
|
||||
Bind("/run/lock", "/run/lock", false, true).
|
||||
Bind("/run/log", "/run/log", false, true).
|
||||
Bind("/run/lvm", "/run/lvm", false, true).
|
||||
Bind("/run/mount", "/run/mount", false, true).
|
||||
Bind("/run/NetworkManager", "/run/NetworkManager", false, true).
|
||||
Bind("/run/nginx", "/run/nginx", false, true).
|
||||
Bind("/run/nixos", "/run/nixos", false, true).
|
||||
Bind("/run/nscd", "/run/nscd", false, true).
|
||||
Bind("/run/opengl-driver", "/run/opengl-driver", false, true).
|
||||
Bind("/run/pppd", "/run/pppd", false, true).
|
||||
Bind("/run/resolvconf", "/run/resolvconf", false, true).
|
||||
Bind("/run/sddm", "/run/sddm", false, true).
|
||||
Bind("/run/store", "/run/store", false, true).
|
||||
Bind("/run/syncoid", "/run/syncoid", false, true).
|
||||
Bind("/run/system", "/run/system", false, true).
|
||||
Bind("/run/systemd", "/run/systemd", false, true).
|
||||
Bind("/run/tmpfiles.d", "/run/tmpfiles.d", false, true).
|
||||
Bind("/run/udev", "/run/udev", false, true).
|
||||
Bind("/run/udisks2", "/run/udisks2", false, true).
|
||||
Bind("/run/utmp", "/run/utmp", false, true).
|
||||
Bind("/run/virtlogd.pid", "/run/virtlogd.pid", false, true).
|
||||
Bind("/run/wrappers", "/run/wrappers", false, true).
|
||||
Bind("/run/zed.pid", "/run/zed.pid", false, true).
|
||||
Bind("/run/zed.state", "/run/zed.state", false, true).
|
||||
Bind("/etc", "/fortify/etc").
|
||||
Symlink("/fortify/etc/alsa", "/etc/alsa").
|
||||
Symlink("/fortify/etc/bashrc", "/etc/bashrc").
|
||||
Symlink("/fortify/etc/binfmt.d", "/etc/binfmt.d").
|
||||
Symlink("/fortify/etc/dbus-1", "/etc/dbus-1").
|
||||
Symlink("/fortify/etc/default", "/etc/default").
|
||||
Symlink("/fortify/etc/ethertypes", "/etc/ethertypes").
|
||||
Symlink("/fortify/etc/fonts", "/etc/fonts").
|
||||
Symlink("/fortify/etc/fstab", "/etc/fstab").
|
||||
Symlink("/fortify/etc/fuse.conf", "/etc/fuse.conf").
|
||||
Symlink("/fortify/etc/host.conf", "/etc/host.conf").
|
||||
Symlink("/fortify/etc/hostid", "/etc/hostid").
|
||||
Symlink("/fortify/etc/hostname", "/etc/hostname").
|
||||
Symlink("/fortify/etc/hostname.CHECKSUM", "/etc/hostname.CHECKSUM").
|
||||
Symlink("/fortify/etc/hosts", "/etc/hosts").
|
||||
Symlink("/fortify/etc/inputrc", "/etc/inputrc").
|
||||
Symlink("/fortify/etc/ipsec.d", "/etc/ipsec.d").
|
||||
Symlink("/fortify/etc/issue", "/etc/issue").
|
||||
Symlink("/fortify/etc/kbd", "/etc/kbd").
|
||||
Symlink("/fortify/etc/libblockdev", "/etc/libblockdev").
|
||||
Symlink("/fortify/etc/locale.conf", "/etc/locale.conf").
|
||||
Symlink("/fortify/etc/localtime", "/etc/localtime").
|
||||
Symlink("/fortify/etc/login.defs", "/etc/login.defs").
|
||||
Symlink("/fortify/etc/lsb-release", "/etc/lsb-release").
|
||||
Symlink("/fortify/etc/lvm", "/etc/lvm").
|
||||
Symlink("/fortify/etc/machine-id", "/etc/machine-id").
|
||||
Symlink("/fortify/etc/man_db.conf", "/etc/man_db.conf").
|
||||
Symlink("/fortify/etc/modprobe.d", "/etc/modprobe.d").
|
||||
Symlink("/fortify/etc/modules-load.d", "/etc/modules-load.d").
|
||||
Symlink("/proc/mounts", "/etc/mtab").
|
||||
Symlink("/fortify/etc/nanorc", "/etc/nanorc").
|
||||
Symlink("/fortify/etc/netgroup", "/etc/netgroup").
|
||||
Symlink("/fortify/etc/NetworkManager", "/etc/NetworkManager").
|
||||
Symlink("/fortify/etc/nix", "/etc/nix").
|
||||
Symlink("/fortify/etc/nixos", "/etc/nixos").
|
||||
Symlink("/fortify/etc/NIXOS", "/etc/NIXOS").
|
||||
Symlink("/fortify/etc/nscd.conf", "/etc/nscd.conf").
|
||||
Symlink("/fortify/etc/nsswitch.conf", "/etc/nsswitch.conf").
|
||||
Symlink("/fortify/etc/opensnitchd", "/etc/opensnitchd").
|
||||
Symlink("/fortify/etc/os-release", "/etc/os-release").
|
||||
Symlink("/fortify/etc/pam", "/etc/pam").
|
||||
Symlink("/fortify/etc/pam.d", "/etc/pam.d").
|
||||
Symlink("/fortify/etc/pipewire", "/etc/pipewire").
|
||||
Symlink("/fortify/etc/pki", "/etc/pki").
|
||||
Symlink("/fortify/etc/polkit-1", "/etc/polkit-1").
|
||||
Symlink("/fortify/etc/profile", "/etc/profile").
|
||||
Symlink("/fortify/etc/protocols", "/etc/protocols").
|
||||
Symlink("/fortify/etc/qemu", "/etc/qemu").
|
||||
Symlink("/fortify/etc/resolv.conf", "/etc/resolv.conf").
|
||||
Symlink("/fortify/etc/resolvconf.conf", "/etc/resolvconf.conf").
|
||||
Symlink("/fortify/etc/rpc", "/etc/rpc").
|
||||
Symlink("/fortify/etc/samba", "/etc/samba").
|
||||
Symlink("/fortify/etc/sddm.conf", "/etc/sddm.conf").
|
||||
Symlink("/fortify/etc/secureboot", "/etc/secureboot").
|
||||
Symlink("/fortify/etc/services", "/etc/services").
|
||||
Symlink("/fortify/etc/set-environment", "/etc/set-environment").
|
||||
Symlink("/fortify/etc/shadow", "/etc/shadow").
|
||||
Symlink("/fortify/etc/shells", "/etc/shells").
|
||||
Symlink("/fortify/etc/ssh", "/etc/ssh").
|
||||
Symlink("/fortify/etc/ssl", "/etc/ssl").
|
||||
Symlink("/fortify/etc/static", "/etc/static").
|
||||
Symlink("/fortify/etc/subgid", "/etc/subgid").
|
||||
Symlink("/fortify/etc/subuid", "/etc/subuid").
|
||||
Symlink("/fortify/etc/sudoers", "/etc/sudoers").
|
||||
Symlink("/fortify/etc/sysctl.d", "/etc/sysctl.d").
|
||||
Symlink("/fortify/etc/systemd", "/etc/systemd").
|
||||
Symlink("/fortify/etc/terminfo", "/etc/terminfo").
|
||||
Symlink("/fortify/etc/tmpfiles.d", "/etc/tmpfiles.d").
|
||||
Symlink("/fortify/etc/udev", "/etc/udev").
|
||||
Symlink("/fortify/etc/udisks2", "/etc/udisks2").
|
||||
Symlink("/fortify/etc/UPower", "/etc/UPower").
|
||||
Symlink("/fortify/etc/vconsole.conf", "/etc/vconsole.conf").
|
||||
Symlink("/fortify/etc/X11", "/etc/X11").
|
||||
Symlink("/fortify/etc/zfs", "/etc/zfs").
|
||||
Symlink("/fortify/etc/zinputrc", "/etc/zinputrc").
|
||||
Symlink("/fortify/etc/zoneinfo", "/etc/zoneinfo").
|
||||
Symlink("/fortify/etc/zprofile", "/etc/zprofile").
|
||||
Symlink("/fortify/etc/zshenv", "/etc/zshenv").
|
||||
Symlink("/fortify/etc/zshrc", "/etc/zshrc").
|
||||
Bind("/tmp/fortify.1971/tmpdir/0", "/tmp", false, true).
|
||||
Tmpfs("/tmp/fortify.1971", 1048576).
|
||||
Tmpfs("/run/user", 1048576).
|
||||
Tmpfs("/run/user/65534", 8388608).
|
||||
Bind("/home/chronos", "/home/chronos", false, true).
|
||||
Bind("/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac/passwd", "/etc/passwd").
|
||||
Bind("/tmp/fortify.1971/4a450b6596d7bc15bd01780eb9a607ac/group", "/etc/group").
|
||||
Tmpfs("/var/run/nscd", 8192),
|
||||
},
|
||||
{
|
||||
"nixos permissive defaults chromium", new(stubNixOS),
|
||||
&fst.Config{
|
||||
ID: "org.chromium.Chromium",
|
||||
Command: []string{"/run/current-system/sw/bin/zsh", "-c", "exec chromium "},
|
||||
Confinement: fst.ConfinementConfig{
|
||||
AppID: 9,
|
||||
Groups: []string{"video"},
|
||||
Username: "chronos",
|
||||
Outer: "/home/chronos",
|
||||
SessionBus: &dbus.Config{
|
||||
Talk: []string{
|
||||
"org.freedesktop.Notifications",
|
||||
"org.freedesktop.FileManager1",
|
||||
"org.freedesktop.ScreenSaver",
|
||||
"org.freedesktop.secrets",
|
||||
"org.kde.kwalletd5",
|
||||
"org.kde.kwalletd6",
|
||||
"org.gnome.SessionManager",
|
||||
},
|
||||
Own: []string{
|
||||
"org.chromium.Chromium.*",
|
||||
"org.mpris.MediaPlayer2.org.chromium.Chromium.*",
|
||||
"org.mpris.MediaPlayer2.chromium.*",
|
||||
},
|
||||
Call: map[string]string{
|
||||
"org.freedesktop.portal.*": "*",
|
||||
},
|
||||
Broadcast: map[string]string{
|
||||
"org.freedesktop.portal.*": "@/org/freedesktop/portal/*",
|
||||
},
|
||||
Filter: true,
|
||||
},
|
||||
SystemBus: &dbus.Config{
|
||||
Talk: []string{
|
||||
"org.bluez",
|
||||
"org.freedesktop.Avahi",
|
||||
"org.freedesktop.UPower",
|
||||
},
|
||||
Filter: true,
|
||||
},
|
||||
Enablements: system.EWayland.Mask() | system.EDBus.Mask() | system.EPulse.Mask(),
|
||||
},
|
||||
},
|
||||
fst.ID{
|
||||
0xeb, 0xf0, 0x83, 0xd1,
|
||||
0xb1, 0x75, 0x91, 0x17,
|
||||
0x82, 0xd4, 0x13, 0x36,
|
||||
0x9b, 0x64, 0xce, 0x7c,
|
||||
},
|
||||
system.New(1000009).
|
||||
Ensure("/tmp/fortify.1971", 0711).
|
||||
Ephemeral(system.Process, "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c", 0711).
|
||||
Ensure("/tmp/fortify.1971/tmpdir", 0700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir", acl.Execute).
|
||||
Ensure("/tmp/fortify.1971/tmpdir/9", 01700).UpdatePermType(system.User, "/tmp/fortify.1971/tmpdir/9", acl.Read, acl.Write, acl.Execute).
|
||||
Ensure("/run/user/1971/fortify", 0700).UpdatePermType(system.User, "/run/user/1971/fortify", acl.Execute).
|
||||
Ensure("/run/user/1971", 0700).UpdatePermType(system.User, "/run/user/1971", acl.Execute). // this is ordered as is because the previous Ensure only calls mkdir if XDG_RUNTIME_DIR is unset
|
||||
Ephemeral(system.Process, "/run/user/1971/fortify/ebf083d1b175911782d413369b64ce7c", 0700).UpdatePermType(system.Process, "/run/user/1971/fortify/ebf083d1b175911782d413369b64ce7c", acl.Execute).
|
||||
WriteType(system.Process, "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/passwd", "chronos:x:65534:65534:Fortify:/home/chronos:/run/current-system/sw/bin/zsh\n").
|
||||
WriteType(system.Process, "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/group", "fortify:x:65534:\n").
|
||||
Ensure("/tmp/fortify.1971/wayland", 0711).
|
||||
Wayland("/tmp/fortify.1971/wayland/ebf083d1b175911782d413369b64ce7c", "/run/user/1971/wayland-0", "org.chromium.Chromium", "ebf083d1b175911782d413369b64ce7c").
|
||||
Link("/run/user/1971/pulse/native", "/run/user/1971/fortify/ebf083d1b175911782d413369b64ce7c/pulse").
|
||||
CopyFile("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/pulse-cookie", "/home/ophestra/xdg/config/pulse/cookie").
|
||||
MustProxyDBus("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/bus", &dbus.Config{
|
||||
Talk: []string{
|
||||
"org.freedesktop.Notifications",
|
||||
"org.freedesktop.FileManager1",
|
||||
"org.freedesktop.ScreenSaver",
|
||||
"org.freedesktop.secrets",
|
||||
"org.kde.kwalletd5",
|
||||
"org.kde.kwalletd6",
|
||||
"org.gnome.SessionManager",
|
||||
},
|
||||
Own: []string{
|
||||
"org.chromium.Chromium.*",
|
||||
"org.mpris.MediaPlayer2.org.chromium.Chromium.*",
|
||||
"org.mpris.MediaPlayer2.chromium.*",
|
||||
},
|
||||
Call: map[string]string{
|
||||
"org.freedesktop.portal.*": "*",
|
||||
},
|
||||
Broadcast: map[string]string{
|
||||
"org.freedesktop.portal.*": "@/org/freedesktop/portal/*",
|
||||
},
|
||||
Filter: true,
|
||||
}, "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/system_bus_socket", &dbus.Config{
|
||||
Talk: []string{
|
||||
"org.bluez",
|
||||
"org.freedesktop.Avahi",
|
||||
"org.freedesktop.UPower",
|
||||
},
|
||||
Filter: true,
|
||||
}).
|
||||
UpdatePerm("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/bus", acl.Read, acl.Write).
|
||||
UpdatePerm("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/system_bus_socket", acl.Read, acl.Write),
|
||||
(&bwrap.Config{
|
||||
Net: true,
|
||||
UserNS: true,
|
||||
Chdir: "/home/chronos",
|
||||
Clearenv: true,
|
||||
SetEnv: map[string]string{
|
||||
"DBUS_SESSION_BUS_ADDRESS": "unix:path=/run/user/65534/bus",
|
||||
"DBUS_SYSTEM_BUS_ADDRESS": "unix:path=/run/dbus/system_bus_socket",
|
||||
"HOME": "/home/chronos",
|
||||
"PULSE_COOKIE": "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/pulse-cookie",
|
||||
"PULSE_SERVER": "unix:/run/user/65534/pulse/native",
|
||||
"SHELL": "/run/current-system/sw/bin/zsh",
|
||||
"TERM": "xterm-256color",
|
||||
"USER": "chronos",
|
||||
"WAYLAND_DISPLAY": "/run/user/65534/wayland-0",
|
||||
"XDG_RUNTIME_DIR": "/run/user/65534",
|
||||
"XDG_SESSION_CLASS": "user",
|
||||
"XDG_SESSION_TYPE": "tty",
|
||||
},
|
||||
Chmod: make(bwrap.ChmodConfig),
|
||||
DieWithParent: true,
|
||||
AsInit: true,
|
||||
}).SetUID(65534).SetGID(65534).
|
||||
Procfs("/proc").
|
||||
Tmpfs("/fortify", 4096).
|
||||
DevTmpfs("/dev").Mqueue("/dev/mqueue").
|
||||
Bind("/bin", "/bin", false, true).
|
||||
Bind("/boot", "/boot", false, true).
|
||||
Bind("/home", "/home", false, true).
|
||||
Bind("/lib", "/lib", false, true).
|
||||
Bind("/lib64", "/lib64", false, true).
|
||||
Bind("/nix", "/nix", false, true).
|
||||
Bind("/root", "/root", false, true).
|
||||
Bind("/srv", "/srv", false, true).
|
||||
Bind("/sys", "/sys", false, true).
|
||||
Bind("/usr", "/usr", false, true).
|
||||
Bind("/var", "/var", false, true).
|
||||
Bind("/run/agetty.reload", "/run/agetty.reload", false, true).
|
||||
Bind("/run/binfmt", "/run/binfmt", false, true).
|
||||
Bind("/run/booted-system", "/run/booted-system", false, true).
|
||||
Bind("/run/credentials", "/run/credentials", false, true).
|
||||
Bind("/run/cryptsetup", "/run/cryptsetup", false, true).
|
||||
Bind("/run/current-system", "/run/current-system", false, true).
|
||||
Bind("/run/host", "/run/host", false, true).
|
||||
Bind("/run/keys", "/run/keys", false, true).
|
||||
Bind("/run/libvirt", "/run/libvirt", false, true).
|
||||
Bind("/run/libvirtd.pid", "/run/libvirtd.pid", false, true).
|
||||
Bind("/run/lock", "/run/lock", false, true).
|
||||
Bind("/run/log", "/run/log", false, true).
|
||||
Bind("/run/lvm", "/run/lvm", false, true).
|
||||
Bind("/run/mount", "/run/mount", false, true).
|
||||
Bind("/run/NetworkManager", "/run/NetworkManager", false, true).
|
||||
Bind("/run/nginx", "/run/nginx", false, true).
|
||||
Bind("/run/nixos", "/run/nixos", false, true).
|
||||
Bind("/run/nscd", "/run/nscd", false, true).
|
||||
Bind("/run/opengl-driver", "/run/opengl-driver", false, true).
|
||||
Bind("/run/pppd", "/run/pppd", false, true).
|
||||
Bind("/run/resolvconf", "/run/resolvconf", false, true).
|
||||
Bind("/run/sddm", "/run/sddm", false, true).
|
||||
Bind("/run/store", "/run/store", false, true).
|
||||
Bind("/run/syncoid", "/run/syncoid", false, true).
|
||||
Bind("/run/system", "/run/system", false, true).
|
||||
Bind("/run/systemd", "/run/systemd", false, true).
|
||||
Bind("/run/tmpfiles.d", "/run/tmpfiles.d", false, true).
|
||||
Bind("/run/udev", "/run/udev", false, true).
|
||||
Bind("/run/udisks2", "/run/udisks2", false, true).
|
||||
Bind("/run/utmp", "/run/utmp", false, true).
|
||||
Bind("/run/virtlogd.pid", "/run/virtlogd.pid", false, true).
|
||||
Bind("/run/wrappers", "/run/wrappers", false, true).
|
||||
Bind("/run/zed.pid", "/run/zed.pid", false, true).
|
||||
Bind("/run/zed.state", "/run/zed.state", false, true).
|
||||
Bind("/dev/dri", "/dev/dri", true, true, true).
|
||||
Bind("/etc", "/fortify/etc").
|
||||
Symlink("/fortify/etc/alsa", "/etc/alsa").
|
||||
Symlink("/fortify/etc/bashrc", "/etc/bashrc").
|
||||
Symlink("/fortify/etc/binfmt.d", "/etc/binfmt.d").
|
||||
Symlink("/fortify/etc/dbus-1", "/etc/dbus-1").
|
||||
Symlink("/fortify/etc/default", "/etc/default").
|
||||
Symlink("/fortify/etc/ethertypes", "/etc/ethertypes").
|
||||
Symlink("/fortify/etc/fonts", "/etc/fonts").
|
||||
Symlink("/fortify/etc/fstab", "/etc/fstab").
|
||||
Symlink("/fortify/etc/fuse.conf", "/etc/fuse.conf").
|
||||
Symlink("/fortify/etc/host.conf", "/etc/host.conf").
|
||||
Symlink("/fortify/etc/hostid", "/etc/hostid").
|
||||
Symlink("/fortify/etc/hostname", "/etc/hostname").
|
||||
Symlink("/fortify/etc/hostname.CHECKSUM", "/etc/hostname.CHECKSUM").
|
||||
Symlink("/fortify/etc/hosts", "/etc/hosts").
|
||||
Symlink("/fortify/etc/inputrc", "/etc/inputrc").
|
||||
Symlink("/fortify/etc/ipsec.d", "/etc/ipsec.d").
|
||||
Symlink("/fortify/etc/issue", "/etc/issue").
|
||||
Symlink("/fortify/etc/kbd", "/etc/kbd").
|
||||
Symlink("/fortify/etc/libblockdev", "/etc/libblockdev").
|
||||
Symlink("/fortify/etc/locale.conf", "/etc/locale.conf").
|
||||
Symlink("/fortify/etc/localtime", "/etc/localtime").
|
||||
Symlink("/fortify/etc/login.defs", "/etc/login.defs").
|
||||
Symlink("/fortify/etc/lsb-release", "/etc/lsb-release").
|
||||
Symlink("/fortify/etc/lvm", "/etc/lvm").
|
||||
Symlink("/fortify/etc/machine-id", "/etc/machine-id").
|
||||
Symlink("/fortify/etc/man_db.conf", "/etc/man_db.conf").
|
||||
Symlink("/fortify/etc/modprobe.d", "/etc/modprobe.d").
|
||||
Symlink("/fortify/etc/modules-load.d", "/etc/modules-load.d").
|
||||
Symlink("/proc/mounts", "/etc/mtab").
|
||||
Symlink("/fortify/etc/nanorc", "/etc/nanorc").
|
||||
Symlink("/fortify/etc/netgroup", "/etc/netgroup").
|
||||
Symlink("/fortify/etc/NetworkManager", "/etc/NetworkManager").
|
||||
Symlink("/fortify/etc/nix", "/etc/nix").
|
||||
Symlink("/fortify/etc/nixos", "/etc/nixos").
|
||||
Symlink("/fortify/etc/NIXOS", "/etc/NIXOS").
|
||||
Symlink("/fortify/etc/nscd.conf", "/etc/nscd.conf").
|
||||
Symlink("/fortify/etc/nsswitch.conf", "/etc/nsswitch.conf").
|
||||
Symlink("/fortify/etc/opensnitchd", "/etc/opensnitchd").
|
||||
Symlink("/fortify/etc/os-release", "/etc/os-release").
|
||||
Symlink("/fortify/etc/pam", "/etc/pam").
|
||||
Symlink("/fortify/etc/pam.d", "/etc/pam.d").
|
||||
Symlink("/fortify/etc/pipewire", "/etc/pipewire").
|
||||
Symlink("/fortify/etc/pki", "/etc/pki").
|
||||
Symlink("/fortify/etc/polkit-1", "/etc/polkit-1").
|
||||
Symlink("/fortify/etc/profile", "/etc/profile").
|
||||
Symlink("/fortify/etc/protocols", "/etc/protocols").
|
||||
Symlink("/fortify/etc/qemu", "/etc/qemu").
|
||||
Symlink("/fortify/etc/resolv.conf", "/etc/resolv.conf").
|
||||
Symlink("/fortify/etc/resolvconf.conf", "/etc/resolvconf.conf").
|
||||
Symlink("/fortify/etc/rpc", "/etc/rpc").
|
||||
Symlink("/fortify/etc/samba", "/etc/samba").
|
||||
Symlink("/fortify/etc/sddm.conf", "/etc/sddm.conf").
|
||||
Symlink("/fortify/etc/secureboot", "/etc/secureboot").
|
||||
Symlink("/fortify/etc/services", "/etc/services").
|
||||
Symlink("/fortify/etc/set-environment", "/etc/set-environment").
|
||||
Symlink("/fortify/etc/shadow", "/etc/shadow").
|
||||
Symlink("/fortify/etc/shells", "/etc/shells").
|
||||
Symlink("/fortify/etc/ssh", "/etc/ssh").
|
||||
Symlink("/fortify/etc/ssl", "/etc/ssl").
|
||||
Symlink("/fortify/etc/static", "/etc/static").
|
||||
Symlink("/fortify/etc/subgid", "/etc/subgid").
|
||||
Symlink("/fortify/etc/subuid", "/etc/subuid").
|
||||
Symlink("/fortify/etc/sudoers", "/etc/sudoers").
|
||||
Symlink("/fortify/etc/sysctl.d", "/etc/sysctl.d").
|
||||
Symlink("/fortify/etc/systemd", "/etc/systemd").
|
||||
Symlink("/fortify/etc/terminfo", "/etc/terminfo").
|
||||
Symlink("/fortify/etc/tmpfiles.d", "/etc/tmpfiles.d").
|
||||
Symlink("/fortify/etc/udev", "/etc/udev").
|
||||
Symlink("/fortify/etc/udisks2", "/etc/udisks2").
|
||||
Symlink("/fortify/etc/UPower", "/etc/UPower").
|
||||
Symlink("/fortify/etc/vconsole.conf", "/etc/vconsole.conf").
|
||||
Symlink("/fortify/etc/X11", "/etc/X11").
|
||||
Symlink("/fortify/etc/zfs", "/etc/zfs").
|
||||
Symlink("/fortify/etc/zinputrc", "/etc/zinputrc").
|
||||
Symlink("/fortify/etc/zoneinfo", "/etc/zoneinfo").
|
||||
Symlink("/fortify/etc/zprofile", "/etc/zprofile").
|
||||
Symlink("/fortify/etc/zshenv", "/etc/zshenv").
|
||||
Symlink("/fortify/etc/zshrc", "/etc/zshrc").
|
||||
Bind("/tmp/fortify.1971/tmpdir/9", "/tmp", false, true).
|
||||
Tmpfs("/tmp/fortify.1971", 1048576).
|
||||
Tmpfs("/run/user", 1048576).
|
||||
Tmpfs("/run/user/65534", 8388608).
|
||||
Bind("/home/chronos", "/home/chronos", false, true).
|
||||
Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/passwd", "/etc/passwd").
|
||||
Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/group", "/etc/group").
|
||||
Bind("/tmp/fortify.1971/wayland/ebf083d1b175911782d413369b64ce7c", "/run/user/65534/wayland-0").
|
||||
Bind("/run/user/1971/fortify/ebf083d1b175911782d413369b64ce7c/pulse", "/run/user/65534/pulse/native").
|
||||
Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/pulse-cookie", "/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/pulse-cookie").
|
||||
Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/bus", "/run/user/65534/bus").
|
||||
Bind("/tmp/fortify.1971/ebf083d1b175911782d413369b64ce7c/system_bus_socket", "/run/dbus/system_bus_socket").
|
||||
Tmpfs("/var/run/nscd", 8192),
|
||||
},
|
||||
}
|
@ -1,153 +0,0 @@
|
||||
package app_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os/user"
|
||||
"strconv"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
)
|
||||
|
||||
// fs methods are not implemented using a real FS
|
||||
// to help better understand filesystem access behaviour
|
||||
type stubNixOS struct {
|
||||
lookPathErr map[string]error
|
||||
usernameErr map[string]error
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Geteuid() int {
|
||||
return 1971
|
||||
}
|
||||
|
||||
func (s *stubNixOS) LookupEnv(key string) (string, bool) {
|
||||
switch key {
|
||||
case "SHELL":
|
||||
return "/run/current-system/sw/bin/zsh", true
|
||||
case "TERM":
|
||||
return "xterm-256color", true
|
||||
case "WAYLAND_DISPLAY":
|
||||
return "wayland-0", true
|
||||
case "PULSE_COOKIE":
|
||||
return "", false
|
||||
case "HOME":
|
||||
return "/home/ophestra", true
|
||||
case "XDG_CONFIG_HOME":
|
||||
return "/home/ophestra/xdg/config", true
|
||||
default:
|
||||
panic(fmt.Sprintf("attempted to access unexpected environment variable %q", key))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) TempDir() string {
|
||||
return "/tmp"
|
||||
}
|
||||
|
||||
func (s *stubNixOS) LookPath(file string) (string, error) {
|
||||
if s.lookPathErr != nil {
|
||||
if err, ok := s.lookPathErr[file]; ok {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
switch file {
|
||||
case "sudo":
|
||||
return "/run/wrappers/bin/sudo", nil
|
||||
case "machinectl":
|
||||
return "/home/ophestra/.nix-profile/bin/machinectl", nil
|
||||
default:
|
||||
panic(fmt.Sprintf("attempted to look up unexpected executable %q", file))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Executable() (string, error) {
|
||||
return "/home/ophestra/.nix-profile/bin/fortify", nil
|
||||
}
|
||||
|
||||
func (s *stubNixOS) LookupGroup(name string) (*user.Group, error) {
|
||||
switch name {
|
||||
case "video":
|
||||
return &user.Group{Gid: "26", Name: "video"}, nil
|
||||
default:
|
||||
return nil, user.UnknownGroupError(name)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) ReadDir(name string) ([]fs.DirEntry, error) {
|
||||
switch name {
|
||||
case "/":
|
||||
return stubDirEntries("bin", "boot", "dev", "etc", "home", "lib",
|
||||
"lib64", "nix", "proc", "root", "run", "srv", "sys", "tmp", "usr", "var")
|
||||
case "/run":
|
||||
return stubDirEntries("agetty.reload", "binfmt", "booted-system",
|
||||
"credentials", "cryptsetup", "current-system", "dbus", "host", "keys",
|
||||
"libvirt", "libvirtd.pid", "lock", "log", "lvm", "mount", "NetworkManager",
|
||||
"nginx", "nixos", "nscd", "opengl-driver", "pppd", "resolvconf", "sddm",
|
||||
"store", "syncoid", "system", "systemd", "tmpfiles.d", "udev", "udisks2",
|
||||
"user", "utmp", "virtlogd.pid", "wrappers", "zed.pid", "zed.state")
|
||||
case "/etc":
|
||||
return stubDirEntries("alsa", "bashrc", "binfmt.d", "dbus-1", "default",
|
||||
"ethertypes", "fonts", "fstab", "fuse.conf", "group", "host.conf", "hostid",
|
||||
"hostname", "hostname.CHECKSUM", "hosts", "inputrc", "ipsec.d", "issue", "kbd",
|
||||
"libblockdev", "locale.conf", "localtime", "login.defs", "lsb-release", "lvm",
|
||||
"machine-id", "man_db.conf", "modprobe.d", "modules-load.d", "mtab", "nanorc",
|
||||
"netgroup", "NetworkManager", "nix", "nixos", "NIXOS", "nscd.conf", "nsswitch.conf",
|
||||
"opensnitchd", "os-release", "pam", "pam.d", "passwd", "pipewire", "pki", "polkit-1",
|
||||
"profile", "protocols", "qemu", "resolv.conf", "resolvconf.conf", "rpc", "samba",
|
||||
"sddm.conf", "secureboot", "services", "set-environment", "shadow", "shells", "ssh",
|
||||
"ssl", "static", "subgid", "subuid", "sudoers", "sysctl.d", "systemd", "terminfo",
|
||||
"tmpfiles.d", "udev", "udisks2", "UPower", "vconsole.conf", "X11", "zfs", "zinputrc",
|
||||
"zoneinfo", "zprofile", "zshenv", "zshrc")
|
||||
default:
|
||||
panic(fmt.Sprintf("attempted to read unexpected directory %q", name))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Stat(name string) (fs.FileInfo, error) {
|
||||
switch name {
|
||||
case "/var/run/nscd":
|
||||
return nil, nil
|
||||
case "/run/user/1971/pulse":
|
||||
return nil, nil
|
||||
case "/run/user/1971/pulse/native":
|
||||
return stubFileInfoMode(0666), nil
|
||||
case "/home/ophestra/.pulse-cookie":
|
||||
return stubFileInfoIsDir(true), nil
|
||||
case "/home/ophestra/xdg/config/pulse/cookie":
|
||||
return stubFileInfoIsDir(false), nil
|
||||
default:
|
||||
panic(fmt.Sprintf("attempted to stat unexpected path %q", name))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Open(name string) (fs.File, error) {
|
||||
switch name {
|
||||
default:
|
||||
panic(fmt.Sprintf("attempted to open unexpected file %q", name))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Exit(code int) {
|
||||
panic("called exit on stub with code " + strconv.Itoa(code))
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Stdout() io.Writer {
|
||||
panic("requested stdout")
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Paths() linux.Paths {
|
||||
return linux.Paths{
|
||||
SharePath: "/tmp/fortify.1971",
|
||||
RuntimePath: "/run/user/1971",
|
||||
RunDirPath: "/run/user/1971/fortify",
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubNixOS) Uid(aid int) (int, error) {
|
||||
return 1000000 + 0*10000 + aid, nil
|
||||
}
|
||||
|
||||
func (s *stubNixOS) SdBooted() bool {
|
||||
return true
|
||||
}
|
@ -4,26 +4,24 @@ import (
|
||||
"io/fs"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/internal/app"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/app"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
type sealTestCase struct {
|
||||
name string
|
||||
os linux.System
|
||||
config *fst.Config
|
||||
id fst.ID
|
||||
os internal.System
|
||||
config *app.Config
|
||||
id app.ID
|
||||
wantSys *system.I
|
||||
wantBwrap *bwrap.Config
|
||||
}
|
||||
|
||||
func TestApp(t *testing.T) {
|
||||
testCases := append(testCasesPd, testCasesNixos...)
|
||||
testCases := append(testCasesNixos)
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
@ -81,55 +79,3 @@ func (p stubDirEntryPath) Type() fs.FileMode {
|
||||
func (p stubDirEntryPath) Info() (fs.FileInfo, error) {
|
||||
panic("attempted to call Info")
|
||||
}
|
||||
|
||||
type stubFileInfoMode fs.FileMode
|
||||
|
||||
func (s stubFileInfoMode) Name() string {
|
||||
panic("attempted to call Name")
|
||||
}
|
||||
|
||||
func (s stubFileInfoMode) Size() int64 {
|
||||
panic("attempted to call Size")
|
||||
}
|
||||
|
||||
func (s stubFileInfoMode) Mode() fs.FileMode {
|
||||
return fs.FileMode(s)
|
||||
}
|
||||
|
||||
func (s stubFileInfoMode) ModTime() time.Time {
|
||||
panic("attempted to call ModTime")
|
||||
}
|
||||
|
||||
func (s stubFileInfoMode) IsDir() bool {
|
||||
panic("attempted to call IsDir")
|
||||
}
|
||||
|
||||
func (s stubFileInfoMode) Sys() any {
|
||||
panic("attempted to call Sys")
|
||||
}
|
||||
|
||||
type stubFileInfoIsDir bool
|
||||
|
||||
func (s stubFileInfoIsDir) Name() string {
|
||||
panic("attempted to call Name")
|
||||
}
|
||||
|
||||
func (s stubFileInfoIsDir) Size() int64 {
|
||||
panic("attempted to call Size")
|
||||
}
|
||||
|
||||
func (s stubFileInfoIsDir) Mode() fs.FileMode {
|
||||
panic("attempted to call Mode")
|
||||
}
|
||||
|
||||
func (s stubFileInfoIsDir) ModTime() time.Time {
|
||||
panic("attempted to call ModTime")
|
||||
}
|
||||
|
||||
func (s stubFileInfoIsDir) IsDir() bool {
|
||||
return bool(s)
|
||||
}
|
||||
|
||||
func (s stubFileInfoIsDir) Sys() any {
|
||||
panic("attempted to call Sys")
|
||||
}
|
||||
|
@ -1,22 +1,23 @@
|
||||
package fst
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
const fTmp = "/fortify"
|
||||
|
||||
// Config is used to seal an *App
|
||||
type Config struct {
|
||||
// D-Bus application ID
|
||||
ID string `json:"id"`
|
||||
// username of the target user to switch to
|
||||
User string `json:"user"`
|
||||
// value passed through to the child process as its argv
|
||||
Command []string `json:"command"`
|
||||
// string representation of the child's launch method
|
||||
Method string `json:"method"`
|
||||
|
||||
// child confinement configuration
|
||||
Confinement ConfinementConfig `json:"confinement"`
|
||||
@ -24,16 +25,6 @@ type Config struct {
|
||||
|
||||
// ConfinementConfig defines fortified child's confinement
|
||||
type ConfinementConfig struct {
|
||||
// numerical application id, determines uid in the init namespace
|
||||
AppID int `json:"app_id"`
|
||||
// list of supplementary groups to inherit
|
||||
Groups []string `json:"groups"`
|
||||
// passwd username in the sandbox, defaults to chronos
|
||||
Username string `json:"username,omitempty"`
|
||||
// home directory in sandbox, empty for outer
|
||||
Inner string `json:"home_inner"`
|
||||
// home directory in init namespace
|
||||
Outer string `json:"home"`
|
||||
// bwrap sandbox confinement configuration
|
||||
Sandbox *SandboxConfig `json:"sandbox"`
|
||||
|
||||
@ -56,14 +47,10 @@ type SandboxConfig struct {
|
||||
UserNS bool `json:"userns,omitempty"`
|
||||
// share net namespace
|
||||
Net bool `json:"net,omitempty"`
|
||||
// share all devices
|
||||
Dev bool `json:"dev,omitempty"`
|
||||
// do not run in new session
|
||||
NoNewSession bool `json:"no_new_session,omitempty"`
|
||||
// map target user uid to privileged user uid in the user namespace
|
||||
MapRealUID bool `json:"map_real_uid"`
|
||||
// direct access to wayland socket
|
||||
DirectWayland bool `json:"direct_wayland,omitempty"`
|
||||
// mediated access to wayland socket
|
||||
Wayland bool `json:"wayland,omitempty"`
|
||||
|
||||
// final environment variables
|
||||
Env map[string]string `json:"env"`
|
||||
@ -71,8 +58,6 @@ type SandboxConfig struct {
|
||||
Filesystem []*FilesystemConfig `json:"filesystem"`
|
||||
// symlinks created inside the sandbox
|
||||
Link [][2]string `json:"symlink"`
|
||||
// automatically set up /etc symlinks
|
||||
AutoEtc bool `json:"auto_etc"`
|
||||
// paths to override by mounting tmpfs over them
|
||||
Override []string `json:"override"`
|
||||
}
|
||||
@ -92,16 +77,9 @@ type FilesystemConfig struct {
|
||||
|
||||
// Bwrap returns the address of the corresponding bwrap.Config to s.
|
||||
// Note that remaining tmpfs entries must be queued by the caller prior to launch.
|
||||
func (s *SandboxConfig) Bwrap(os linux.System) (*bwrap.Config, error) {
|
||||
func (s *SandboxConfig) Bwrap() *bwrap.Config {
|
||||
if s == nil {
|
||||
return nil, errors.New("nil sandbox config")
|
||||
}
|
||||
|
||||
var uid int
|
||||
if !s.MapRealUID {
|
||||
uid = 65534
|
||||
} else {
|
||||
uid = os.Geteuid()
|
||||
return nil
|
||||
}
|
||||
|
||||
conf := (&bwrap.Config{
|
||||
@ -115,21 +93,11 @@ func (s *SandboxConfig) Bwrap(os linux.System) (*bwrap.Config, error) {
|
||||
AsInit: true,
|
||||
|
||||
// initialise map
|
||||
Chmod: make(bwrap.ChmodConfig),
|
||||
Chmod: make(map[string]os.FileMode),
|
||||
}).
|
||||
SetUID(uid).SetGID(uid).
|
||||
Procfs("/proc").
|
||||
Tmpfs(fTmp, 4*1024)
|
||||
|
||||
if !s.Dev {
|
||||
conf.DevTmpfs("/dev").Mqueue("/dev/mqueue")
|
||||
} else {
|
||||
conf.Bind("/dev", "/dev", false, true, true)
|
||||
}
|
||||
|
||||
if !s.AutoEtc {
|
||||
conf.Dir("/etc")
|
||||
}
|
||||
SetUID(65534).SetGID(65534).
|
||||
Procfs("/proc").DevTmpfs("/dev").Mqueue("/dev/mqueue").
|
||||
Tmpfs("/dev/fortify", 4*1024)
|
||||
|
||||
for _, c := range s.Filesystem {
|
||||
if c == nil {
|
||||
@ -147,35 +115,14 @@ func (s *SandboxConfig) Bwrap(os linux.System) (*bwrap.Config, error) {
|
||||
conf.Symlink(l[0], l[1])
|
||||
}
|
||||
|
||||
if s.AutoEtc {
|
||||
conf.Bind("/etc", fTmp+"/etc")
|
||||
|
||||
// link host /etc contents to prevent passwd/group from being overwritten
|
||||
if d, err := os.ReadDir("/etc"); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
for _, ent := range d {
|
||||
name := ent.Name()
|
||||
switch name {
|
||||
case "passwd":
|
||||
case "group":
|
||||
|
||||
case "mtab":
|
||||
conf.Symlink("/proc/mounts", "/etc/"+name)
|
||||
default:
|
||||
conf.Symlink(fTmp+"/etc/"+name, "/etc/"+name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return conf, nil
|
||||
return conf
|
||||
}
|
||||
|
||||
// Template returns a fully populated instance of Config.
|
||||
func Template() *Config {
|
||||
return &Config{
|
||||
ID: "org.chromium.Chromium",
|
||||
ID: "org.chromium.Chromium",
|
||||
User: "chronos",
|
||||
Command: []string{
|
||||
"chromium",
|
||||
"--ignore-gpu-blocklist",
|
||||
@ -183,20 +130,14 @@ func Template() *Config {
|
||||
"--enable-features=UseOzonePlatform",
|
||||
"--ozone-platform=wayland",
|
||||
},
|
||||
Method: "sudo",
|
||||
Confinement: ConfinementConfig{
|
||||
AppID: 9,
|
||||
Groups: []string{"video"},
|
||||
Username: "chronos",
|
||||
Outer: "/var/lib/persist/home/org.chromium.Chromium",
|
||||
Inner: "/var/lib/fortify",
|
||||
Sandbox: &SandboxConfig{
|
||||
Hostname: "localhost",
|
||||
UserNS: true,
|
||||
Net: true,
|
||||
NoNewSession: true,
|
||||
MapRealUID: true,
|
||||
Dev: true,
|
||||
DirectWayland: false,
|
||||
Hostname: "localhost",
|
||||
UserNS: true,
|
||||
Net: true,
|
||||
NoNewSession: true,
|
||||
Wayland: false,
|
||||
// example API credentials pulled from Google Chrome
|
||||
// DO NOT USE THESE IN A REAL BROWSER
|
||||
Env: map[string]string{
|
||||
@ -205,15 +146,12 @@ func Template() *Config {
|
||||
"GOOGLE_DEFAULT_CLIENT_SECRET": "OTJgUOQcT7lO7GsGZq2G4IlT",
|
||||
},
|
||||
Filesystem: []*FilesystemConfig{
|
||||
{Src: "/nix/store"},
|
||||
{Src: "/run/current-system"},
|
||||
{Src: "/run/opengl-driver"},
|
||||
{Src: "/var/db/nix-channels"},
|
||||
{Src: "/home/chronos", Write: true, Must: true},
|
||||
{Src: "/dev/dri", Device: true},
|
||||
{Src: "/nix"},
|
||||
{Src: "/storage/emulated/0", Write: true, Must: true},
|
||||
{Src: "/data/user/0", Dst: "/data/data", Write: true, Must: true},
|
||||
{Src: "/var/tmp", Write: true},
|
||||
},
|
||||
Link: [][2]string{{"/run/user/65534", "/run/user/150"}},
|
||||
AutoEtc: true,
|
||||
Link: [][2]string{{"/dev/fortify/etc", "/etc"}},
|
||||
Override: []string{"/var/run/nscd"},
|
||||
},
|
||||
SystemBus: &dbus.Config{
|
@ -1,13 +1,12 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
func NewWithID(id fst.ID, os linux.System) App {
|
||||
func NewWithID(id ID, os internal.System) App {
|
||||
a := new(app)
|
||||
a.id = &id
|
||||
a.os = os
|
||||
|
17
internal/app/id.go
Normal file
17
internal/app/id.go
Normal file
@ -0,0 +1,17 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
type ID [16]byte
|
||||
|
||||
func (a *ID) String() string {
|
||||
return hex.EncodeToString(a[:])
|
||||
}
|
||||
|
||||
func newAppID(id *ID) error {
|
||||
_, err := rand.Read(id[:])
|
||||
return err
|
||||
}
|
57
internal/app/launch.machinectl.go
Normal file
57
internal/app/launch.machinectl.go
Normal file
@ -0,0 +1,57 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
func (a *app) commandBuilderMachineCtl(shimEnv string) (args []string) {
|
||||
args = make([]string, 0, 9+len(a.seal.sys.bwrap.SetEnv))
|
||||
|
||||
// shell --uid=$USER
|
||||
args = append(args, "shell", "--uid="+a.seal.sys.user.Username)
|
||||
|
||||
// --quiet
|
||||
if !fmsg.Verbose() {
|
||||
args = append(args, "--quiet")
|
||||
}
|
||||
|
||||
// environ
|
||||
envQ := make([]string, 0, len(a.seal.sys.bwrap.SetEnv)+1)
|
||||
for k, v := range a.seal.sys.bwrap.SetEnv {
|
||||
envQ = append(envQ, "-E"+k+"="+v)
|
||||
}
|
||||
// add shim payload to environment for shim path
|
||||
envQ = append(envQ, "-E"+shimEnv)
|
||||
args = append(args, envQ...)
|
||||
|
||||
// -- .host
|
||||
args = append(args, "--", ".host")
|
||||
|
||||
// /bin/sh -c
|
||||
if sh, err := a.os.LookPath("sh"); err != nil {
|
||||
// hardcode /bin/sh path since it exists more often than not
|
||||
args = append(args, "/bin/sh", "-c")
|
||||
} else {
|
||||
args = append(args, sh, "-c")
|
||||
}
|
||||
|
||||
// build inner command expression ran as target user
|
||||
innerCommand := strings.Builder{}
|
||||
|
||||
// apply custom environment variables to activation environment
|
||||
innerCommand.WriteString("dbus-update-activation-environment --systemd")
|
||||
for k := range a.seal.sys.bwrap.SetEnv {
|
||||
innerCommand.WriteString(" " + k)
|
||||
}
|
||||
innerCommand.WriteString("; ")
|
||||
|
||||
// launch fortify as shim
|
||||
innerCommand.WriteString("exec " + a.seal.sys.executable + " shim")
|
||||
|
||||
// append inner command
|
||||
args = append(args, innerCommand.String())
|
||||
|
||||
return
|
||||
}
|
30
internal/app/launch.sudo.go
Normal file
30
internal/app/launch.sudo.go
Normal file
@ -0,0 +1,30 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
const (
|
||||
sudoAskPass = "SUDO_ASKPASS"
|
||||
)
|
||||
|
||||
func (a *app) commandBuilderSudo(shimEnv string) (args []string) {
|
||||
args = make([]string, 0, 8)
|
||||
|
||||
// -Hiu $USER
|
||||
args = append(args, "-Hiu", a.seal.sys.user.Username)
|
||||
|
||||
// -A?
|
||||
if _, ok := a.os.LookupEnv(sudoAskPass); ok {
|
||||
fmsg.VPrintln(sudoAskPass, "set, adding askpass flag")
|
||||
args = append(args, "-A")
|
||||
}
|
||||
|
||||
// shim payload
|
||||
args = append(args, shimEnv)
|
||||
|
||||
// -- $@
|
||||
args = append(args, "--", a.seal.sys.executable, "shim")
|
||||
|
||||
return
|
||||
}
|
@ -2,35 +2,45 @@ package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os/user"
|
||||
"path"
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
"git.gensokyo.uk/security/fortify/internal/state"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/shim"
|
||||
"git.ophivana.moe/security/fortify/internal/state"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
const (
|
||||
LaunchMethodSudo uint8 = iota
|
||||
LaunchMethodMachineCtl
|
||||
)
|
||||
|
||||
var method = [...]string{
|
||||
LaunchMethodSudo: "sudo",
|
||||
LaunchMethodMachineCtl: "systemd",
|
||||
}
|
||||
|
||||
var (
|
||||
ErrConfig = errors.New("no configuration to seal")
|
||||
ErrUser = errors.New("invalid aid")
|
||||
ErrHome = errors.New("invalid home directory")
|
||||
ErrName = errors.New("invalid username")
|
||||
)
|
||||
ErrUser = errors.New("unknown user")
|
||||
ErrLaunch = errors.New("invalid launch method")
|
||||
|
||||
var posixUsername = regexp.MustCompilePOSIX("^[a-z_]([A-Za-z0-9_-]{0,31}|[A-Za-z0-9_-]{0,30}\\$)$")
|
||||
ErrSudo = errors.New("sudo not available")
|
||||
ErrSystemd = errors.New("systemd not available")
|
||||
ErrMachineCtl = errors.New("machinectl not available")
|
||||
)
|
||||
|
||||
// appSeal seals the application with child-related information
|
||||
type appSeal struct {
|
||||
// app unique ID string representation
|
||||
id string
|
||||
// dbus proxy message buffer retriever
|
||||
dbusMsg func(f func(msgbuf []string))
|
||||
// wayland mediation, disabled if nil
|
||||
wl *shim.Wayland
|
||||
|
||||
// freedesktop application ID
|
||||
fid string
|
||||
@ -39,28 +49,30 @@ type appSeal struct {
|
||||
// persistent process state store
|
||||
store state.Store
|
||||
|
||||
// uint8 representation of launch method sealed from config
|
||||
launchOption uint8
|
||||
// process-specific share directory path
|
||||
share string
|
||||
// process-specific share directory path local to XDG_RUNTIME_DIR
|
||||
shareLocal string
|
||||
|
||||
// path to launcher program
|
||||
toolPath string
|
||||
// pass-through enablement tracking from config
|
||||
et system.Enablements
|
||||
// wayland socket direct access
|
||||
directWayland bool
|
||||
|
||||
// prevents sharing from happening twice
|
||||
shared bool
|
||||
// seal system-level component
|
||||
sys *appSealSys
|
||||
|
||||
linux.Paths
|
||||
internal.Paths
|
||||
|
||||
// protected by upstream mutex
|
||||
}
|
||||
|
||||
// Seal seals the app launch context
|
||||
func (a *app) Seal(config *fst.Config) error {
|
||||
func (a *app) Seal(config *Config) error {
|
||||
a.lock.Lock()
|
||||
defer a.lock.Unlock()
|
||||
|
||||
@ -84,63 +96,55 @@ func (a *app) Seal(config *fst.Config) error {
|
||||
seal.fid = config.ID
|
||||
seal.command = config.Command
|
||||
|
||||
// parses launch method text and looks up tool path
|
||||
switch config.Method {
|
||||
case method[LaunchMethodSudo]:
|
||||
seal.launchOption = LaunchMethodSudo
|
||||
if sudoPath, err := a.os.LookPath("sudo"); err != nil {
|
||||
return fmsg.WrapError(ErrSudo,
|
||||
"sudo not found")
|
||||
} else {
|
||||
seal.toolPath = sudoPath
|
||||
}
|
||||
case method[LaunchMethodMachineCtl]:
|
||||
seal.launchOption = LaunchMethodMachineCtl
|
||||
if !internal.SdBootedV {
|
||||
return fmsg.WrapError(ErrSystemd,
|
||||
"system has not been booted with systemd as init system")
|
||||
}
|
||||
|
||||
if machineCtlPath, err := a.os.LookPath("machinectl"); err != nil {
|
||||
return fmsg.WrapError(ErrMachineCtl,
|
||||
"machinectl not found")
|
||||
} else {
|
||||
seal.toolPath = machineCtlPath
|
||||
}
|
||||
default:
|
||||
return fmsg.WrapError(ErrLaunch,
|
||||
"invalid launch method")
|
||||
}
|
||||
|
||||
// create seal system component
|
||||
seal.sys = new(appSealSys)
|
||||
|
||||
// mapped uid
|
||||
if config.Confinement.Sandbox != nil && config.Confinement.Sandbox.MapRealUID {
|
||||
seal.sys.mappedID = a.os.Geteuid()
|
||||
// look up fortify executable path
|
||||
if p, err := a.os.Executable(); err != nil {
|
||||
return fmsg.WrapErrorSuffix(err, "cannot look up fortify executable path:")
|
||||
} else {
|
||||
seal.sys.mappedID = 65534
|
||||
seal.sys.executable = p
|
||||
}
|
||||
seal.sys.mappedIDString = strconv.Itoa(seal.sys.mappedID)
|
||||
seal.sys.runtime = path.Join("/run/user", seal.sys.mappedIDString)
|
||||
|
||||
// validate uid and set user info
|
||||
if config.Confinement.AppID < 0 || config.Confinement.AppID > 9999 {
|
||||
return fmsg.WrapError(ErrUser,
|
||||
fmt.Sprintf("aid %d out of range", config.Confinement.AppID))
|
||||
} else {
|
||||
seal.sys.user = appUser{
|
||||
aid: config.Confinement.AppID,
|
||||
as: strconv.Itoa(config.Confinement.AppID),
|
||||
data: config.Confinement.Outer,
|
||||
home: config.Confinement.Inner,
|
||||
username: config.Confinement.Username,
|
||||
}
|
||||
if seal.sys.user.username == "" {
|
||||
seal.sys.user.username = "chronos"
|
||||
} else if !posixUsername.MatchString(seal.sys.user.username) {
|
||||
return fmsg.WrapError(ErrName,
|
||||
fmt.Sprintf("invalid user name %q", seal.sys.user.username))
|
||||
}
|
||||
if seal.sys.user.data == "" || !path.IsAbs(seal.sys.user.data) {
|
||||
return fmsg.WrapError(ErrHome,
|
||||
fmt.Sprintf("invalid home directory %q", seal.sys.user.data))
|
||||
}
|
||||
if seal.sys.user.home == "" {
|
||||
seal.sys.user.home = seal.sys.user.data
|
||||
}
|
||||
|
||||
// invoke fsu for full uid
|
||||
if u, err := a.os.Uid(seal.sys.user.aid); err != nil {
|
||||
return fmsg.WrapErrorSuffix(err,
|
||||
"cannot obtain uid from fsu:")
|
||||
// look up user from system
|
||||
if u, err := a.os.Lookup(config.User); err != nil {
|
||||
if errors.As(err, new(user.UnknownUserError)) {
|
||||
return fmsg.WrapError(ErrUser, "unknown user", config.User)
|
||||
} else {
|
||||
seal.sys.user.uid = u
|
||||
seal.sys.user.us = strconv.Itoa(u)
|
||||
}
|
||||
|
||||
// resolve supplementary group ids from names
|
||||
seal.sys.user.supp = make([]string, len(config.Confinement.Groups))
|
||||
for i, name := range config.Confinement.Groups {
|
||||
if g, err := a.os.LookupGroup(name); err != nil {
|
||||
return fmsg.WrapError(err,
|
||||
fmt.Sprintf("unknown group %q", name))
|
||||
} else {
|
||||
seal.sys.user.supp[i] = g.Gid
|
||||
}
|
||||
// unreachable
|
||||
panic(err)
|
||||
}
|
||||
} else {
|
||||
seal.sys.user = u
|
||||
seal.sys.runtime = path.Join("/run/user", u.Uid)
|
||||
}
|
||||
|
||||
// map sandbox config to bwrap
|
||||
@ -148,17 +152,16 @@ func (a *app) Seal(config *fst.Config) error {
|
||||
fmsg.VPrintln("sandbox configuration not supplied, PROCEED WITH CAUTION")
|
||||
|
||||
// permissive defaults
|
||||
conf := &fst.SandboxConfig{
|
||||
conf := &SandboxConfig{
|
||||
UserNS: true,
|
||||
Net: true,
|
||||
NoNewSession: true,
|
||||
AutoEtc: true,
|
||||
}
|
||||
// bind entries in /
|
||||
if d, err := a.os.ReadDir("/"); err != nil {
|
||||
return err
|
||||
} else {
|
||||
b := make([]*fst.FilesystemConfig, 0, len(d))
|
||||
b := make([]*FilesystemConfig, 0, len(d))
|
||||
for _, ent := range d {
|
||||
p := "/" + ent.Name()
|
||||
switch p {
|
||||
@ -167,10 +170,11 @@ func (a *app) Seal(config *fst.Config) error {
|
||||
case "/run":
|
||||
case "/tmp":
|
||||
case "/mnt":
|
||||
case "/etc":
|
||||
|
||||
case "/etc":
|
||||
b = append(b, &FilesystemConfig{Src: p, Dst: "/dev/fortify/etc", Write: false, Must: true})
|
||||
default:
|
||||
b = append(b, &fst.FilesystemConfig{Src: p, Write: true, Must: true})
|
||||
b = append(b, &FilesystemConfig{Src: p, Write: true, Must: true})
|
||||
}
|
||||
}
|
||||
conf.Filesystem = append(conf.Filesystem, b...)
|
||||
@ -179,7 +183,7 @@ func (a *app) Seal(config *fst.Config) error {
|
||||
if d, err := a.os.ReadDir("/run"); err != nil {
|
||||
return err
|
||||
} else {
|
||||
b := make([]*fst.FilesystemConfig, 0, len(d))
|
||||
b := make([]*FilesystemConfig, 0, len(d))
|
||||
for _, ent := range d {
|
||||
name := ent.Name()
|
||||
switch name {
|
||||
@ -187,7 +191,7 @@ func (a *app) Seal(config *fst.Config) error {
|
||||
case "dbus":
|
||||
default:
|
||||
p := "/run/" + name
|
||||
b = append(b, &fst.FilesystemConfig{Src: p, Write: true, Must: true})
|
||||
b = append(b, &FilesystemConfig{Src: p, Write: true, Must: true})
|
||||
}
|
||||
}
|
||||
conf.Filesystem = append(conf.Filesystem, b...)
|
||||
@ -199,29 +203,60 @@ func (a *app) Seal(config *fst.Config) error {
|
||||
}
|
||||
// bind GPU stuff
|
||||
if config.Confinement.Enablements.Has(system.EX11) || config.Confinement.Enablements.Has(system.EWayland) {
|
||||
conf.Filesystem = append(conf.Filesystem, &fst.FilesystemConfig{Src: "/dev/dri", Device: true})
|
||||
conf.Filesystem = append(conf.Filesystem, &FilesystemConfig{Src: "/dev/dri", Device: true})
|
||||
}
|
||||
// link host /etc to prevent passwd/group from being overwritten
|
||||
if d, err := a.os.ReadDir("/etc"); err != nil {
|
||||
return err
|
||||
} else {
|
||||
b := make([][2]string, 0, len(d))
|
||||
for _, ent := range d {
|
||||
name := ent.Name()
|
||||
switch name {
|
||||
case "passwd":
|
||||
case "group":
|
||||
|
||||
case "mtab":
|
||||
b = append(b, [2]string{
|
||||
"/proc/mounts",
|
||||
"/etc/" + name,
|
||||
})
|
||||
default:
|
||||
b = append(b, [2]string{
|
||||
"/dev/fortify/etc/" + name,
|
||||
"/etc/" + name,
|
||||
})
|
||||
}
|
||||
}
|
||||
conf.Link = append(conf.Link, b...)
|
||||
}
|
||||
|
||||
config.Confinement.Sandbox = conf
|
||||
}
|
||||
seal.directWayland = config.Confinement.Sandbox.DirectWayland
|
||||
if b, err := config.Confinement.Sandbox.Bwrap(a.os); err != nil {
|
||||
return err
|
||||
} else {
|
||||
seal.sys.bwrap = b
|
||||
}
|
||||
seal.sys.bwrap = config.Confinement.Sandbox.Bwrap()
|
||||
seal.sys.override = config.Confinement.Sandbox.Override
|
||||
if seal.sys.bwrap.SetEnv == nil {
|
||||
seal.sys.bwrap.SetEnv = make(map[string]string)
|
||||
}
|
||||
|
||||
// create wayland struct and client wait channel if mediated wayland is enabled
|
||||
// this field being set enables mediated wayland setup later on
|
||||
if config.Confinement.Sandbox.Wayland {
|
||||
seal.wl = shim.NewWayland()
|
||||
}
|
||||
|
||||
// open process state store
|
||||
// the simple store only starts holding an open file after first action
|
||||
// store activity begins after Start is called and must end before Wait
|
||||
seal.store = state.NewMulti(seal.RunDirPath)
|
||||
seal.store = state.NewSimple(seal.RunDirPath, seal.sys.user.Uid)
|
||||
|
||||
// initialise system interface with full uid
|
||||
seal.sys.I = system.New(seal.sys.user.uid)
|
||||
// parse string UID
|
||||
if u, err := strconv.Atoi(seal.sys.user.Uid); err != nil {
|
||||
// unreachable unless kernel bug
|
||||
panic("uid parse")
|
||||
} else {
|
||||
seal.sys.I = system.New(u)
|
||||
}
|
||||
|
||||
// pass through enablements
|
||||
seal.et = config.Confinement.Enablements
|
||||
@ -232,11 +267,13 @@ func (a *app) Seal(config *fst.Config) error {
|
||||
}
|
||||
|
||||
// verbose log seal information
|
||||
fmsg.VPrintf("created application seal for uid %s (%s) groups: %v, command: %s",
|
||||
seal.sys.user.us, seal.sys.user.username, config.Confinement.Groups, config.Command)
|
||||
fmsg.VPrintln("created application seal as user",
|
||||
seal.sys.user.Username, "("+seal.sys.user.Uid+"),",
|
||||
"method:", config.Method+",",
|
||||
"launcher:", seal.toolPath+",",
|
||||
"command:", config.Command)
|
||||
|
||||
// seal app and release lock
|
||||
a.seal = seal
|
||||
a.ct = newAppCt(config)
|
||||
return nil
|
||||
}
|
||||
|
@ -3,9 +3,9 @@ package app
|
||||
import (
|
||||
"path"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -22,10 +22,8 @@ func (seal *appSeal) shareDBus(config [2]*dbus.Config) error {
|
||||
sessionPath, systemPath := path.Join(seal.share, "bus"), path.Join(seal.share, "system_bus_socket")
|
||||
|
||||
// configure dbus proxy
|
||||
if f, err := seal.sys.ProxyDBus(config[0], config[1], sessionPath, systemPath); err != nil {
|
||||
if err := seal.sys.ProxyDBus(config[0], config[1], sessionPath, systemPath); err != nil {
|
||||
return err
|
||||
} else {
|
||||
seal.dbusMsg = f
|
||||
}
|
||||
|
||||
// share proxy sockets
|
||||
|
@ -4,10 +4,10 @@ import (
|
||||
"errors"
|
||||
"path"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -23,7 +23,7 @@ var (
|
||||
ErrXDisplay = errors.New(display + " unset")
|
||||
)
|
||||
|
||||
func (seal *appSeal) shareDisplay(os linux.System) error {
|
||||
func (seal *appSeal) shareDisplay(os internal.System) error {
|
||||
// pass $TERM to launcher
|
||||
if t, ok := os.LookupEnv(term); ok {
|
||||
seal.sys.bwrap.SetEnv[term] = t
|
||||
@ -31,36 +31,23 @@ func (seal *appSeal) shareDisplay(os linux.System) error {
|
||||
|
||||
// set up wayland
|
||||
if seal.et.Has(system.EWayland) {
|
||||
var wp string
|
||||
if wd, ok := os.LookupEnv(waylandDisplay); !ok {
|
||||
return fmsg.WrapError(ErrWayland,
|
||||
"WAYLAND_DISPLAY is not set")
|
||||
} else {
|
||||
wp = path.Join(seal.RuntimePath, wd)
|
||||
}
|
||||
|
||||
w := path.Join(seal.sys.runtime, "wayland-0")
|
||||
seal.sys.bwrap.SetEnv[waylandDisplay] = w
|
||||
|
||||
if seal.directWayland {
|
||||
} else if seal.wl == nil {
|
||||
// hardlink wayland socket
|
||||
wp := path.Join(seal.RuntimePath, wd)
|
||||
wpi := path.Join(seal.shareLocal, "wayland")
|
||||
w := path.Join(seal.sys.runtime, "wayland-0")
|
||||
seal.sys.Link(wp, wpi)
|
||||
seal.sys.bwrap.SetEnv[waylandDisplay] = w
|
||||
seal.sys.bwrap.Bind(wpi, w)
|
||||
|
||||
// ensure Wayland socket ACL (e.g. `/run/user/%d/wayland-%d`)
|
||||
seal.sys.UpdatePermType(system.EWayland, wp, acl.Read, acl.Write, acl.Execute)
|
||||
} else {
|
||||
wc := path.Join(seal.SharePath, "wayland")
|
||||
wt := path.Join(wc, seal.id)
|
||||
seal.sys.Ensure(wc, 0711)
|
||||
appID := seal.fid
|
||||
if appID == "" {
|
||||
// use instance ID in case app id is not set
|
||||
appID = "moe.ophivana.fortify." + seal.id
|
||||
}
|
||||
seal.sys.Wayland(wt, wp, appID, seal.id)
|
||||
seal.sys.bwrap.Bind(wt, w)
|
||||
// set wayland socket path for mediation (e.g. `/run/user/%d/wayland-%d`)
|
||||
seal.wl.Path = path.Join(seal.RuntimePath, wd)
|
||||
}
|
||||
}
|
||||
|
||||
@ -71,7 +58,7 @@ func (seal *appSeal) shareDisplay(os linux.System) error {
|
||||
return fmsg.WrapError(ErrXDisplay,
|
||||
"DISPLAY is not set")
|
||||
} else {
|
||||
seal.sys.ChangeHosts("#" + seal.sys.user.us)
|
||||
seal.sys.ChangeHosts(seal.sys.user.Username)
|
||||
seal.sys.bwrap.SetEnv[display] = d
|
||||
seal.sys.bwrap.Bind("/tmp/.X11-unix", "/tmp/.X11-unix")
|
||||
}
|
||||
|
@ -6,9 +6,9 @@ import (
|
||||
"io/fs"
|
||||
"path"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -25,7 +25,7 @@ var (
|
||||
ErrPulseMode = errors.New("unexpected pulse socket mode")
|
||||
)
|
||||
|
||||
func (seal *appSeal) sharePulse(os linux.System) error {
|
||||
func (seal *appSeal) sharePulse(os internal.System) error {
|
||||
if !seal.et.Has(system.EPulse) {
|
||||
return nil
|
||||
}
|
||||
@ -78,7 +78,7 @@ func (seal *appSeal) sharePulse(os linux.System) error {
|
||||
}
|
||||
|
||||
// discoverPulseCookie attempts various standard methods to discover the current user's PulseAudio authentication cookie
|
||||
func discoverPulseCookie(os linux.System) (string, error) {
|
||||
func discoverPulseCookie(os internal.System) (string, error) {
|
||||
if p, ok := os.LookupEnv(pulseCookie); ok {
|
||||
return p, nil
|
||||
}
|
||||
|
@ -3,8 +3,8 @@ package app
|
||||
import (
|
||||
"path"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -3,9 +3,9 @@ package app
|
||||
import (
|
||||
"path"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -16,12 +16,12 @@ const (
|
||||
func (seal *appSeal) shareSystem() {
|
||||
// ensure Share (e.g. `/tmp/fortify.%d`)
|
||||
// acl is unnecessary as this directory is world executable
|
||||
seal.sys.Ensure(seal.SharePath, 0711)
|
||||
seal.sys.Ensure(seal.SharePath, 0701)
|
||||
|
||||
// ensure process-specific share (e.g. `/tmp/fortify.%d/%s`)
|
||||
// acl is unnecessary as this directory is world executable
|
||||
seal.share = path.Join(seal.SharePath, seal.id)
|
||||
seal.sys.Ephemeral(system.Process, seal.share, 0711)
|
||||
seal.sys.Ephemeral(system.Process, seal.share, 0701)
|
||||
|
||||
// ensure child tmpdir parent directory (e.g. `/tmp/fortify.%d/tmpdir`)
|
||||
targetTmpdirParent := path.Join(seal.SharePath, "tmpdir")
|
||||
@ -29,7 +29,7 @@ func (seal *appSeal) shareSystem() {
|
||||
seal.sys.UpdatePermType(system.User, targetTmpdirParent, acl.Execute)
|
||||
|
||||
// ensure child tmpdir (e.g. `/tmp/fortify.%d/tmpdir/%d`)
|
||||
targetTmpdir := path.Join(targetTmpdirParent, seal.sys.user.as)
|
||||
targetTmpdir := path.Join(targetTmpdirParent, seal.sys.user.Uid)
|
||||
seal.sys.Ensure(targetTmpdir, 01700)
|
||||
seal.sys.UpdatePermType(system.User, targetTmpdir, acl.Read, acl.Write, acl.Execute)
|
||||
seal.sys.bwrap.Bind(targetTmpdir, "/tmp", false, true)
|
||||
@ -38,7 +38,7 @@ func (seal *appSeal) shareSystem() {
|
||||
seal.sys.bwrap.Tmpfs(seal.SharePath, 1*1024*1024)
|
||||
}
|
||||
|
||||
func (seal *appSeal) sharePasswd(os linux.System) {
|
||||
func (seal *appSeal) sharePasswd(os internal.System) {
|
||||
// look up shell
|
||||
sh := "/bin/sh"
|
||||
if s, ok := os.LookupEnv(shell); ok {
|
||||
@ -49,27 +49,21 @@ func (seal *appSeal) sharePasswd(os linux.System) {
|
||||
// generate /etc/passwd
|
||||
passwdPath := path.Join(seal.share, "passwd")
|
||||
username := "chronos"
|
||||
if seal.sys.user.username != "" {
|
||||
username = seal.sys.user.username
|
||||
if seal.sys.user.Username != "" {
|
||||
username = seal.sys.user.Username
|
||||
seal.sys.bwrap.SetEnv["USER"] = seal.sys.user.Username
|
||||
}
|
||||
homeDir := "/var/empty"
|
||||
if seal.sys.user.home != "" {
|
||||
homeDir = seal.sys.user.home
|
||||
if seal.sys.user.HomeDir != "" {
|
||||
homeDir = seal.sys.user.HomeDir
|
||||
seal.sys.bwrap.SetEnv["HOME"] = seal.sys.user.HomeDir
|
||||
}
|
||||
|
||||
// bind home directory
|
||||
seal.sys.bwrap.Bind(seal.sys.user.data, homeDir, false, true)
|
||||
seal.sys.bwrap.Chdir = homeDir
|
||||
|
||||
seal.sys.bwrap.SetEnv["USER"] = username
|
||||
seal.sys.bwrap.SetEnv["HOME"] = homeDir
|
||||
|
||||
passwd := username + ":x:" + seal.sys.mappedIDString + ":" + seal.sys.mappedIDString + ":Fortify:" + homeDir + ":" + sh + "\n"
|
||||
passwd := username + ":x:65534:65534:Fortify:" + homeDir + ":" + sh + "\n"
|
||||
seal.sys.Write(passwdPath, passwd)
|
||||
|
||||
// write /etc/group
|
||||
groupPath := path.Join(seal.share, "group")
|
||||
seal.sys.Write(groupPath, "fortify:x:"+seal.sys.mappedIDString+":\n")
|
||||
seal.sys.Write(groupPath, "fortify:x:65534:\n")
|
||||
|
||||
// bind /etc/passwd and /etc/group
|
||||
seal.sys.bwrap.Bind(passwdPath, "/etc/passwd")
|
||||
|
@ -4,15 +4,15 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
shim0 "git.gensokyo.uk/security/fortify/cmd/fshim/ipc"
|
||||
"git.gensokyo.uk/security/fortify/cmd/fshim/ipc/shim"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/state"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/shim"
|
||||
"git.ophivana.moe/security/fortify/internal/state"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
// Start selects a user switcher and starts shim.
|
||||
@ -22,9 +22,9 @@ func (a *app) Start() error {
|
||||
defer a.lock.Unlock()
|
||||
|
||||
// resolve exec paths
|
||||
shimExec := [2]string{helper.BubblewrapName}
|
||||
shimExec := [3]string{a.seal.sys.executable, helper.BubblewrapName}
|
||||
if len(a.seal.command) > 0 {
|
||||
shimExec[1] = a.seal.command[0]
|
||||
shimExec[2] = a.seal.command[0]
|
||||
}
|
||||
for i, n := range shimExec {
|
||||
if len(n) == 0 {
|
||||
@ -40,15 +40,24 @@ func (a *app) Start() error {
|
||||
}
|
||||
}
|
||||
|
||||
// select command builder
|
||||
var commandBuilder shim.CommandBuilder
|
||||
switch a.seal.launchOption {
|
||||
case LaunchMethodSudo:
|
||||
commandBuilder = a.commandBuilderSudo
|
||||
case LaunchMethodMachineCtl:
|
||||
commandBuilder = a.commandBuilderMachineCtl
|
||||
default:
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
// construct shim manager
|
||||
a.shim = shim.New(
|
||||
uint32(a.seal.sys.UID()),
|
||||
a.seal.sys.user.as,
|
||||
a.seal.sys.user.supp,
|
||||
&shim0.Payload{
|
||||
a.shim = shim.New(a.seal.toolPath, uint32(a.seal.sys.UID()), path.Join(a.seal.share, "shim"), a.seal.wl,
|
||||
&shim.Payload{
|
||||
Argv: a.seal.command,
|
||||
Exec: shimExec,
|
||||
Bwrap: a.seal.sys.bwrap,
|
||||
WL: a.seal.wl != nil,
|
||||
|
||||
Verbose: fmsg.Verbose(),
|
||||
},
|
||||
@ -60,24 +69,23 @@ func (a *app) Start() error {
|
||||
}
|
||||
a.seal.sys.needRevert = true
|
||||
|
||||
// export sync pipe from sys
|
||||
a.seal.sys.bwrap.SetSync(a.seal.sys.Sync())
|
||||
|
||||
if startTime, err := a.shim.Start(); err != nil {
|
||||
if startTime, err := a.shim.Start(commandBuilder); err != nil {
|
||||
return err
|
||||
} else {
|
||||
// shim start and setup success, create process state
|
||||
sd := state.State{
|
||||
ID: *a.id,
|
||||
PID: a.shim.Unwrap().Process.Pid,
|
||||
Config: a.ct.Unwrap(),
|
||||
Time: *startTime,
|
||||
PID: a.shim.Unwrap().Process.Pid,
|
||||
Command: a.seal.command,
|
||||
Capability: a.seal.et,
|
||||
Method: method[a.seal.launchOption],
|
||||
Argv: a.shim.Unwrap().Args,
|
||||
Time: *startTime,
|
||||
}
|
||||
|
||||
// register process state
|
||||
var err0 = new(StateStoreError)
|
||||
err0.Inner, err0.DoErr = a.seal.store.Do(a.seal.sys.user.aid, func(c state.Cursor) {
|
||||
err0.InnerErr = c.Save(&sd)
|
||||
err0.Inner, err0.DoErr = a.seal.store.Do(func(b state.Backend) {
|
||||
err0.InnerErr = b.Save(&sd)
|
||||
})
|
||||
a.seal.sys.saveState = true
|
||||
return err0.equiv("cannot save process state:")
|
||||
@ -97,7 +105,7 @@ type StateStoreError struct {
|
||||
}
|
||||
|
||||
func (e *StateStoreError) equiv(a ...any) error {
|
||||
if e.Inner && e.DoErr == nil && e.InnerErr == nil && e.Err == nil {
|
||||
if e.Inner == true && e.DoErr == nil && e.InnerErr == nil && e.Err == nil {
|
||||
return nil
|
||||
} else {
|
||||
return fmsg.WrapErrorSuffix(e, a...)
|
||||
@ -143,67 +151,45 @@ func (a *app) Wait() (int, error) {
|
||||
a.lock.Lock()
|
||||
defer a.lock.Unlock()
|
||||
|
||||
if a.shim == nil {
|
||||
fmsg.VPrintln("shim not initialised, skipping cleanup")
|
||||
return 1, nil
|
||||
}
|
||||
|
||||
var r int
|
||||
|
||||
if cmd := a.shim.Unwrap(); cmd == nil {
|
||||
// failure prior to process start
|
||||
r = 255
|
||||
} else {
|
||||
wait := make(chan error, 1)
|
||||
go func() { wait <- cmd.Wait() }()
|
||||
|
||||
select {
|
||||
// wait for process and resolve exit code
|
||||
case err := <-wait:
|
||||
if err != nil {
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) {
|
||||
// should be unreachable
|
||||
a.waitErr = err
|
||||
}
|
||||
|
||||
// store non-zero return code
|
||||
r = exitError.ExitCode()
|
||||
} else {
|
||||
r = cmd.ProcessState.ExitCode()
|
||||
if err := cmd.Wait(); err != nil {
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) {
|
||||
// should be unreachable
|
||||
a.waitErr = err
|
||||
}
|
||||
fmsg.VPrintf("process %d exited with exit code %d", cmd.Process.Pid, r)
|
||||
|
||||
// alternative exit path when kill was unsuccessful
|
||||
case err := <-a.shim.WaitFallback():
|
||||
r = 255
|
||||
if err != nil {
|
||||
fmsg.Printf("cannot terminate shim on faulted setup: %v", err)
|
||||
} else {
|
||||
fmsg.VPrintln("alternative exit path selected")
|
||||
}
|
||||
// store non-zero return code
|
||||
r = exitError.ExitCode()
|
||||
} else {
|
||||
r = cmd.ProcessState.ExitCode()
|
||||
}
|
||||
fmsg.VPrintf("process %d exited with exit code %d", cmd.Process.Pid, r)
|
||||
}
|
||||
|
||||
// child process exited, resume output
|
||||
fmsg.Resume()
|
||||
|
||||
// print queued up dbus messages
|
||||
if a.seal.dbusMsg != nil {
|
||||
a.seal.dbusMsg(func(msgbuf []string) {
|
||||
for _, msg := range msgbuf {
|
||||
fmsg.Println(msg)
|
||||
}
|
||||
})
|
||||
// close wayland connection
|
||||
if a.seal.wl != nil {
|
||||
if err := a.seal.wl.Close(); err != nil {
|
||||
fmsg.Println("cannot close wayland connection:", err)
|
||||
}
|
||||
}
|
||||
|
||||
// update store and revert app setup transaction
|
||||
e := new(StateStoreError)
|
||||
e.Inner, e.DoErr = a.seal.store.Do(a.seal.sys.user.aid, func(b state.Cursor) {
|
||||
e.Inner, e.DoErr = a.seal.store.Do(func(b state.Backend) {
|
||||
e.InnerErr = func() error {
|
||||
// destroy defunct state entry
|
||||
if cmd := a.shim.Unwrap(); cmd != nil && a.seal.sys.saveState {
|
||||
if err := b.Destroy(*a.id); err != nil {
|
||||
if err := b.Destroy(cmd.Process.Pid); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@ -224,12 +210,8 @@ func (a *app) Wait() (int, error) {
|
||||
}
|
||||
|
||||
// accumulate capabilities of other launchers
|
||||
for i, s := range states {
|
||||
if s.Config != nil {
|
||||
*rt |= s.Config.Confinement.Enablements
|
||||
} else {
|
||||
fmsg.Printf("state entry %d does not contain config", i)
|
||||
}
|
||||
for _, s := range states {
|
||||
*rt |= s.Capability
|
||||
}
|
||||
}
|
||||
// invert accumulated enablements for cleanup
|
||||
@ -250,10 +232,9 @@ func (a *app) Wait() (int, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if a.seal.sys.needRevert {
|
||||
if err := a.seal.sys.Revert(ec); err != nil {
|
||||
return err.(RevertCompoundError)
|
||||
}
|
||||
a.shim.AbortWait(errors.New("shim exited"))
|
||||
if err := a.seal.sys.Revert(ec); err != nil {
|
||||
return err.(RevertCompoundError)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
@ -1,10 +1,12 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"os/user"
|
||||
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
// appSealSys encapsulates app seal behaviour with OS interactions
|
||||
@ -15,13 +17,10 @@ type appSealSys struct {
|
||||
|
||||
// default formatted XDG_RUNTIME_DIR of User
|
||||
runtime string
|
||||
// sealed path to fortify executable, used by shim
|
||||
executable string
|
||||
// target user sealed from config
|
||||
user appUser
|
||||
|
||||
// mapped uid and gid in user namespace
|
||||
mappedID int
|
||||
// string representation of mappedID
|
||||
mappedIDString string
|
||||
user *user.User
|
||||
|
||||
needRevert bool
|
||||
saveState bool
|
||||
@ -30,30 +29,8 @@ type appSealSys struct {
|
||||
// protected by upstream mutex
|
||||
}
|
||||
|
||||
type appUser struct {
|
||||
// full uid resolved by fsu
|
||||
uid int
|
||||
// string representation of uid
|
||||
us string
|
||||
|
||||
// supplementary group ids
|
||||
supp []string
|
||||
|
||||
// application id
|
||||
aid int
|
||||
// string representation of aid
|
||||
as string
|
||||
|
||||
// home directory host path
|
||||
data string
|
||||
// app user home directory
|
||||
home string
|
||||
// passwd database username
|
||||
username string
|
||||
}
|
||||
|
||||
// shareAll calls all share methods in sequence
|
||||
func (seal *appSeal) shareAll(bus [2]*dbus.Config, os linux.System) error {
|
||||
func (seal *appSeal) shareAll(bus [2]*dbus.Config, os internal.System) error {
|
||||
if seal.shared {
|
||||
panic("seal shared twice")
|
||||
}
|
||||
|
@ -1,12 +0,0 @@
|
||||
package internal
|
||||
|
||||
const compPoison = "INVALIDINVALIDINVALIDINVALIDINVALID"
|
||||
|
||||
var (
|
||||
Version = compPoison
|
||||
)
|
||||
|
||||
// Check validates string value set at compile time.
|
||||
func Check(s string) (string, bool) {
|
||||
return s, s != compPoison && s != ""
|
||||
}
|
35
internal/early.go
Normal file
35
internal/early.go
Normal file
@ -0,0 +1,35 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
const (
|
||||
systemdCheckPath = "/run/systemd/system"
|
||||
)
|
||||
|
||||
var SdBootedV = func() bool {
|
||||
if v, err := SdBooted(); err != nil {
|
||||
fmsg.Println("cannot read systemd marker:", err)
|
||||
return false
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}()
|
||||
|
||||
// SdBooted implements https://www.freedesktop.org/software/systemd/man/sd_booted.html
|
||||
func SdBooted() (bool, error) {
|
||||
_, err := os.Stat(systemdCheckPath)
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
err = nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
@ -8,7 +8,6 @@ import (
|
||||
|
||||
var (
|
||||
wstate atomic.Bool
|
||||
dropped atomic.Uint64
|
||||
withhold = make(chan struct{}, 1)
|
||||
msgbuf = make(chan dOp, 64) // these ops are tiny so a large buffer is allocated for withholding output
|
||||
|
||||
@ -30,26 +29,6 @@ func dequeue() {
|
||||
}()
|
||||
}
|
||||
|
||||
// queue submits ops to msgbuf but drops messages
|
||||
// when the buffer is full and dequeue is withholding
|
||||
func queue(op dOp) {
|
||||
queueSync.Add(1)
|
||||
|
||||
select {
|
||||
case msgbuf <- op:
|
||||
default:
|
||||
// send the op anyway if not withholding
|
||||
// as dequeue will get to it eventually
|
||||
if !wstate.Load() {
|
||||
msgbuf <- op
|
||||
} else {
|
||||
queueSync.Done()
|
||||
// increment dropped message count
|
||||
dropped.Add(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type dOp interface{ Do() }
|
||||
|
||||
func Exit(code int) {
|
||||
@ -57,10 +36,9 @@ func Exit(code int) {
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func Suspend() {
|
||||
func Withhold() {
|
||||
dequeueOnce.Do(dequeue)
|
||||
if wstate.CompareAndSwap(false, true) {
|
||||
queueSync.Wait()
|
||||
withhold <- struct{}{}
|
||||
}
|
||||
}
|
||||
@ -69,9 +47,6 @@ func Resume() {
|
||||
dequeueOnce.Do(dequeue)
|
||||
if wstate.CompareAndSwap(true, false) {
|
||||
withhold <- struct{}{}
|
||||
if d := dropped.Swap(0); d != 0 {
|
||||
Printf("dropped %d messages during withhold", d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -16,17 +16,20 @@ func SetPrefix(prefix string) {
|
||||
|
||||
func Print(v ...any) {
|
||||
dequeueOnce.Do(dequeue)
|
||||
queue(dPrint(v))
|
||||
queueSync.Add(1)
|
||||
msgbuf <- dPrint(v)
|
||||
}
|
||||
|
||||
func Printf(format string, v ...any) {
|
||||
dequeueOnce.Do(dequeue)
|
||||
queue(&dPrintf{format, v})
|
||||
queueSync.Add(1)
|
||||
msgbuf <- &dPrintf{format, v}
|
||||
}
|
||||
|
||||
func Println(v ...any) {
|
||||
dequeueOnce.Do(dequeue)
|
||||
queue(dPrintln(v))
|
||||
queueSync.Add(1)
|
||||
msgbuf <- dPrintln(v)
|
||||
}
|
||||
|
||||
func Fatal(v ...any) {
|
||||
|
@ -1,83 +1,69 @@
|
||||
package main
|
||||
package init0
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"flag"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
init0 "git.gensokyo.uk/security/fortify/cmd/finit/ipc"
|
||||
"git.gensokyo.uk/security/fortify/internal"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/proc"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
const (
|
||||
// time to wait for linger processes after death of initial process
|
||||
// time to wait for linger processes after death initial process
|
||||
residualProcessTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
// everything beyond this point runs within pid namespace
|
||||
// proceed with caution!
|
||||
|
||||
func main() {
|
||||
// sharing stdout with shim
|
||||
// USE WITH CAUTION
|
||||
func doInit(fd uintptr) {
|
||||
fmsg.SetPrefix("init")
|
||||
|
||||
// setting this prevents ptrace
|
||||
if err := internal.PR_SET_DUMPABLE__SUID_DUMP_DISABLE(); err != nil {
|
||||
fmsg.Fatalf("cannot set SUID_DUMP_DISABLE: %s", err)
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
if os.Getpid() != 1 {
|
||||
fmsg.Fatal("this process must run as pid 1")
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
// re-exec
|
||||
if len(os.Args) > 0 && (os.Args[0] != "finit" || len(os.Args) != 1) && path.IsAbs(os.Args[0]) {
|
||||
if err := syscall.Exec(os.Args[0], []string{"finit"}, os.Environ()); err != nil {
|
||||
if len(os.Args) > 0 && os.Args[0] != "fortify" && path.IsAbs(os.Args[0]) {
|
||||
if err := syscall.Exec(os.Args[0], []string{"fortify", "init"}, os.Environ()); err != nil {
|
||||
fmsg.Println("cannot re-exec self:", err)
|
||||
// continue anyway
|
||||
}
|
||||
}
|
||||
|
||||
// receive setup payload
|
||||
var (
|
||||
payload init0.Payload
|
||||
closeSetup func() error
|
||||
)
|
||||
if f, err := proc.Receive(init0.Env, &payload); err != nil {
|
||||
if errors.Is(err, proc.ErrInvalid) {
|
||||
fmsg.Fatal("invalid config descriptor")
|
||||
}
|
||||
if errors.Is(err, proc.ErrNotSet) {
|
||||
fmsg.Fatal("FORTIFY_INIT not set")
|
||||
}
|
||||
|
||||
fmsg.Fatalf("cannot decode init setup payload: %v", err)
|
||||
panic("unreachable")
|
||||
var payload Payload
|
||||
p := os.NewFile(fd, "config-stream")
|
||||
if p == nil {
|
||||
fmsg.Fatal("invalid config descriptor")
|
||||
}
|
||||
if err := gob.NewDecoder(p).Decode(&payload); err != nil {
|
||||
fmsg.Fatal("cannot decode init payload:", err)
|
||||
} else {
|
||||
// sharing stdout with parent
|
||||
// USE WITH CAUTION
|
||||
fmsg.SetVerbose(payload.Verbose)
|
||||
closeSetup = f
|
||||
|
||||
// child does not need to see this
|
||||
if err = os.Unsetenv(init0.Env); err != nil {
|
||||
fmsg.Printf("cannot unset %s: %v", init0.Env, err)
|
||||
if err = os.Unsetenv(EnvInit); err != nil {
|
||||
fmsg.Println("cannot unset", EnvInit+":", err)
|
||||
// not fatal
|
||||
} else {
|
||||
fmsg.VPrintln("received configuration")
|
||||
}
|
||||
}
|
||||
|
||||
// close config fd
|
||||
if err := p.Close(); err != nil {
|
||||
fmsg.Println("cannot close config fd:", err)
|
||||
// not fatal
|
||||
}
|
||||
|
||||
// die with parent
|
||||
if err := internal.PR_SET_PDEATHSIG__SIGKILL(); err != nil {
|
||||
fmsg.Fatalf("prctl(PR_SET_PDEATHSIG, SIGKILL): %v", err)
|
||||
if _, _, errno := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_PDEATHSIG, uintptr(syscall.SIGKILL), 0); errno != 0 {
|
||||
fmsg.Fatal("prctl(PR_SET_PDEATHSIG, SIGKILL):", errno.Error())
|
||||
}
|
||||
|
||||
cmd := exec.Command(payload.Argv0)
|
||||
@ -85,16 +71,17 @@ func main() {
|
||||
cmd.Args = payload.Argv
|
||||
cmd.Env = os.Environ()
|
||||
|
||||
// pass wayland fd
|
||||
if payload.WL != -1 {
|
||||
if f := os.NewFile(uintptr(payload.WL), "wayland"); f != nil {
|
||||
cmd.Env = append(cmd.Env, "WAYLAND_SOCKET="+strconv.Itoa(3+len(cmd.ExtraFiles)))
|
||||
cmd.ExtraFiles = append(cmd.ExtraFiles, f)
|
||||
}
|
||||
}
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
fmsg.Fatalf("cannot start %q: %v", payload.Argv0, err)
|
||||
}
|
||||
fmsg.Suspend()
|
||||
|
||||
// close setup pipe as setup is now complete
|
||||
if err := closeSetup(); err != nil {
|
||||
fmsg.Println("cannot close setup pipe:", err)
|
||||
// not fatal
|
||||
}
|
||||
|
||||
sig := make(chan os.Signal, 2)
|
||||
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
||||
@ -135,7 +122,6 @@ func main() {
|
||||
close(done)
|
||||
}()
|
||||
|
||||
// closed after residualProcessTimeout has elapsed after initial process death
|
||||
timeout := make(chan struct{})
|
||||
|
||||
r := 2
|
||||
@ -143,13 +129,9 @@ func main() {
|
||||
select {
|
||||
case s := <-sig:
|
||||
fmsg.VPrintln("received", s.String())
|
||||
fmsg.Resume() // output could still be withheld at this point, so resume is called
|
||||
fmsg.Exit(0)
|
||||
case w := <-info:
|
||||
if w.wpid == cmd.Process.Pid {
|
||||
// initial process exited, output is most likely available again
|
||||
fmsg.Resume()
|
||||
|
||||
switch {
|
||||
case w.wstatus.Exited():
|
||||
r = w.wstatus.ExitStatus()
|
||||
@ -172,3 +154,21 @@ func main() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try runs init and stops execution if FORTIFY_INIT is set.
|
||||
func Try() {
|
||||
if os.Getpid() != 1 {
|
||||
return
|
||||
}
|
||||
|
||||
if args := flag.Args(); len(args) == 1 && args[0] == "init" {
|
||||
if s, ok := os.LookupEnv(EnvInit); ok {
|
||||
if fd, err := strconv.Atoi(s); err != nil {
|
||||
fmsg.Fatalf("cannot parse %q: %v", s, err)
|
||||
} else {
|
||||
doInit(uintptr(fd))
|
||||
}
|
||||
panic("unreachable")
|
||||
}
|
||||
}
|
||||
}
|
@ -1,12 +1,14 @@
|
||||
package init0
|
||||
|
||||
const Env = "FORTIFY_INIT"
|
||||
const EnvInit = "FORTIFY_INIT"
|
||||
|
||||
type Payload struct {
|
||||
// target full exec path
|
||||
Argv0 string
|
||||
// child full argv
|
||||
Argv []string
|
||||
// wayland fd, -1 to disable
|
||||
WL int
|
||||
|
||||
// verbosity pass through
|
||||
Verbose bool
|
@ -1,88 +0,0 @@
|
||||
package linux
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// Std implements System using the standard library.
|
||||
type Std struct {
|
||||
paths Paths
|
||||
pathsOnce sync.Once
|
||||
|
||||
uidOnce sync.Once
|
||||
uidCopy map[int]struct {
|
||||
uid int
|
||||
err error
|
||||
}
|
||||
uidMu sync.RWMutex
|
||||
}
|
||||
|
||||
func (s *Std) Geteuid() int { return os.Geteuid() }
|
||||
func (s *Std) LookupEnv(key string) (string, bool) { return os.LookupEnv(key) }
|
||||
func (s *Std) TempDir() string { return os.TempDir() }
|
||||
func (s *Std) LookPath(file string) (string, error) { return exec.LookPath(file) }
|
||||
func (s *Std) Executable() (string, error) { return os.Executable() }
|
||||
func (s *Std) LookupGroup(name string) (*user.Group, error) { return user.LookupGroup(name) }
|
||||
func (s *Std) ReadDir(name string) ([]os.DirEntry, error) { return os.ReadDir(name) }
|
||||
func (s *Std) Stat(name string) (fs.FileInfo, error) { return os.Stat(name) }
|
||||
func (s *Std) Open(name string) (fs.File, error) { return os.Open(name) }
|
||||
func (s *Std) Exit(code int) { fmsg.Exit(code) }
|
||||
func (s *Std) Stdout() io.Writer { return os.Stdout }
|
||||
|
||||
const xdgRuntimeDir = "XDG_RUNTIME_DIR"
|
||||
|
||||
func (s *Std) Paths() Paths {
|
||||
s.pathsOnce.Do(func() { CopyPaths(s, &s.paths) })
|
||||
return s.paths
|
||||
}
|
||||
|
||||
func (s *Std) Uid(aid int) (int, error) {
|
||||
s.uidOnce.Do(func() {
|
||||
s.uidCopy = make(map[int]struct {
|
||||
uid int
|
||||
err error
|
||||
})
|
||||
})
|
||||
|
||||
s.uidMu.RLock()
|
||||
if u, ok := s.uidCopy[aid]; ok {
|
||||
s.uidMu.RUnlock()
|
||||
return u.uid, u.err
|
||||
}
|
||||
|
||||
s.uidMu.RUnlock()
|
||||
s.uidMu.Lock()
|
||||
defer s.uidMu.Unlock()
|
||||
|
||||
u := struct {
|
||||
uid int
|
||||
err error
|
||||
}{}
|
||||
defer func() { s.uidCopy[aid] = u }()
|
||||
|
||||
u.uid = -1
|
||||
if fsu, ok := internal.Check(internal.Fsu); !ok {
|
||||
fmsg.Fatal("invalid fsu path, this copy of fshim is not compiled correctly")
|
||||
panic("unreachable")
|
||||
} else {
|
||||
cmd := exec.Command(fsu)
|
||||
cmd.Path = fsu
|
||||
cmd.Stderr = os.Stderr // pass through fatal messages
|
||||
cmd.Env = []string{"FORTIFY_APP_ID=" + strconv.Itoa(aid)}
|
||||
cmd.Dir = "/"
|
||||
var p []byte
|
||||
if p, u.err = cmd.Output(); u.err == nil {
|
||||
u.uid, u.err = strconv.Atoi(string(p))
|
||||
}
|
||||
return u.uid, u.err
|
||||
}
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
package internal
|
||||
|
||||
import "path"
|
||||
|
||||
var (
|
||||
Fsu = compPoison
|
||||
Finit = compPoison
|
||||
)
|
||||
|
||||
func Path(p string) (string, bool) {
|
||||
return p, p != compPoison && p != "" && path.IsAbs(p)
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
package internal
|
||||
|
||||
import "syscall"
|
||||
|
||||
func PR_SET_DUMPABLE__SUID_DUMP_DISABLE() error {
|
||||
// linux/sched/coredump.h
|
||||
if _, _, errno := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_DUMPABLE, 0, 0); errno != 0 {
|
||||
return errno
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func PR_SET_PDEATHSIG__SIGKILL() error {
|
||||
if _, _, errno := syscall.AllThreadsSyscall(syscall.SYS_PRCTL, syscall.PR_SET_PDEATHSIG, uintptr(syscall.SIGKILL), 0); errno != 0 {
|
||||
return errno
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
@ -1,42 +0,0 @@
|
||||
package proc
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotSet = errors.New("environment variable not set")
|
||||
ErrInvalid = errors.New("bad file descriptor")
|
||||
)
|
||||
|
||||
func Setup(extraFiles *[]*os.File) (int, *gob.Encoder, error) {
|
||||
if r, w, err := os.Pipe(); err != nil {
|
||||
return -1, nil, err
|
||||
} else {
|
||||
fd := 3 + len(*extraFiles)
|
||||
*extraFiles = append(*extraFiles, r)
|
||||
return fd, gob.NewEncoder(w), nil
|
||||
}
|
||||
}
|
||||
|
||||
func Receive(key string, e any) (func() error, error) {
|
||||
var setup *os.File
|
||||
|
||||
if s, ok := os.LookupEnv(key); !ok {
|
||||
return nil, ErrNotSet
|
||||
} else {
|
||||
if fd, err := strconv.Atoi(s); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
setup = os.NewFile(uintptr(fd), "setup")
|
||||
if setup == nil {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return func() error { return setup.Close() }, gob.NewDecoder(setup).Decode(e)
|
||||
}
|
@ -1,13 +0,0 @@
|
||||
package proc
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
func ExtraFile(cmd *exec.Cmd, f *os.File) (fd uintptr) {
|
||||
// ExtraFiles: If non-nil, entry i becomes file descriptor 3+i.
|
||||
fd = uintptr(3 + len(cmd.ExtraFiles))
|
||||
cmd.ExtraFiles = append(cmd.ExtraFiles, f)
|
||||
return
|
||||
}
|
179
internal/shim/main.go
Normal file
179
internal/shim/main.go
Normal file
@ -0,0 +1,179 @@
|
||||
package shim
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"flag"
|
||||
"net"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"syscall"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
init0 "git.ophivana.moe/security/fortify/internal/init"
|
||||
)
|
||||
|
||||
// everything beyond this point runs as target user
|
||||
// proceed with caution!
|
||||
|
||||
func doShim(socket string) {
|
||||
fmsg.SetPrefix("shim")
|
||||
|
||||
// re-exec
|
||||
if len(os.Args) > 0 && os.Args[0] != "fortify" && path.IsAbs(os.Args[0]) {
|
||||
if err := syscall.Exec(os.Args[0], []string{"fortify", "shim"}, os.Environ()); err != nil {
|
||||
fmsg.Println("cannot re-exec self:", err)
|
||||
// continue anyway
|
||||
}
|
||||
}
|
||||
|
||||
// dial setup socket
|
||||
var conn *net.UnixConn
|
||||
if c, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: socket, Net: "unix"}); err != nil {
|
||||
fmsg.Fatal("cannot dial setup socket:", err)
|
||||
panic("unreachable")
|
||||
} else {
|
||||
conn = c
|
||||
}
|
||||
|
||||
// decode payload gob stream
|
||||
var payload Payload
|
||||
if err := gob.NewDecoder(conn).Decode(&payload); err != nil {
|
||||
fmsg.Fatal("cannot decode shim payload:", err)
|
||||
} else {
|
||||
// sharing stdout with parent
|
||||
// USE WITH CAUTION
|
||||
fmsg.SetVerbose(payload.Verbose)
|
||||
}
|
||||
|
||||
if payload.Bwrap == nil {
|
||||
fmsg.Fatal("bwrap config not supplied")
|
||||
}
|
||||
|
||||
// receive wayland fd over socket
|
||||
wfd := -1
|
||||
if payload.WL {
|
||||
if fd, err := receiveWLfd(conn); err != nil {
|
||||
fmsg.Fatal("cannot receive wayland fd:", err)
|
||||
} else {
|
||||
wfd = fd
|
||||
}
|
||||
}
|
||||
|
||||
// close setup socket
|
||||
if err := conn.Close(); err != nil {
|
||||
fmsg.Println("cannot close setup socket:", err)
|
||||
// not fatal
|
||||
}
|
||||
|
||||
var ic init0.Payload
|
||||
|
||||
// resolve argv0
|
||||
ic.Argv = payload.Argv
|
||||
if len(ic.Argv) > 0 {
|
||||
// looked up from $PATH by parent
|
||||
ic.Argv0 = payload.Exec[2]
|
||||
} else {
|
||||
// no argv, look up shell instead
|
||||
var ok bool
|
||||
if ic.Argv0, ok = os.LookupEnv("SHELL"); !ok {
|
||||
fmsg.Fatal("no command was specified and $SHELL was unset")
|
||||
}
|
||||
|
||||
ic.Argv = []string{ic.Argv0}
|
||||
}
|
||||
|
||||
conf := payload.Bwrap
|
||||
|
||||
var extraFiles []*os.File
|
||||
|
||||
// pass wayland fd
|
||||
if wfd != -1 {
|
||||
if f := os.NewFile(uintptr(wfd), "wayland"); f != nil {
|
||||
ic.WL = 3 + len(extraFiles)
|
||||
extraFiles = append(extraFiles, f)
|
||||
}
|
||||
} else {
|
||||
ic.WL = -1
|
||||
}
|
||||
|
||||
// share config pipe
|
||||
if r, w, err := os.Pipe(); err != nil {
|
||||
fmsg.Fatal("cannot pipe:", err)
|
||||
} else {
|
||||
conf.SetEnv[init0.EnvInit] = strconv.Itoa(3 + len(extraFiles))
|
||||
extraFiles = append(extraFiles, r)
|
||||
|
||||
fmsg.VPrintln("transmitting config to init")
|
||||
go func() {
|
||||
// stream config to pipe
|
||||
if err = gob.NewEncoder(w).Encode(&ic); err != nil {
|
||||
fmsg.Fatal("cannot transmit init config:", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
helper.BubblewrapName = payload.Exec[1] // resolved bwrap path by parent
|
||||
if b, err := helper.NewBwrap(conf, nil, payload.Exec[0], func(int, int) []string { return []string{"init"} }); err != nil {
|
||||
fmsg.Fatal("malformed sandbox config:", err)
|
||||
} else {
|
||||
cmd := b.Unwrap()
|
||||
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
cmd.ExtraFiles = extraFiles
|
||||
|
||||
if fmsg.Verbose() {
|
||||
fmsg.VPrintln("bwrap args:", conf.Args())
|
||||
}
|
||||
|
||||
// run and pass through exit code
|
||||
if err = b.Start(); err != nil {
|
||||
fmsg.Fatal("cannot start target process:", err)
|
||||
} else if err = b.Wait(); err != nil {
|
||||
fmsg.VPrintln("wait:", err)
|
||||
}
|
||||
if b.Unwrap().ProcessState != nil {
|
||||
fmsg.Exit(b.Unwrap().ProcessState.ExitCode())
|
||||
} else {
|
||||
fmsg.Exit(127)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func receiveWLfd(conn *net.UnixConn) (int, error) {
|
||||
oob := make([]byte, syscall.CmsgSpace(4)) // single fd
|
||||
|
||||
if _, oobn, _, _, err := conn.ReadMsgUnix(nil, oob); err != nil {
|
||||
return -1, err
|
||||
} else if len(oob) != oobn {
|
||||
return -1, errors.New("invalid message length")
|
||||
}
|
||||
|
||||
var msg syscall.SocketControlMessage
|
||||
if messages, err := syscall.ParseSocketControlMessage(oob); err != nil {
|
||||
return -1, err
|
||||
} else if len(messages) != 1 {
|
||||
return -1, errors.New("unexpected message count")
|
||||
} else {
|
||||
msg = messages[0]
|
||||
}
|
||||
|
||||
if fds, err := syscall.ParseUnixRights(&msg); err != nil {
|
||||
return -1, err
|
||||
} else if len(fds) != 1 {
|
||||
return -1, errors.New("unexpected fd count")
|
||||
} else {
|
||||
return fds[0], nil
|
||||
}
|
||||
}
|
||||
|
||||
// Try runs shim and stops execution if FORTIFY_SHIM is set.
|
||||
func Try() {
|
||||
if args := flag.Args(); len(args) == 1 && args[0] == "shim" {
|
||||
if s, ok := os.LookupEnv(EnvShim); ok {
|
||||
doShim(s)
|
||||
panic("unreachable")
|
||||
}
|
||||
}
|
||||
}
|
202
internal/shim/parent.go
Normal file
202
internal/shim/parent.go
Normal file
@ -0,0 +1,202 @@
|
||||
package shim
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// used by the parent process
|
||||
|
||||
type Shim struct {
|
||||
// user switcher process
|
||||
cmd *exec.Cmd
|
||||
// uid of shim target user
|
||||
uid uint32
|
||||
// whether to check shim pid
|
||||
checkPid bool
|
||||
// user switcher executable path
|
||||
executable string
|
||||
// path to setup socket
|
||||
socket string
|
||||
// shim setup abort reason and completion
|
||||
abort chan error
|
||||
abortErr atomic.Pointer[error]
|
||||
abortOnce sync.Once
|
||||
// wayland mediation, nil if disabled
|
||||
wl *Wayland
|
||||
// shim setup payload
|
||||
payload *Payload
|
||||
}
|
||||
|
||||
func New(executable string, uid uint32, socket string, wl *Wayland, payload *Payload) *Shim {
|
||||
// checkPid is impossible at the moment since there is no way to obtain shim's pid
|
||||
// this feature is disabled here until sudo is replaced by fortify suid wrapper
|
||||
return &Shim{uid: uid, executable: executable, socket: socket, wl: wl, payload: payload}
|
||||
}
|
||||
|
||||
func (s *Shim) String() string {
|
||||
if s.cmd == nil {
|
||||
return "(unused shim manager)"
|
||||
}
|
||||
return s.cmd.String()
|
||||
}
|
||||
|
||||
func (s *Shim) Unwrap() *exec.Cmd {
|
||||
return s.cmd
|
||||
}
|
||||
|
||||
func (s *Shim) Abort(err error) {
|
||||
s.abortOnce.Do(func() {
|
||||
s.abortErr.Store(&err)
|
||||
// s.abort is buffered so this will never block
|
||||
s.abort <- err
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Shim) AbortWait(err error) {
|
||||
s.Abort(err)
|
||||
<-s.abort
|
||||
}
|
||||
|
||||
type CommandBuilder func(shimEnv string) (args []string)
|
||||
|
||||
func (s *Shim) Start(f CommandBuilder) (*time.Time, error) {
|
||||
var (
|
||||
cf chan *net.UnixConn
|
||||
accept func()
|
||||
)
|
||||
|
||||
// listen on setup socket
|
||||
if c, a, err := s.serve(); err != nil {
|
||||
return nil, fmsg.WrapErrorSuffix(err,
|
||||
"cannot listen on shim setup socket:")
|
||||
} else {
|
||||
// accepts a connection after each call to accept
|
||||
// connections are sent to the channel cf
|
||||
cf, accept = c, a
|
||||
}
|
||||
|
||||
// start user switcher process and save time
|
||||
s.cmd = exec.Command(s.executable, f(EnvShim+"="+s.socket)...)
|
||||
s.cmd.Env = []string{}
|
||||
s.cmd.Stdin, s.cmd.Stdout, s.cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
s.cmd.Dir = "/"
|
||||
fmsg.VPrintln("starting shim via user switcher:", s.cmd)
|
||||
fmsg.Withhold() // withhold messages to stderr
|
||||
if err := s.cmd.Start(); err != nil {
|
||||
return nil, fmsg.WrapErrorSuffix(err,
|
||||
"cannot start user switcher:")
|
||||
}
|
||||
startTime := time.Now().UTC()
|
||||
|
||||
// kill shim if something goes wrong and an error is returned
|
||||
killShim := func() {
|
||||
if err := s.cmd.Process.Signal(os.Interrupt); err != nil {
|
||||
fmsg.Println("cannot terminate shim on faulted setup:", err)
|
||||
}
|
||||
}
|
||||
defer func() { killShim() }()
|
||||
|
||||
accept()
|
||||
conn := <-cf
|
||||
if conn == nil {
|
||||
return &startTime, fmsg.WrapErrorSuffix(*s.abortErr.Load(), "cannot accept call on setup socket:")
|
||||
}
|
||||
|
||||
// authenticate against called provided uid and shim pid
|
||||
if cred, err := peerCred(conn); err != nil {
|
||||
return &startTime, fmsg.WrapErrorSuffix(*s.abortErr.Load(), "cannot retrieve shim credentials:")
|
||||
} else if cred.Uid != s.uid {
|
||||
fmsg.Printf("process %d owned by user %d tried to connect, expecting %d",
|
||||
cred.Pid, cred.Uid, s.uid)
|
||||
err = errors.New("compromised fortify build")
|
||||
s.Abort(err)
|
||||
return &startTime, err
|
||||
} else if s.checkPid && cred.Pid != int32(s.cmd.Process.Pid) {
|
||||
fmsg.Printf("process %d tried to connect to shim setup socket, expecting shim %d",
|
||||
cred.Pid, s.cmd.Process.Pid)
|
||||
err = errors.New("compromised target user")
|
||||
s.Abort(err)
|
||||
return &startTime, err
|
||||
}
|
||||
|
||||
// serve payload and wayland fd if enabled
|
||||
// this also closes the connection
|
||||
err := s.payload.serve(conn, s.wl)
|
||||
if err == nil {
|
||||
killShim = func() {}
|
||||
}
|
||||
s.Abort(err) // aborting with nil indicates success
|
||||
return &startTime, err
|
||||
}
|
||||
|
||||
func (s *Shim) serve() (chan *net.UnixConn, func(), error) {
|
||||
if s.abort != nil {
|
||||
panic("attempted to serve shim setup twice")
|
||||
}
|
||||
s.abort = make(chan error, 1)
|
||||
|
||||
cf := make(chan *net.UnixConn)
|
||||
accept := make(chan struct{}, 1)
|
||||
|
||||
if l, err := net.ListenUnix("unix", &net.UnixAddr{Name: s.socket, Net: "unix"}); err != nil {
|
||||
return nil, nil, err
|
||||
} else {
|
||||
l.SetUnlinkOnClose(true)
|
||||
|
||||
fmsg.VPrintf("listening on shim setup socket %q", s.socket)
|
||||
if err = acl.UpdatePerm(s.socket, int(s.uid), acl.Read, acl.Write, acl.Execute); err != nil {
|
||||
fmsg.Println("cannot append ACL entry to shim setup socket:", err)
|
||||
s.Abort(err) // ensures setup socket cleanup
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
case err = <-s.abort:
|
||||
if err != nil {
|
||||
fmsg.VPrintln("aborting shim setup, reason:", err)
|
||||
}
|
||||
if err = l.Close(); err != nil {
|
||||
fmsg.Println("cannot close setup socket:", err)
|
||||
}
|
||||
close(s.abort)
|
||||
close(cf)
|
||||
return
|
||||
case <-accept:
|
||||
if conn, err0 := l.AcceptUnix(); err0 != nil {
|
||||
s.Abort(err0) // does not block, breaks loop
|
||||
cf <- nil // receiver sees nil value and loads err0 stored during abort
|
||||
} else {
|
||||
cf <- conn
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return cf, func() { accept <- struct{}{} }, nil
|
||||
}
|
||||
|
||||
// peerCred fetches peer credentials of conn
|
||||
func peerCred(conn *net.UnixConn) (ucred *syscall.Ucred, err error) {
|
||||
var raw syscall.RawConn
|
||||
if raw, err = conn.SyscallConn(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err0 := raw.Control(func(fd uintptr) {
|
||||
ucred, err = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
|
||||
})
|
||||
err = errors.Join(err, err0)
|
||||
return
|
||||
}
|
42
internal/shim/payload.go
Normal file
42
internal/shim/payload.go
Normal file
@ -0,0 +1,42 @@
|
||||
package shim
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"net"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
const EnvShim = "FORTIFY_SHIM"
|
||||
|
||||
type Payload struct {
|
||||
// child full argv
|
||||
Argv []string
|
||||
// fortify, bwrap, target full exec path
|
||||
Exec [3]string
|
||||
// bwrap config
|
||||
Bwrap *bwrap.Config
|
||||
// whether to pass wayland fd
|
||||
WL bool
|
||||
|
||||
// verbosity pass through
|
||||
Verbose bool
|
||||
}
|
||||
|
||||
func (p *Payload) serve(conn *net.UnixConn, wl *Wayland) error {
|
||||
if err := gob.NewEncoder(conn).Encode(*p); err != nil {
|
||||
return fmsg.WrapErrorSuffix(err,
|
||||
"cannot stream shim payload:")
|
||||
}
|
||||
|
||||
if wl != nil {
|
||||
if err := wl.WriteUnix(conn); err != nil {
|
||||
return errors.Join(err, conn.Close())
|
||||
}
|
||||
}
|
||||
|
||||
return fmsg.WrapErrorSuffix(conn.Close(),
|
||||
"cannot close setup connection:")
|
||||
}
|
75
internal/shim/wayland.go
Normal file
75
internal/shim/wayland.go
Normal file
@ -0,0 +1,75 @@
|
||||
package shim
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// Wayland implements wayland mediation.
|
||||
type Wayland struct {
|
||||
// wayland socket path
|
||||
Path string
|
||||
|
||||
// wayland connection
|
||||
conn *net.UnixConn
|
||||
|
||||
connErr error
|
||||
sync.Once
|
||||
// wait for wayland client to exit
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func (wl *Wayland) WriteUnix(conn *net.UnixConn) error {
|
||||
// connect to host wayland socket
|
||||
if f, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: wl.Path, Net: "unix"}); err != nil {
|
||||
return fmsg.WrapErrorSuffix(err,
|
||||
fmt.Sprintf("cannot connect to wayland at %q:", wl.Path))
|
||||
} else {
|
||||
fmsg.VPrintf("connected to wayland at %q", wl.Path)
|
||||
wl.conn = f
|
||||
}
|
||||
|
||||
// set up for passing wayland socket
|
||||
if rc, err := wl.conn.SyscallConn(); err != nil {
|
||||
return fmsg.WrapErrorSuffix(err, "cannot obtain raw wayland connection:")
|
||||
} else {
|
||||
ec := make(chan error)
|
||||
go func() {
|
||||
// pass wayland connection fd
|
||||
if err = rc.Control(func(fd uintptr) {
|
||||
if _, _, err = conn.WriteMsgUnix(nil, syscall.UnixRights(int(fd)), nil); err != nil {
|
||||
ec <- fmsg.WrapErrorSuffix(err, "cannot pass wayland connection to shim:")
|
||||
return
|
||||
}
|
||||
ec <- nil
|
||||
|
||||
// block until shim exits
|
||||
<-wl.done
|
||||
fmsg.VPrintln("releasing wayland connection")
|
||||
}); err != nil {
|
||||
ec <- fmsg.WrapErrorSuffix(err, "cannot obtain wayland connection fd:")
|
||||
return
|
||||
}
|
||||
}()
|
||||
return <-ec
|
||||
}
|
||||
}
|
||||
|
||||
func (wl *Wayland) Close() error {
|
||||
wl.Do(func() {
|
||||
close(wl.done)
|
||||
wl.connErr = wl.conn.Close()
|
||||
})
|
||||
|
||||
return wl.connErr
|
||||
}
|
||||
|
||||
func NewWayland() *Wayland {
|
||||
wl := new(Wayland)
|
||||
wl.done = make(chan struct{})
|
||||
return wl
|
||||
}
|
@ -1,292 +0,0 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// fine-grained locking and access
|
||||
type multiStore struct {
|
||||
base string
|
||||
|
||||
// initialised backends
|
||||
backends *sync.Map
|
||||
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
func (s *multiStore) Do(aid int, f func(c Cursor)) (bool, error) {
|
||||
s.lock.RLock()
|
||||
defer s.lock.RUnlock()
|
||||
|
||||
// load or initialise new backend
|
||||
b := new(multiBackend)
|
||||
if v, ok := s.backends.LoadOrStore(aid, b); ok {
|
||||
b = v.(*multiBackend)
|
||||
} else {
|
||||
b.lock.Lock()
|
||||
b.path = path.Join(s.base, strconv.Itoa(aid))
|
||||
|
||||
// ensure directory
|
||||
if err := os.MkdirAll(b.path, 0700); err != nil && !errors.Is(err, fs.ErrExist) {
|
||||
s.backends.CompareAndDelete(aid, b)
|
||||
return false, err
|
||||
}
|
||||
|
||||
// open locker file
|
||||
if l, err := os.OpenFile(b.path+".lock", os.O_RDWR|os.O_CREATE, 0600); err != nil {
|
||||
s.backends.CompareAndDelete(aid, b)
|
||||
return false, err
|
||||
} else {
|
||||
b.lockfile = l
|
||||
}
|
||||
b.lock.Unlock()
|
||||
}
|
||||
|
||||
// lock backend
|
||||
if err := b.lockFile(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// expose backend methods without exporting the pointer
|
||||
c := new(struct{ *multiBackend })
|
||||
c.multiBackend = b
|
||||
f(b)
|
||||
// disable access to the backend on a best-effort basis
|
||||
c.multiBackend = nil
|
||||
|
||||
// unlock backend
|
||||
return true, b.unlockFile()
|
||||
}
|
||||
|
||||
func (s *multiStore) List() ([]int, error) {
|
||||
var entries []os.DirEntry
|
||||
|
||||
// read base directory to get all aids
|
||||
if v, err := os.ReadDir(s.base); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
} else {
|
||||
entries = v
|
||||
}
|
||||
|
||||
aidsBuf := make([]int, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
// skip non-directories
|
||||
if !e.IsDir() {
|
||||
fmsg.VPrintf("skipped non-directory entry %q", e.Name())
|
||||
continue
|
||||
}
|
||||
|
||||
// skip non-numerical names
|
||||
if v, err := strconv.Atoi(e.Name()); err != nil {
|
||||
fmsg.VPrintf("skipped non-aid entry %q", e.Name())
|
||||
continue
|
||||
} else {
|
||||
if v < 0 || v > 9999 {
|
||||
fmsg.VPrintf("skipped out of bounds entry %q", e.Name())
|
||||
continue
|
||||
}
|
||||
|
||||
aidsBuf = append(aidsBuf, v)
|
||||
}
|
||||
}
|
||||
|
||||
return append([]int(nil), aidsBuf...), nil
|
||||
}
|
||||
|
||||
func (s *multiStore) Close() error {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
|
||||
var errs []error
|
||||
s.backends.Range(func(_, value any) bool {
|
||||
b := value.(*multiBackend)
|
||||
errs = append(errs, b.close())
|
||||
return true
|
||||
})
|
||||
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
type multiBackend struct {
|
||||
path string
|
||||
|
||||
// created/opened by prepare
|
||||
lockfile *os.File
|
||||
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
func (b *multiBackend) filename(id *fst.ID) string {
|
||||
return path.Join(b.path, id.String())
|
||||
}
|
||||
|
||||
func (b *multiBackend) lockFileAct(lt int) (err error) {
|
||||
op := "LockAct"
|
||||
switch lt {
|
||||
case syscall.LOCK_EX:
|
||||
op = "Lock"
|
||||
case syscall.LOCK_UN:
|
||||
op = "Unlock"
|
||||
}
|
||||
|
||||
for {
|
||||
err = syscall.Flock(int(b.lockfile.Fd()), lt)
|
||||
if !errors.Is(err, syscall.EINTR) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return &fs.PathError{
|
||||
Op: op,
|
||||
Path: b.lockfile.Name(),
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *multiBackend) lockFile() error {
|
||||
return b.lockFileAct(syscall.LOCK_EX)
|
||||
}
|
||||
|
||||
func (b *multiBackend) unlockFile() error {
|
||||
return b.lockFileAct(syscall.LOCK_UN)
|
||||
}
|
||||
|
||||
// reads all launchers in simpleBackend
|
||||
// file contents are ignored if decode is false
|
||||
func (b *multiBackend) load(decode bool) (Entries, error) {
|
||||
b.lock.RLock()
|
||||
defer b.lock.RUnlock()
|
||||
|
||||
// read directory contents, should only contain files named after ids
|
||||
var entries []os.DirEntry
|
||||
if pl, err := os.ReadDir(b.path); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
entries = pl
|
||||
}
|
||||
|
||||
// allocate as if every entry is valid
|
||||
// since that should be the case assuming no external interference happens
|
||||
r := make(Entries, len(entries))
|
||||
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
return nil, fmt.Errorf("unexpected directory %q in store", e.Name())
|
||||
}
|
||||
|
||||
id := new(fst.ID)
|
||||
if err := fst.ParseAppID(id, e.Name()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// run in a function to better handle file closing
|
||||
if err := func() error {
|
||||
// open state file for reading
|
||||
if f, err := os.Open(path.Join(b.path, e.Name())); err != nil {
|
||||
return err
|
||||
} else {
|
||||
defer func() {
|
||||
if f.Close() != nil {
|
||||
// unreachable
|
||||
panic("foreign state file closed prematurely")
|
||||
}
|
||||
}()
|
||||
|
||||
s := new(State)
|
||||
r[*id] = s
|
||||
|
||||
// append regardless, but only parse if required, used to implement Len
|
||||
if decode {
|
||||
if err = gob.NewDecoder(f).Decode(s); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if s.ID != *id {
|
||||
return fmt.Errorf("state entry %s has unexpected id %s", id, &s.ID)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// Save writes process state to filesystem
|
||||
func (b *multiBackend) Save(state *State) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
if state.Config == nil {
|
||||
return errors.New("state does not contain config")
|
||||
}
|
||||
|
||||
statePath := b.filename(&state.ID)
|
||||
|
||||
// create and open state data file
|
||||
if f, err := os.OpenFile(statePath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600); err != nil {
|
||||
return err
|
||||
} else {
|
||||
defer func() {
|
||||
if f.Close() != nil {
|
||||
// unreachable
|
||||
panic("state file closed prematurely")
|
||||
}
|
||||
}()
|
||||
// encode into state file
|
||||
return gob.NewEncoder(f).Encode(state)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *multiBackend) Destroy(id fst.ID) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
return os.Remove(b.filename(&id))
|
||||
}
|
||||
|
||||
func (b *multiBackend) Load() (Entries, error) {
|
||||
return b.load(true)
|
||||
}
|
||||
|
||||
func (b *multiBackend) Len() (int, error) {
|
||||
// rn consists of only nil entries but has the correct length
|
||||
rn, err := b.load(false)
|
||||
return len(rn), err
|
||||
}
|
||||
|
||||
func (b *multiBackend) close() error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
err := b.lockfile.Close()
|
||||
if err == nil || errors.Is(err, os.ErrInvalid) || errors.Is(err, os.ErrClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// NewMulti returns an instance of the multi-file store.
|
||||
func NewMulti(runDir string) Store {
|
||||
b := new(multiStore)
|
||||
b.base = path.Join(runDir, "state")
|
||||
b.backends = new(sync.Map)
|
||||
return b
|
||||
}
|
@ -1,11 +0,0 @@
|
||||
package state_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/state"
|
||||
)
|
||||
|
||||
func TestMulti(t *testing.T) {
|
||||
testStore(t, state.NewMulti(t.TempDir()))
|
||||
}
|
@ -1,45 +1,62 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
// MustPrintLauncherStateSimpleGlobal prints active launcher states of all simple stores
|
||||
// in an implementation-specific way.
|
||||
func MustPrintLauncherStateSimpleGlobal(w **tabwriter.Writer, runDir string) {
|
||||
now := time.Now().UTC()
|
||||
s := NewMulti(runDir)
|
||||
|
||||
// read runtime directory to get all UIDs
|
||||
if aids, err := s.List(); err != nil {
|
||||
fmsg.Fatal("cannot list store:", err)
|
||||
if dirs, err := os.ReadDir(path.Join(runDir, "state")); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
fmsg.Fatal("cannot read runtime directory:", err)
|
||||
} else {
|
||||
for _, aid := range aids {
|
||||
// print states belonging to this store
|
||||
s.(*multiStore).mustPrintLauncherState(aid, w, now)
|
||||
}
|
||||
}
|
||||
for _, e := range dirs {
|
||||
// skip non-directories
|
||||
if !e.IsDir() {
|
||||
fmsg.VPrintf("skipped non-directory entry %q", e.Name())
|
||||
continue
|
||||
}
|
||||
|
||||
// mustPrintLauncherState causes store activity so store needs to be closed
|
||||
if err := s.Close(); err != nil {
|
||||
fmsg.Printf("cannot close store: %v", err)
|
||||
// skip non-numerical names
|
||||
if _, err = strconv.Atoi(e.Name()); err != nil {
|
||||
fmsg.VPrintf("skipped non-uid entry %q", e.Name())
|
||||
continue
|
||||
}
|
||||
|
||||
// obtain temporary store
|
||||
s := NewSimple(runDir, e.Name()).(*simpleStore)
|
||||
|
||||
// print states belonging to this store
|
||||
s.mustPrintLauncherState(w, now)
|
||||
|
||||
// mustPrintLauncherState causes store activity so store needs to be closed
|
||||
if err = s.Close(); err != nil {
|
||||
fmsg.Printf("cannot close store for user %q: %s", e.Name(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *multiStore) mustPrintLauncherState(aid int, w **tabwriter.Writer, now time.Time) {
|
||||
func (s *simpleStore) mustPrintLauncherState(w **tabwriter.Writer, now time.Time) {
|
||||
var innerErr error
|
||||
|
||||
if ok, err := s.Do(aid, func(c Cursor) {
|
||||
if ok, err := s.Do(func(b Backend) {
|
||||
innerErr = func() error {
|
||||
// read launcher states
|
||||
states, err := c.Load()
|
||||
states, err := b.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -50,10 +67,10 @@ func (s *multiStore) mustPrintLauncherState(aid int, w **tabwriter.Writer, now t
|
||||
|
||||
// write header when initialising
|
||||
if !fmsg.Verbose() {
|
||||
_, _ = fmt.Fprintln(*w, "\tPID\tApp\tUptime\tEnablements\tCommand")
|
||||
_, _ = fmt.Fprintln(*w, "\tUID\tPID\tUptime\tEnablements\tMethod\tCommand")
|
||||
} else {
|
||||
// argv is emitted in body when verbose
|
||||
_, _ = fmt.Fprintln(*w, "\tPID\tApp\tArgv")
|
||||
_, _ = fmt.Fprintln(*w, "\tUID\tPID\tArgv")
|
||||
}
|
||||
}
|
||||
|
||||
@ -65,54 +82,40 @@ func (s *multiStore) mustPrintLauncherState(aid int, w **tabwriter.Writer, now t
|
||||
continue
|
||||
}
|
||||
|
||||
// build enablements and command string
|
||||
var (
|
||||
ets *strings.Builder
|
||||
cs = "(No command information)"
|
||||
)
|
||||
|
||||
// check if enablements are provided
|
||||
if state.Config != nil {
|
||||
ets = new(strings.Builder)
|
||||
// append enablement strings in order
|
||||
for i := system.Enablement(0); i < system.Enablement(system.ELen); i++ {
|
||||
if state.Config.Confinement.Enablements.Has(i) {
|
||||
ets.WriteString(", " + i.String())
|
||||
}
|
||||
// build enablements string
|
||||
ets := strings.Builder{}
|
||||
// append enablement strings in order
|
||||
for i := system.Enablement(0); i < system.Enablement(system.ELen); i++ {
|
||||
if state.Capability.Has(i) {
|
||||
ets.WriteString(", " + i.String())
|
||||
}
|
||||
|
||||
cs = fmt.Sprintf("%q", state.Config.Command)
|
||||
}
|
||||
if ets != nil {
|
||||
// prevent an empty string
|
||||
if ets.Len() == 0 {
|
||||
ets.WriteString("(No enablements)")
|
||||
}
|
||||
} else {
|
||||
ets = new(strings.Builder)
|
||||
ets.WriteString("(No confinement information)")
|
||||
// prevent an empty string when
|
||||
if ets.Len() == 0 {
|
||||
ets.WriteString("(No enablements)")
|
||||
}
|
||||
|
||||
if !fmsg.Verbose() {
|
||||
_, _ = fmt.Fprintf(*w, "\t%d\t%d\t%s\t%s\t%s\n",
|
||||
state.PID, aid, now.Sub(state.Time).Round(time.Second).String(), strings.TrimPrefix(ets.String(), ", "), cs)
|
||||
_, _ = fmt.Fprintf(*w, "\t%s\t%d\t%s\t%s\t%s\t%s\n",
|
||||
s.path[len(s.path)-1], state.PID, now.Sub(state.Time).Round(time.Second).String(), strings.TrimPrefix(ets.String(), ", "), state.Method,
|
||||
state.Command)
|
||||
} else {
|
||||
// emit argv instead when verbose
|
||||
_, _ = fmt.Fprintf(*w, "\t%d\t%d\t%s\n",
|
||||
state.PID, aid, state.ID)
|
||||
_, _ = fmt.Fprintf(*w, "\t%s\t%d\t%s\n",
|
||||
s.path[len(s.path)-1], state.PID, state.Argv)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}()
|
||||
}); err != nil {
|
||||
fmsg.Printf("cannot perform action on app %d: %v", aid, err)
|
||||
fmsg.Printf("cannot perform action on store %q: %s", path.Join(s.path...), err)
|
||||
if !ok {
|
||||
fmsg.Fatal("store faulted before printing")
|
||||
}
|
||||
}
|
||||
|
||||
if innerErr != nil {
|
||||
fmsg.Fatalf("cannot print launcher state of app %d: %s", aid, innerErr)
|
||||
fmsg.Fatalf("cannot print launcher state for store %q: %s", path.Join(s.path...), innerErr)
|
||||
}
|
||||
}
|
||||
|
218
internal/state/simple.go
Normal file
218
internal/state/simple.go
Normal file
@ -0,0 +1,218 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"sync"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// file-based locking
|
||||
type simpleStore struct {
|
||||
path []string
|
||||
|
||||
// created/opened by prepare
|
||||
lockfile *os.File
|
||||
// enforce prepare method
|
||||
init sync.Once
|
||||
// error returned by prepare
|
||||
initErr error
|
||||
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
func (s *simpleStore) Do(f func(b Backend)) (bool, error) {
|
||||
s.init.Do(s.prepare)
|
||||
if s.initErr != nil {
|
||||
return false, s.initErr
|
||||
}
|
||||
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
|
||||
// lock store
|
||||
if err := s.lockFile(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// initialise new backend for caller
|
||||
b := new(simpleBackend)
|
||||
b.path = path.Join(s.path...)
|
||||
f(b)
|
||||
// disable backend
|
||||
b.lock.Lock()
|
||||
|
||||
// unlock store
|
||||
return true, s.unlockFile()
|
||||
}
|
||||
|
||||
func (s *simpleStore) lockFileAct(lt int) (err error) {
|
||||
op := "LockAct"
|
||||
switch lt {
|
||||
case syscall.LOCK_EX:
|
||||
op = "Lock"
|
||||
case syscall.LOCK_UN:
|
||||
op = "Unlock"
|
||||
}
|
||||
|
||||
for {
|
||||
err = syscall.Flock(int(s.lockfile.Fd()), lt)
|
||||
if !errors.Is(err, syscall.EINTR) {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return &fs.PathError{
|
||||
Op: op,
|
||||
Path: s.lockfile.Name(),
|
||||
Err: err,
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *simpleStore) lockFile() error {
|
||||
return s.lockFileAct(syscall.LOCK_EX)
|
||||
}
|
||||
|
||||
func (s *simpleStore) unlockFile() error {
|
||||
return s.lockFileAct(syscall.LOCK_UN)
|
||||
}
|
||||
|
||||
func (s *simpleStore) prepare() {
|
||||
s.initErr = func() error {
|
||||
prefix := path.Join(s.path...)
|
||||
// ensure directory
|
||||
if err := os.MkdirAll(prefix, 0700); err != nil && !errors.Is(err, fs.ErrExist) {
|
||||
return err
|
||||
}
|
||||
|
||||
// open locker file
|
||||
if f, err := os.OpenFile(prefix+".lock", os.O_RDWR|os.O_CREATE, 0600); err != nil {
|
||||
return err
|
||||
} else {
|
||||
s.lockfile = f
|
||||
}
|
||||
|
||||
return nil
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *simpleStore) Close() error {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
|
||||
err := s.lockfile.Close()
|
||||
if err == nil || errors.Is(err, os.ErrInvalid) || errors.Is(err, os.ErrClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type simpleBackend struct {
|
||||
path string
|
||||
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
func (b *simpleBackend) filename(pid int) string {
|
||||
return path.Join(b.path, strconv.Itoa(pid))
|
||||
}
|
||||
|
||||
// reads all launchers in simpleBackend
|
||||
// file contents are ignored if decode is false
|
||||
func (b *simpleBackend) load(decode bool) ([]*State, error) {
|
||||
b.lock.RLock()
|
||||
defer b.lock.RUnlock()
|
||||
|
||||
var (
|
||||
r []*State
|
||||
f *os.File
|
||||
)
|
||||
|
||||
// read directory contents, should only contain files named after PIDs
|
||||
if pl, err := os.ReadDir(b.path); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
for _, e := range pl {
|
||||
// run in a function to better handle file closing
|
||||
if err = func() error {
|
||||
// open state file for reading
|
||||
if f, err = os.Open(path.Join(b.path, e.Name())); err != nil {
|
||||
return err
|
||||
} else {
|
||||
defer func() {
|
||||
if f.Close() != nil {
|
||||
// unreachable
|
||||
panic("foreign state file closed prematurely")
|
||||
}
|
||||
}()
|
||||
|
||||
var s State
|
||||
r = append(r, &s)
|
||||
|
||||
// append regardless, but only parse if required, used to implement Len
|
||||
if decode {
|
||||
return gob.NewDecoder(f).Decode(&s)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// Save writes process state to filesystem
|
||||
func (b *simpleBackend) Save(state *State) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
statePath := b.filename(state.PID)
|
||||
|
||||
// create and open state data file
|
||||
if f, err := os.OpenFile(statePath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600); err != nil {
|
||||
return err
|
||||
} else {
|
||||
defer func() {
|
||||
if f.Close() != nil {
|
||||
// unreachable
|
||||
panic("state file closed prematurely")
|
||||
}
|
||||
}()
|
||||
// encode into state file
|
||||
return gob.NewEncoder(f).Encode(state)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *simpleBackend) Destroy(pid int) error {
|
||||
b.lock.Lock()
|
||||
defer b.lock.Unlock()
|
||||
|
||||
return os.Remove(b.filename(pid))
|
||||
}
|
||||
|
||||
func (b *simpleBackend) Load() ([]*State, error) {
|
||||
return b.load(true)
|
||||
}
|
||||
|
||||
func (b *simpleBackend) Len() (int, error) {
|
||||
// rn consists of only nil entries but has the correct length
|
||||
rn, err := b.load(false)
|
||||
return len(rn), err
|
||||
}
|
||||
|
||||
// NewSimple returns an instance of a file-based store.
|
||||
func NewSimple(runDir string, prefix ...string) Store {
|
||||
b := new(simpleStore)
|
||||
b.path = append([]string{runDir, "state"}, prefix...)
|
||||
return b
|
||||
}
|
@ -3,42 +3,40 @@ package state
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
type Entries map[fst.ID]*State
|
||||
|
||||
type Store interface {
|
||||
// Do calls f exactly once and ensures store exclusivity until f returns.
|
||||
// Returns whether f is called and any errors during the locking process.
|
||||
// Cursor provided to f becomes invalid as soon as f returns.
|
||||
Do(aid int, f func(c Cursor)) (ok bool, err error)
|
||||
|
||||
// List queries the store and returns a list of aids known to the store.
|
||||
// Note that some or all returned aids might not have any active apps.
|
||||
List() (aids []int, err error)
|
||||
// Backend provided to f becomes invalid as soon as f returns.
|
||||
Do(f func(b Backend)) (bool, error)
|
||||
|
||||
// Close releases any resources held by Store.
|
||||
Close() error
|
||||
}
|
||||
|
||||
// Cursor provides access to the store
|
||||
type Cursor interface {
|
||||
// Backend provides access to the store
|
||||
type Backend interface {
|
||||
Save(state *State) error
|
||||
Destroy(id fst.ID) error
|
||||
Load() (Entries, error)
|
||||
Destroy(pid int) error
|
||||
Load() ([]*State, error)
|
||||
Len() (int, error)
|
||||
}
|
||||
|
||||
// State is the on-disk format for a fortified process's state information
|
||||
type State struct {
|
||||
// fortify instance id
|
||||
ID fst.ID `json:"instance"`
|
||||
// child process PID value
|
||||
PID int `json:"pid"`
|
||||
// sealed app configuration
|
||||
Config *fst.Config `json:"config"`
|
||||
PID int
|
||||
// command used to seal the app
|
||||
Command []string
|
||||
// capability enablements applied to child
|
||||
Capability system.Enablements
|
||||
|
||||
// user switch method
|
||||
Method string
|
||||
// full argv whe launching
|
||||
Argv []string
|
||||
// process start time
|
||||
Time time.Time
|
||||
}
|
||||
|
@ -1,126 +0,0 @@
|
||||
package state_test
|
||||
|
||||
import (
|
||||
"math/rand/v2"
|
||||
"reflect"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/internal/state"
|
||||
)
|
||||
|
||||
func testStore(t *testing.T, s state.Store) {
|
||||
t.Run("list empty store", func(t *testing.T) {
|
||||
if aids, err := s.List(); err != nil {
|
||||
t.Fatalf("List: error = %v", err)
|
||||
} else if len(aids) != 0 {
|
||||
t.Fatalf("List: aids = %#v", aids)
|
||||
}
|
||||
})
|
||||
|
||||
const (
|
||||
insertEntryChecked = iota
|
||||
insertEntryNoCheck
|
||||
insertEntryOtherApp
|
||||
|
||||
tl
|
||||
)
|
||||
|
||||
var tc [tl]state.State
|
||||
for i := 0; i < tl; i++ {
|
||||
makeState(t, &tc[i])
|
||||
}
|
||||
|
||||
do := func(aid int, f func(c state.Cursor)) {
|
||||
if ok, err := s.Do(aid, f); err != nil {
|
||||
t.Fatalf("Do: ok = %v, error = %v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
insert := func(i, aid int) {
|
||||
do(aid, func(c state.Cursor) {
|
||||
if err := c.Save(&tc[i]); err != nil {
|
||||
t.Fatalf("Save(&tc[%v]): error = %v", i, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
check := func(i, aid int) {
|
||||
do(aid, func(c state.Cursor) {
|
||||
if entries, err := c.Load(); err != nil {
|
||||
t.Fatalf("Load: error = %v", err)
|
||||
} else if got, ok := entries[tc[i].ID]; !ok {
|
||||
t.Fatalf("Load: entry %s missing",
|
||||
&tc[i].ID)
|
||||
} else {
|
||||
got.Time = tc[i].Time
|
||||
if !reflect.DeepEqual(got, &tc[i]) {
|
||||
t.Fatalf("Load: entry %s got %#v, want %#v",
|
||||
&tc[i].ID, got, &tc[i])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("insert entry checked", func(t *testing.T) {
|
||||
insert(insertEntryChecked, 0)
|
||||
check(insertEntryChecked, 0)
|
||||
})
|
||||
|
||||
t.Run("insert entry unchecked", func(t *testing.T) {
|
||||
insert(insertEntryNoCheck, 0)
|
||||
})
|
||||
|
||||
t.Run("insert entry different aid", func(t *testing.T) {
|
||||
insert(insertEntryOtherApp, 1)
|
||||
check(insertEntryOtherApp, 1)
|
||||
})
|
||||
|
||||
t.Run("check previous insertion", func(t *testing.T) {
|
||||
check(insertEntryNoCheck, 0)
|
||||
})
|
||||
|
||||
t.Run("list aids", func(t *testing.T) {
|
||||
if aids, err := s.List(); err != nil {
|
||||
t.Fatalf("List: error = %v", err)
|
||||
} else {
|
||||
slices.Sort(aids)
|
||||
want := []int{0, 1}
|
||||
if slices.Compare(aids, want) != 0 {
|
||||
t.Fatalf("List() = %#v, want %#v", aids, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("clear aid 1", func(t *testing.T) {
|
||||
do(1, func(c state.Cursor) {
|
||||
if err := c.Destroy(tc[insertEntryOtherApp].ID); err != nil {
|
||||
t.Fatalf("Destroy: error = %v", err)
|
||||
}
|
||||
})
|
||||
do(1, func(c state.Cursor) {
|
||||
if l, err := c.Len(); err != nil {
|
||||
t.Fatalf("Len: error = %v", err)
|
||||
} else if l != 0 {
|
||||
t.Fatalf("Len() = %d, want 0", l)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("close store", func(t *testing.T) {
|
||||
if err := s.Close(); err != nil {
|
||||
t.Fatalf("Close: error = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func makeState(t *testing.T, s *state.State) {
|
||||
if err := fst.NewAppID(&s.ID); err != nil {
|
||||
t.Fatalf("cannot create dummy state: %v", err)
|
||||
}
|
||||
s.Config = fst.Template()
|
||||
s.PID = rand.Int()
|
||||
s.Time = time.Now()
|
||||
}
|
@ -1,13 +1,15 @@
|
||||
package linux
|
||||
package internal
|
||||
|
||||
import (
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/user"
|
||||
"path"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// System provides safe access to operating system resources.
|
||||
@ -22,8 +24,8 @@ type System interface {
|
||||
LookPath(file string) (string, error)
|
||||
// Executable provides [os.Executable].
|
||||
Executable() (string, error)
|
||||
// LookupGroup provides [user.LookupGroup].
|
||||
LookupGroup(name string) (*user.Group, error)
|
||||
// Lookup provides [user.Lookup].
|
||||
Lookup(username string) (*user.User, error)
|
||||
// ReadDir provides [os.ReadDir].
|
||||
ReadDir(name string) ([]fs.DirEntry, error)
|
||||
// Stat provides [os.Stat].
|
||||
@ -32,13 +34,9 @@ type System interface {
|
||||
Open(name string) (fs.File, error)
|
||||
// Exit provides [os.Exit].
|
||||
Exit(code int)
|
||||
// Stdout provides [os.Stdout].
|
||||
Stdout() io.Writer
|
||||
|
||||
// Paths returns a populated [Paths] struct.
|
||||
Paths() Paths
|
||||
// Uid invokes fsu and returns target uid.
|
||||
Uid(aid int) (int, error)
|
||||
}
|
||||
|
||||
// Paths contains environment dependent paths used by fortify.
|
||||
@ -68,3 +66,55 @@ func CopyPaths(os System, v *Paths) {
|
||||
|
||||
fmsg.VPrintf("runtime directory at %q", v.RunDirPath)
|
||||
}
|
||||
|
||||
// Std implements System using the standard library.
|
||||
type Std struct {
|
||||
paths Paths
|
||||
pathsOnce sync.Once
|
||||
}
|
||||
|
||||
func (s *Std) Geteuid() int {
|
||||
return os.Geteuid()
|
||||
}
|
||||
|
||||
func (s *Std) LookupEnv(key string) (string, bool) {
|
||||
return os.LookupEnv(key)
|
||||
}
|
||||
|
||||
func (s *Std) TempDir() string {
|
||||
return os.TempDir()
|
||||
}
|
||||
|
||||
func (s *Std) LookPath(file string) (string, error) {
|
||||
return exec.LookPath(file)
|
||||
}
|
||||
|
||||
func (s *Std) Executable() (string, error) {
|
||||
return os.Executable()
|
||||
}
|
||||
|
||||
func (s *Std) Lookup(username string) (*user.User, error) {
|
||||
return user.Lookup(username)
|
||||
}
|
||||
|
||||
func (s *Std) ReadDir(name string) ([]os.DirEntry, error) {
|
||||
return os.ReadDir(name)
|
||||
}
|
||||
|
||||
func (s *Std) Stat(name string) (fs.FileInfo, error) {
|
||||
return os.Stat(name)
|
||||
}
|
||||
|
||||
func (s *Std) Open(name string) (fs.File, error) {
|
||||
return os.Open(name)
|
||||
}
|
||||
func (s *Std) Exit(code int) {
|
||||
fmsg.Exit(code)
|
||||
}
|
||||
|
||||
const xdgRuntimeDir = "XDG_RUNTIME_DIR"
|
||||
|
||||
func (s *Std) Paths() Paths {
|
||||
s.pathsOnce.Do(func() { CopyPaths(s, &s.paths) })
|
||||
return s.paths
|
||||
}
|
@ -4,8 +4,8 @@ import (
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// UpdatePerm appends an ephemeral acl update Op.
|
||||
|
@ -3,7 +3,7 @@ package system
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
)
|
||||
|
||||
func TestUpdatePerm(t *testing.T) {
|
||||
|
@ -1,29 +1,18 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrDBusConfig = errors.New("dbus config not supplied")
|
||||
)
|
||||
|
||||
func (sys *I) MustProxyDBus(sessionPath string, session *dbus.Config, systemPath string, system *dbus.Config) *I {
|
||||
if _, err := sys.ProxyDBus(session, system, sessionPath, systemPath); err != nil {
|
||||
panic(err.Error())
|
||||
} else {
|
||||
return sys
|
||||
}
|
||||
}
|
||||
|
||||
func (sys *I) ProxyDBus(session, system *dbus.Config, sessionPath, systemPath string) (func(f func(msgbuf []string)), error) {
|
||||
func (sys *I) ProxyDBus(session, system *dbus.Config, sessionPath, systemPath string) error {
|
||||
d := new(DBus)
|
||||
|
||||
// used by waiting goroutine to notify process exit
|
||||
@ -31,7 +20,7 @@ func (sys *I) ProxyDBus(session, system *dbus.Config, sessionPath, systemPath st
|
||||
|
||||
// session bus is mandatory
|
||||
if session == nil {
|
||||
return nil, fmsg.WrapError(ErrDBusConfig,
|
||||
return fmsg.WrapError(ErrDBusConfig,
|
||||
"attempted to seal message bus proxy without session bus config")
|
||||
}
|
||||
|
||||
@ -64,15 +53,13 @@ func (sys *I) ProxyDBus(session, system *dbus.Config, sessionPath, systemPath st
|
||||
sys.ops = append(sys.ops, d)
|
||||
|
||||
// seal dbus proxy
|
||||
d.out = &scanToFmsg{msg: new(strings.Builder)}
|
||||
return d.out.F, fmsg.WrapErrorSuffix(d.proxy.Seal(session, system),
|
||||
return fmsg.WrapErrorSuffix(d.proxy.Seal(session, system),
|
||||
"cannot seal message bus proxy:")
|
||||
}
|
||||
|
||||
type DBus struct {
|
||||
proxy *dbus.Proxy
|
||||
|
||||
out *scanToFmsg
|
||||
// whether system bus proxy is enabled
|
||||
system bool
|
||||
// notification from goroutine waiting for dbus.Proxy
|
||||
@ -93,7 +80,7 @@ func (d *DBus) apply(_ *I) error {
|
||||
ready := make(chan error, 1)
|
||||
|
||||
// background dbus proxy start
|
||||
if err := d.proxy.Start(ready, d.out, true); err != nil {
|
||||
if err := d.proxy.Start(ready, os.Stderr, true); err != nil {
|
||||
return fmsg.WrapErrorSuffix(err,
|
||||
"cannot start message bus proxy:")
|
||||
}
|
||||
@ -157,9 +144,7 @@ func (d *DBus) revert(_ *I, _ *Criteria) error {
|
||||
|
||||
func (d *DBus) Is(o Op) bool {
|
||||
d0, ok := o.(*DBus)
|
||||
return ok && d0 != nil &&
|
||||
((d.proxy == nil && d0.proxy == nil) ||
|
||||
(d.proxy != nil && d0.proxy != nil && d.proxy.String() == d0.proxy.String()))
|
||||
return ok && d0 != nil && *d == *d0
|
||||
}
|
||||
|
||||
func (d *DBus) Path() string {
|
||||
@ -169,34 +154,3 @@ func (d *DBus) Path() string {
|
||||
func (d *DBus) String() string {
|
||||
return d.proxy.String()
|
||||
}
|
||||
|
||||
type scanToFmsg struct {
|
||||
msg *strings.Builder
|
||||
msgbuf []string
|
||||
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func (s *scanToFmsg) Write(p []byte) (n int, err error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.write(p, 0)
|
||||
}
|
||||
|
||||
func (s *scanToFmsg) write(p []byte, a int) (int, error) {
|
||||
if i := bytes.IndexByte(p, '\n'); i == -1 {
|
||||
n, _ := s.msg.Write(p)
|
||||
return a + n, nil
|
||||
} else {
|
||||
n, _ := s.msg.Write(p[:i])
|
||||
s.msgbuf = append(s.msgbuf, s.msg.String())
|
||||
s.msg.Reset()
|
||||
return s.write(p[i+1:], a+n+1)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *scanToFmsg) F(f func(msgbuf []string)) {
|
||||
s.mu.RLock()
|
||||
f(s.msgbuf)
|
||||
s.mu.RUnlock()
|
||||
}
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// Ensure the existence and mode of a directory.
|
||||
|
@ -2,10 +2,9 @@ package system
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -57,7 +56,6 @@ func TypeString(e Enablement) string {
|
||||
type I struct {
|
||||
uid int
|
||||
ops []Op
|
||||
sp *os.File
|
||||
|
||||
state [2]bool
|
||||
lock sync.Mutex
|
||||
@ -67,10 +65,6 @@ func (sys *I) UID() int {
|
||||
return sys.uid
|
||||
}
|
||||
|
||||
func (sys *I) Sync() *os.File {
|
||||
return sys.sp
|
||||
}
|
||||
|
||||
func (sys *I) Equal(v *I) bool {
|
||||
if v == nil || sys.uid != v.uid || len(sys.ops) != len(v.ops) {
|
||||
return false
|
||||
|
@ -4,7 +4,7 @@ import (
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
|
@ -7,8 +7,8 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// CopyFile registers an Op that copies path dst from src.
|
||||
|
@ -4,7 +4,7 @@ import (
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
)
|
||||
|
||||
func TestCopyFile(t *testing.T) {
|
||||
|
@ -1,85 +0,0 @@
|
||||
package system
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/wl"
|
||||
)
|
||||
|
||||
// Wayland sets up a wayland socket with a security context attached.
|
||||
func (sys *I) Wayland(dst, src, appID, instanceID string) *I {
|
||||
sys.lock.Lock()
|
||||
defer sys.lock.Unlock()
|
||||
|
||||
sys.ops = append(sys.ops, Wayland{[2]string{dst, src}, new(wl.Conn), appID, instanceID})
|
||||
|
||||
return sys
|
||||
}
|
||||
|
||||
type Wayland struct {
|
||||
pair [2]string
|
||||
conn *wl.Conn
|
||||
|
||||
appID, instanceID string
|
||||
}
|
||||
|
||||
func (w Wayland) Type() Enablement {
|
||||
return Process
|
||||
}
|
||||
|
||||
func (w Wayland) apply(sys *I) error {
|
||||
// the Wayland op is not repeatable
|
||||
if sys.sp != nil {
|
||||
return errors.New("attempted to attach multiple wayland sockets")
|
||||
}
|
||||
|
||||
if err := w.conn.Attach(w.pair[1]); err != nil {
|
||||
return fmsg.WrapErrorSuffix(err,
|
||||
fmt.Sprintf("cannot attach to wayland on %q:", w.pair[1]))
|
||||
} else {
|
||||
fmsg.VPrintf("wayland attached on %q", w.pair[1])
|
||||
}
|
||||
|
||||
if sp, err := w.conn.Bind(w.pair[0], w.appID, w.instanceID); err != nil {
|
||||
return fmsg.WrapErrorSuffix(err,
|
||||
fmt.Sprintf("cannot bind to socket on %q:", w.pair[0]))
|
||||
} else {
|
||||
sys.sp = sp
|
||||
fmsg.VPrintf("wayland listening on %q", w.pair[0])
|
||||
return fmsg.WrapErrorSuffix(errors.Join(os.Chmod(w.pair[0], 0), acl.UpdatePerm(w.pair[0], sys.uid, acl.Read, acl.Write, acl.Execute)),
|
||||
fmt.Sprintf("cannot chmod socket on %q:", w.pair[0]))
|
||||
}
|
||||
}
|
||||
|
||||
func (w Wayland) revert(_ *I, ec *Criteria) error {
|
||||
if ec.hasType(w) {
|
||||
fmsg.VPrintf("removing wayland socket on %q", w.pair[0])
|
||||
if err := os.Remove(w.pair[0]); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
|
||||
fmsg.VPrintf("detaching from wayland on %q", w.pair[1])
|
||||
return fmsg.WrapErrorSuffix(w.conn.Close(),
|
||||
fmt.Sprintf("cannot detach from wayland on %q:", w.pair[1]))
|
||||
} else {
|
||||
fmsg.VPrintf("skipping wayland cleanup on %q", w.pair[0])
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (w Wayland) Is(o Op) bool {
|
||||
w0, ok := o.(Wayland)
|
||||
return ok && w.pair == w0.pair
|
||||
}
|
||||
|
||||
func (w Wayland) Path() string {
|
||||
return w.pair[0]
|
||||
}
|
||||
|
||||
func (w Wayland) String() string {
|
||||
return fmt.Sprintf("wayland socket at %q", w.pair[0])
|
||||
}
|
@ -3,8 +3,8 @@ package system
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/xcb"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/xcb"
|
||||
)
|
||||
|
||||
// ChangeHosts appends an X11 ChangeHosts command Op.
|
||||
|
@ -6,8 +6,8 @@ import (
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
)
|
||||
|
||||
func Exec(p string) ([]*Entry, error) {
|
||||
|
@ -1,4 +1,3 @@
|
||||
// Package ldd retrieves linker information by invoking ldd from glibc or musl and parsing its output.
|
||||
package ldd
|
||||
|
||||
import (
|
||||
|
@ -6,7 +6,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/ldd"
|
||||
"git.ophivana.moe/security/fortify/ldd"
|
||||
)
|
||||
|
||||
func TestParseError(t *testing.T) {
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user