Compare commits
23 Commits
Author | SHA1 | Date | |
---|---|---|---|
195b717e01 | |||
df6fc298f6 | |||
eae3034260 | |||
5ea7333431 | |||
f796622c35 | |||
5d25bee786 | |||
b48ece3bb0 | |||
9f95f60400 | |||
90dd57f75d | |||
141f2e3685 | |||
73aa285e8f | |||
6e87fc02dd | |||
52f21a19f3 | |||
7be53a2438 | |||
7f29b37a32 | |||
f69e8e753e | |||
ef8fd37e9d | |||
2f676c9d6e | |||
bbace8f84b | |||
2efedf56c0 | |||
b752ec4468 | |||
5d00805a7c | |||
7b6052a473 |
@ -22,5 +22,25 @@ jobs:
|
||||
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
|
||||
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
|
||||
|
@ -11,19 +11,22 @@ jobs:
|
||||
container:
|
||||
image: node:16-bookworm-slim
|
||||
steps:
|
||||
- name: Get dependencies
|
||||
- name: Enable backports
|
||||
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
|
||||
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
|
||||
@ -44,13 +47,16 @@ jobs:
|
||||
run: >-
|
||||
go test ./...
|
||||
|
||||
- name: Build for Linux
|
||||
- name: Build for test
|
||||
id: build-test
|
||||
run: >-
|
||||
go build -v -ldflags '-s -w
|
||||
-X git.ophivana.moe/security/fortify/internal.Version=${{ github.ref_name }}
|
||||
-X git.ophivana.moe/security/fortify/internal.Fsu=/usr/bin/fsu
|
||||
-X git.ophivana.moe/security/fortify/internal.Finit=/usr/libexec/fortify/finit
|
||||
-X main.Fmain=/usr/bin/fortify
|
||||
-X main.Fshim=/usr/libexec/fortify/fshim'
|
||||
-o bin/ ./... &&
|
||||
(cd bin && sha512sum --tag -b * > sha512sums)
|
||||
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
|
||||
|
@ -1,8 +1,8 @@
|
||||
Fortify
|
||||
=======
|
||||
|
||||
[![Go Reference](https://pkg.go.dev/badge/git.ophivana.moe/security/fortify.svg)](https://pkg.go.dev/git.ophivana.moe/security/fortify)
|
||||
[![Go Report Card](https://goreportcard.com/badge/git.ophivana.moe/security/fortify)](https://goreportcard.com/report/git.ophivana.moe/security/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)
|
||||
|
||||
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.
|
||||
@ -18,7 +18,7 @@ Why would you want this?
|
||||
If you have a flakes-enabled nix environment, you can try out the tool by running:
|
||||
|
||||
```shell
|
||||
nix run git+https://git.ophivana.moe/security/fortify -- help
|
||||
nix run git+https://git.gensokyo.uk/security/fortify -- help
|
||||
```
|
||||
|
||||
## Module usage
|
||||
@ -35,7 +35,7 @@ To use the module, import it into your configuration with
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
|
||||
|
||||
fortify = {
|
||||
url = "git+https://git.ophivana.moe/security/fortify";
|
||||
url = "git+https://git.gensokyo.uk/security/fortify";
|
||||
|
||||
# Optional but recommended to limit the size of your system closure.
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
|
@ -7,7 +7,7 @@ import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
)
|
||||
|
||||
const testFileName = "acl.test"
|
||||
@ -15,8 +15,6 @@ const testFileName = "acl.test"
|
||||
var (
|
||||
uid = os.Geteuid()
|
||||
cred = int32(os.Geteuid())
|
||||
|
||||
testFilePath = path.Join(os.TempDir(), testFileName)
|
||||
)
|
||||
|
||||
func TestUpdatePerm(t *testing.T) {
|
||||
@ -25,6 +23,8 @@ func TestUpdatePerm(t *testing.T) {
|
||||
t.SkipNow()
|
||||
}
|
||||
|
||||
testFilePath := path.Join(t.TempDir(), testFileName)
|
||||
|
||||
if f, err := os.Create(testFilePath); err != nil {
|
||||
t.Fatalf("Create: error = %v", err)
|
||||
} else {
|
||||
@ -64,16 +64,16 @@ func TestUpdatePerm(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
testUpdate(t, "r--", cur, fAclPermRead, acl.Read)
|
||||
testUpdate(t, "-w-", cur, fAclPermWrite, acl.Write)
|
||||
testUpdate(t, "--x", cur, fAclPermExecute, acl.Execute)
|
||||
testUpdate(t, "-wx", cur, fAclPermWrite|fAclPermExecute, acl.Write, acl.Execute)
|
||||
testUpdate(t, "r-x", cur, fAclPermRead|fAclPermExecute, acl.Read, acl.Execute)
|
||||
testUpdate(t, "rw-", cur, fAclPermRead|fAclPermWrite, acl.Read, acl.Write)
|
||||
testUpdate(t, "rwx", cur, fAclPermRead|fAclPermWrite|fAclPermExecute, acl.Read, acl.Write, acl.Execute)
|
||||
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, name string, cur []*getFAclResp, val fAclPerm, perms ...acl.Perm) {
|
||||
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 {
|
||||
|
@ -1,19 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
init0 "git.ophivana.moe/security/fortify/cmd/finit/ipc"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
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"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -48,30 +47,24 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
// setup pipe fd from environment
|
||||
var setup *os.File
|
||||
if s, ok := os.LookupEnv(init0.Env); !ok {
|
||||
fmsg.Fatal("FORTIFY_INIT not set")
|
||||
panic("unreachable")
|
||||
} else {
|
||||
if fd, err := strconv.Atoi(s); err != nil {
|
||||
fmsg.Fatalf("cannot parse %q: %v", s, err)
|
||||
panic("unreachable")
|
||||
} else {
|
||||
setup = os.NewFile(uintptr(fd), "setup")
|
||||
if setup == nil {
|
||||
fmsg.Fatal("invalid config descriptor")
|
||||
panic("unreachable")
|
||||
}
|
||||
// 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")
|
||||
}
|
||||
}
|
||||
|
||||
var payload init0.Payload
|
||||
if err := gob.NewDecoder(setup).Decode(&payload); err != nil {
|
||||
fmsg.Fatal("cannot decode init setup payload:", err)
|
||||
fmsg.Fatalf("cannot decode init setup payload: %v", err)
|
||||
panic("unreachable")
|
||||
} else {
|
||||
fmsg.SetVerbose(payload.Verbose)
|
||||
closeSetup = f
|
||||
|
||||
// child does not need to see this
|
||||
if err = os.Unsetenv(init0.Env); err != nil {
|
||||
@ -98,7 +91,7 @@ func main() {
|
||||
fmsg.Suspend()
|
||||
|
||||
// close setup pipe as setup is now complete
|
||||
if err := setup.Close(); err != nil {
|
||||
if err := closeSetup(); err != nil {
|
||||
fmsg.Println("cannot close setup pipe:", err)
|
||||
// not fatal
|
||||
}
|
||||
|
@ -1,11 +1,7 @@
|
||||
package shim0
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"net"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
)
|
||||
|
||||
const Env = "FORTIFY_SHIM"
|
||||
@ -23,13 +19,3 @@ type Payload struct {
|
||||
// verbosity pass through
|
||||
Verbose bool
|
||||
}
|
||||
|
||||
func (p *Payload) Serve(conn *net.UnixConn) error {
|
||||
if err := gob.NewEncoder(conn).Encode(*p); err != nil {
|
||||
return fmsg.WrapErrorSuffix(err,
|
||||
"cannot stream shim payload:")
|
||||
}
|
||||
|
||||
return fmsg.WrapErrorSuffix(conn.Close(),
|
||||
"cannot close setup connection:")
|
||||
}
|
||||
|
@ -1,22 +1,20 @@
|
||||
package shim
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
shim0 "git.ophivana.moe/security/fortify/cmd/fshim/ipc"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/proc"
|
||||
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
|
||||
@ -32,20 +30,14 @@ type Shim struct {
|
||||
aid string
|
||||
// string representation of supplementary group ids
|
||||
supp []string
|
||||
// path to setup socket
|
||||
socket string
|
||||
// shim setup abort reason and completion
|
||||
abort chan error
|
||||
abortErr atomic.Pointer[error]
|
||||
abortOnce sync.Once
|
||||
// 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, socket string, payload *shim0.Payload) *Shim {
|
||||
return &Shim{uid: uid, aid: aid, supp: supp, socket: socket, payload: 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 {
|
||||
@ -59,39 +51,11 @@ 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
|
||||
}
|
||||
|
||||
func (s *Shim) WaitFallback() chan error {
|
||||
return s.killFallback
|
||||
}
|
||||
|
||||
func (s *Shim) Start() (*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
|
||||
var fsu string
|
||||
if p, ok := internal.Check(internal.Fsu); !ok {
|
||||
@ -101,10 +65,19 @@ func (s *Shim) Start() (*time.Time, error) {
|
||||
fsu = p
|
||||
}
|
||||
s.cmd = exec.Command(fsu)
|
||||
s.cmd.Env = []string{
|
||||
shim0.Env + "=" + s.socket,
|
||||
"FORTIFY_APP_ID=" + s.aid,
|
||||
|
||||
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, " "))
|
||||
@ -145,117 +118,20 @@ func (s *Shim) Start() (*time.Time, error) {
|
||||
signal.Ignore(syscall.SIGINT, syscall.SIGTERM)
|
||||
}()
|
||||
|
||||
accept()
|
||||
var conn *net.UnixConn
|
||||
shimErr := make(chan error)
|
||||
go func() { shimErr <- encoder.Encode(s.payload) }()
|
||||
|
||||
select {
|
||||
case c := <-cf:
|
||||
if c == nil {
|
||||
return &startTime, fmsg.WrapErrorSuffix(*s.abortErr.Load(), "cannot accept call on setup socket:")
|
||||
} else {
|
||||
conn = c
|
||||
case err := <-shimErr:
|
||||
if err != nil {
|
||||
return &startTime, fmsg.WrapErrorSuffix(err,
|
||||
"cannot transmit shim config:")
|
||||
}
|
||||
case <-time.After(shimSetupTimeout):
|
||||
err := fmsg.WrapError(errors.New("timed out waiting for shim"),
|
||||
"timed out waiting for shim to connect")
|
||||
s.AbortWait(err)
|
||||
return &startTime, err
|
||||
}
|
||||
|
||||
// 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 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
|
||||
// this also closes the connection
|
||||
err := s.payload.Serve(conn)
|
||||
if err == nil {
|
||||
killShim = func() {}
|
||||
case <-time.After(shimSetupTimeout):
|
||||
return &startTime, fmsg.WrapError(errors.New("timed out waiting for shim"),
|
||||
"timed out waiting for shim")
|
||||
}
|
||||
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() {
|
||||
cfWg := new(sync.WaitGroup)
|
||||
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)
|
||||
go func() {
|
||||
cfWg.Wait()
|
||||
close(cf)
|
||||
}()
|
||||
return
|
||||
case <-accept:
|
||||
cfWg.Add(1)
|
||||
go func() {
|
||||
defer cfWg.Done()
|
||||
if conn, err0 := l.AcceptUnix(); err0 != nil {
|
||||
// breaks loop
|
||||
s.Abort(err0)
|
||||
// receiver sees nil value and loads err0 stored during abort
|
||||
cf <- nil
|
||||
} 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
|
||||
|
||||
return &startTime, nil
|
||||
}
|
||||
|
@ -1,18 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
"net"
|
||||
"errors"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"syscall"
|
||||
|
||||
init0 "git.ophivana.moe/security/fortify/cmd/finit/ipc"
|
||||
shim "git.ophivana.moe/security/fortify/cmd/fshim/ipc"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
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
|
||||
@ -37,15 +37,6 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
// lookup socket path from environment
|
||||
var socketPath string
|
||||
if s, ok := os.LookupEnv(shim.Env); !ok {
|
||||
fmsg.Fatal("FORTIFY_SHIM not set")
|
||||
panic("unreachable")
|
||||
} else {
|
||||
socketPath = s
|
||||
}
|
||||
|
||||
// check path to finit
|
||||
var finitPath string
|
||||
if p, ok := internal.Path(internal.Finit); !ok {
|
||||
@ -54,21 +45,24 @@ func main() {
|
||||
finitPath = p
|
||||
}
|
||||
|
||||
// dial setup socket
|
||||
var conn *net.UnixConn
|
||||
if c, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: socketPath, Net: "unix"}); err != nil {
|
||||
fmsg.Fatal(err.Error())
|
||||
// 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 {
|
||||
conn = c
|
||||
}
|
||||
|
||||
// decode payload gob stream
|
||||
var payload shim.Payload
|
||||
if err := gob.NewDecoder(conn).Decode(&payload); err != nil {
|
||||
fmsg.Fatalf("cannot decode shim payload: %v", err)
|
||||
} else {
|
||||
fmsg.SetVerbose(payload.Verbose)
|
||||
closeSetup = f
|
||||
}
|
||||
|
||||
if payload.Bwrap == nil {
|
||||
@ -81,8 +75,8 @@ func main() {
|
||||
}
|
||||
|
||||
// close setup socket
|
||||
if err := conn.Close(); err != nil {
|
||||
fmsg.Println("cannot close setup socket:", err)
|
||||
if err := closeSetup(); err != nil {
|
||||
fmsg.Println("cannot close setup pipe:", err)
|
||||
// not fatal
|
||||
}
|
||||
|
||||
@ -110,17 +104,14 @@ func main() {
|
||||
|
||||
var extraFiles []*os.File
|
||||
|
||||
// share config pipe
|
||||
if r, w, err := os.Pipe(); err != nil {
|
||||
// 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(3 + len(extraFiles))
|
||||
extraFiles = append(extraFiles, r)
|
||||
|
||||
fmsg.VPrintln("transmitting config to init")
|
||||
conf.SetEnv[init0.Env] = strconv.Itoa(fd)
|
||||
go func() {
|
||||
// stream config to pipe
|
||||
if err = gob.NewEncoder(w).Encode(&ic); err != nil {
|
||||
fmsg.VPrintln("transmitting config to init")
|
||||
if err = encoder.Encode(&ic); err != nil {
|
||||
fmsg.Fatalf("cannot transmit init config: %v", err)
|
||||
}
|
||||
}()
|
||||
|
@ -83,17 +83,17 @@ func main() {
|
||||
uid += aid
|
||||
}
|
||||
|
||||
// pass through setup path to shim
|
||||
var shimSetupPath string
|
||||
// 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 !path.IsAbs(s) {
|
||||
log.Fatal("FORTIFY_SHIM is not absolute")
|
||||
} else if len(s) != 1 || s[0] > '9' || s[0] < '3' {
|
||||
log.Fatal("FORTIFY_SHIM holds an invalid value")
|
||||
} else {
|
||||
shimSetupPath = s
|
||||
shimSetupFd = s
|
||||
}
|
||||
|
||||
// supplementary groups
|
||||
@ -142,7 +142,7 @@ func main() {
|
||||
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 + "=" + shimSetupPath}); err != nil {
|
||||
if err := syscall.Exec(fshim, []string{"fshim"}, []string{envShim + "=" + shimSetupFd}); err != nil {
|
||||
log.Fatalf("cannot start shim: %v", err)
|
||||
}
|
||||
|
||||
|
@ -9,7 +9,7 @@ import (
|
||||
"path"
|
||||
"strconv"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
type payloadU struct {
|
||||
|
@ -9,7 +9,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
)
|
||||
|
||||
func TestConfig_Args(t *testing.T) {
|
||||
|
@ -5,8 +5,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
)
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
|
@ -6,8 +6,8 @@ import (
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
)
|
||||
|
||||
// ProxyName is the file name or path to the proxy program.
|
||||
|
@ -9,9 +9,9 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/ldd"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/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.ophivana.moe/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
)
|
||||
|
||||
var samples = []dbusTestCase{
|
||||
|
@ -3,7 +3,7 @@ package dbus_test
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
)
|
||||
|
||||
func TestHelperChildStub(t *testing.T) {
|
||||
|
6
dist/release.sh
vendored
6
dist/release.sh
vendored
@ -8,9 +8,9 @@ mkdir -p "${out}"
|
||||
cp "README.md" "dist/fsurc.default" "dist/install.sh" "${out}"
|
||||
|
||||
go build -v -o "${out}/bin/" -ldflags "-s -w
|
||||
-X git.ophivana.moe/security/fortify/internal.Version=${VERSION}
|
||||
-X git.ophivana.moe/security/fortify/internal.Fsu=/usr/bin/fsu
|
||||
-X git.ophivana.moe/security/fortify/internal.Finit=/usr/libexec/fortify/finit
|
||||
-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" ./...
|
||||
|
||||
|
4
error.go
4
error.go
@ -3,8 +3,8 @@ package main
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/app"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/app"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
func logWaitError(err error) {
|
||||
|
22
flake.nix
22
flake.nix
@ -74,7 +74,7 @@
|
||||
touch $out
|
||||
'';
|
||||
|
||||
nixos-tests = callPackage ./test.nix { inherit self home-manager; };
|
||||
nixos-tests = callPackage ./test.nix { inherit system self home-manager; };
|
||||
}
|
||||
);
|
||||
|
||||
@ -95,6 +95,26 @@
|
||||
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"
|
||||
'';
|
||||
};
|
||||
|
||||
withPackage = nixpkgsFor.${system}.mkShell {
|
||||
buildInputs =
|
||||
with nixpkgsFor.${system};
|
||||
|
@ -1,12 +1,12 @@
|
||||
package app
|
||||
package fst
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal/linux"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"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"
|
||||
)
|
||||
|
||||
const fTmp = "/fortify"
|
48
fst/id.go
Normal file
48
fst/id.go
Normal file
@ -0,0 +1,48 @@
|
||||
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
|
||||
}
|
63
fst/id_test.go
Normal file
63
fst/id_test.go
Normal file
@ -0,0 +1,63 @@
|
||||
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)
|
||||
}
|
||||
}
|
2
fst/shared.go
Normal file
2
fst/shared.go
Normal file
@ -0,0 +1,2 @@
|
||||
// Package fst exports shared fortify types.
|
||||
package fst
|
2
go.mod
2
go.mod
@ -1,3 +1,3 @@
|
||||
module git.ophivana.moe/security/fortify
|
||||
module git.gensokyo.uk/security/fortify
|
||||
|
||||
go 1.22
|
||||
|
@ -6,7 +6,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
)
|
||||
|
||||
func Test_argsFD_String(t *testing.T) {
|
||||
|
@ -8,8 +8,8 @@ import (
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal/proc"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/internal/proc"
|
||||
)
|
||||
|
||||
// BubblewrapName is the file name or path to bubblewrap.
|
||||
|
@ -7,8 +7,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
)
|
||||
|
||||
func TestBwrap(t *testing.T) {
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
)
|
||||
|
||||
func TestDirect(t *testing.T) {
|
||||
|
@ -6,7 +6,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
)
|
||||
|
||||
var (
|
||||
|
@ -6,7 +6,7 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/proc"
|
||||
"git.gensokyo.uk/security/fortify/internal/proc"
|
||||
)
|
||||
|
||||
type pipes struct {
|
||||
|
@ -10,8 +10,8 @@ import (
|
||||
"syscall"
|
||||
"testing"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/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.ophivana.moe/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
)
|
||||
|
||||
func TestHelperChildStub(t *testing.T) {
|
||||
|
@ -2,14 +2,16 @@ package app
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"git.ophivana.moe/security/fortify/cmd/fshim/ipc/shim"
|
||||
"git.ophivana.moe/security/fortify/internal/linux"
|
||||
"git.gensokyo.uk/security/fortify/cmd/fshim/ipc/shim"
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
)
|
||||
|
||||
type App interface {
|
||||
// ID returns a copy of App's unique ID.
|
||||
ID() ID
|
||||
ID() fst.ID
|
||||
// Start sets up the system and starts the App.
|
||||
Start() error
|
||||
// Wait waits for App's process to exit and reverts system setup.
|
||||
@ -17,13 +19,16 @@ type App interface {
|
||||
// WaitErr returns error returned by the underlying wait syscall.
|
||||
WaitErr() error
|
||||
|
||||
Seal(config *Config) error
|
||||
Seal(config *fst.Config) error
|
||||
String() string
|
||||
}
|
||||
|
||||
type app struct {
|
||||
// single-use config reference
|
||||
ct *appCt
|
||||
|
||||
// application unique identifier
|
||||
id *ID
|
||||
id *fst.ID
|
||||
// operating system interface
|
||||
os linux.System
|
||||
// shim process manager
|
||||
@ -36,7 +41,7 @@ type app struct {
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
func (a *app) ID() ID {
|
||||
func (a *app) ID() fst.ID {
|
||||
return *a.id
|
||||
}
|
||||
|
||||
@ -65,7 +70,28 @@ func (a *app) WaitErr() error {
|
||||
|
||||
func New(os linux.System) (App, error) {
|
||||
a := new(app)
|
||||
a.id = new(ID)
|
||||
a.id = new(fst.ID)
|
||||
a.os = os
|
||||
return a, newAppID(a.id)
|
||||
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
|
||||
}
|
||||
|
@ -1,25 +1,25 @@
|
||||
package app_test
|
||||
|
||||
import (
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal/app"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"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 testCasesNixos = []sealTestCase{
|
||||
{
|
||||
"nixos chromium direct wayland", new(stubNixOS),
|
||||
&app.Config{
|
||||
&fst.Config{
|
||||
ID: "org.chromium.Chromium",
|
||||
Command: []string{"/nix/store/yqivzpzzn7z5x0lq9hmbzygh45d8rhqd-chromium-start"},
|
||||
Confinement: app.ConfinementConfig{
|
||||
Confinement: fst.ConfinementConfig{
|
||||
AppID: 1, Groups: []string{}, Username: "u0_a1",
|
||||
Outer: "/var/lib/persist/module/fortify/0/1",
|
||||
Sandbox: &app.SandboxConfig{
|
||||
Sandbox: &fst.SandboxConfig{
|
||||
UserNS: true, Net: true, MapRealUID: true, DirectWayland: true, Env: nil,
|
||||
Filesystem: []*app.FilesystemConfig{
|
||||
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"},
|
||||
@ -48,7 +48,7 @@ var testCasesNixos = []sealTestCase{
|
||||
Enablements: system.EWayland.Mask() | system.EDBus.Mask() | system.EPulse.Mask(),
|
||||
},
|
||||
},
|
||||
app.ID{
|
||||
fst.ID{
|
||||
0x8e, 0x2c, 0x76, 0xb0,
|
||||
0x66, 0xda, 0xbe, 0x57,
|
||||
0x4c, 0xf0, 0x73, 0xbd,
|
||||
|
@ -1,25 +1,25 @@
|
||||
package app_test
|
||||
|
||||
import (
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal/app"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"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),
|
||||
&app.Config{
|
||||
&fst.Config{
|
||||
Command: make([]string, 0),
|
||||
Confinement: app.ConfinementConfig{
|
||||
Confinement: fst.ConfinementConfig{
|
||||
AppID: 0,
|
||||
Username: "chronos",
|
||||
Outer: "/home/chronos",
|
||||
},
|
||||
},
|
||||
app.ID{
|
||||
fst.ID{
|
||||
0x4a, 0x45, 0x0b, 0x65,
|
||||
0x96, 0xd7, 0xbc, 0x15,
|
||||
0xbd, 0x01, 0x78, 0x0e,
|
||||
@ -190,10 +190,10 @@ var testCasesPd = []sealTestCase{
|
||||
},
|
||||
{
|
||||
"nixos permissive defaults chromium", new(stubNixOS),
|
||||
&app.Config{
|
||||
&fst.Config{
|
||||
ID: "org.chromium.Chromium",
|
||||
Command: []string{"/run/current-system/sw/bin/zsh", "-c", "exec chromium "},
|
||||
Confinement: app.ConfinementConfig{
|
||||
Confinement: fst.ConfinementConfig{
|
||||
AppID: 9,
|
||||
Groups: []string{"video"},
|
||||
Username: "chronos",
|
||||
@ -232,7 +232,7 @@ var testCasesPd = []sealTestCase{
|
||||
Enablements: system.EWayland.Mask() | system.EDBus.Mask() | system.EPulse.Mask(),
|
||||
},
|
||||
},
|
||||
app.ID{
|
||||
fst.ID{
|
||||
0xeb, 0xf0, 0x83, 0xd1,
|
||||
0xb1, 0x75, 0x91, 0x17,
|
||||
0x82, 0xd4, 0x13, 0x36,
|
||||
|
@ -7,7 +7,7 @@ import (
|
||||
"os/user"
|
||||
"strconv"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/linux"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
)
|
||||
|
||||
// fs methods are not implemented using a real FS
|
||||
|
@ -6,17 +6,18 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal/app"
|
||||
"git.ophivana.moe/security/fortify/internal/linux"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"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"
|
||||
)
|
||||
|
||||
type sealTestCase struct {
|
||||
name string
|
||||
os linux.System
|
||||
config *app.Config
|
||||
id app.ID
|
||||
config *fst.Config
|
||||
id fst.ID
|
||||
wantSys *system.I
|
||||
wantBwrap *bwrap.Config
|
||||
}
|
||||
|
@ -1,12 +1,13 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal/linux"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"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"
|
||||
)
|
||||
|
||||
func NewWithID(id ID, os linux.System) App {
|
||||
func NewWithID(id fst.ID, os linux.System) App {
|
||||
a := new(app)
|
||||
a.id = &id
|
||||
a.os = os
|
||||
|
@ -1,17 +0,0 @@
|
||||
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
|
||||
}
|
@ -8,11 +8,12 @@ import (
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/linux"
|
||||
"git.ophivana.moe/security/fortify/internal/state"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"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"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -59,7 +60,7 @@ type appSeal struct {
|
||||
}
|
||||
|
||||
// Seal seals the app launch context
|
||||
func (a *app) Seal(config *Config) error {
|
||||
func (a *app) Seal(config *fst.Config) error {
|
||||
a.lock.Lock()
|
||||
defer a.lock.Unlock()
|
||||
|
||||
@ -147,7 +148,7 @@ func (a *app) Seal(config *Config) error {
|
||||
fmsg.VPrintln("sandbox configuration not supplied, PROCEED WITH CAUTION")
|
||||
|
||||
// permissive defaults
|
||||
conf := &SandboxConfig{
|
||||
conf := &fst.SandboxConfig{
|
||||
UserNS: true,
|
||||
Net: true,
|
||||
NoNewSession: true,
|
||||
@ -157,7 +158,7 @@ func (a *app) Seal(config *Config) error {
|
||||
if d, err := a.os.ReadDir("/"); err != nil {
|
||||
return err
|
||||
} else {
|
||||
b := make([]*FilesystemConfig, 0, len(d))
|
||||
b := make([]*fst.FilesystemConfig, 0, len(d))
|
||||
for _, ent := range d {
|
||||
p := "/" + ent.Name()
|
||||
switch p {
|
||||
@ -169,7 +170,7 @@ func (a *app) Seal(config *Config) error {
|
||||
case "/etc":
|
||||
|
||||
default:
|
||||
b = append(b, &FilesystemConfig{Src: p, Write: true, Must: true})
|
||||
b = append(b, &fst.FilesystemConfig{Src: p, Write: true, Must: true})
|
||||
}
|
||||
}
|
||||
conf.Filesystem = append(conf.Filesystem, b...)
|
||||
@ -178,7 +179,7 @@ func (a *app) Seal(config *Config) error {
|
||||
if d, err := a.os.ReadDir("/run"); err != nil {
|
||||
return err
|
||||
} else {
|
||||
b := make([]*FilesystemConfig, 0, len(d))
|
||||
b := make([]*fst.FilesystemConfig, 0, len(d))
|
||||
for _, ent := range d {
|
||||
name := ent.Name()
|
||||
switch name {
|
||||
@ -186,7 +187,7 @@ func (a *app) Seal(config *Config) error {
|
||||
case "dbus":
|
||||
default:
|
||||
p := "/run/" + name
|
||||
b = append(b, &FilesystemConfig{Src: p, Write: true, Must: true})
|
||||
b = append(b, &fst.FilesystemConfig{Src: p, Write: true, Must: true})
|
||||
}
|
||||
}
|
||||
conf.Filesystem = append(conf.Filesystem, b...)
|
||||
@ -198,7 +199,7 @@ func (a *app) Seal(config *Config) error {
|
||||
}
|
||||
// bind GPU stuff
|
||||
if config.Confinement.Enablements.Has(system.EX11) || config.Confinement.Enablements.Has(system.EWayland) {
|
||||
conf.Filesystem = append(conf.Filesystem, &FilesystemConfig{Src: "/dev/dri", Device: true})
|
||||
conf.Filesystem = append(conf.Filesystem, &fst.FilesystemConfig{Src: "/dev/dri", Device: true})
|
||||
}
|
||||
|
||||
config.Confinement.Sandbox = conf
|
||||
@ -217,7 +218,7 @@ func (a *app) Seal(config *Config) error {
|
||||
// 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.NewSimple(seal.RunDirPath, seal.sys.user.as)
|
||||
seal.store = state.NewMulti(seal.RunDirPath)
|
||||
|
||||
// initialise system interface with full uid
|
||||
seal.sys.I = system.New(seal.sys.user.uid)
|
||||
@ -236,5 +237,6 @@ func (a *app) Seal(config *Config) error {
|
||||
|
||||
// seal app and release lock
|
||||
a.seal = seal
|
||||
a.ct = newAppCt(config)
|
||||
return nil
|
||||
}
|
||||
|
@ -3,9 +3,9 @@ package app
|
||||
import (
|
||||
"path"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -4,10 +4,10 @@ import (
|
||||
"errors"
|
||||
"path"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/linux"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"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"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -6,9 +6,9 @@ import (
|
||||
"io/fs"
|
||||
"path"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/linux"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -3,8 +3,8 @@ package app
|
||||
import (
|
||||
"path"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -3,9 +3,9 @@ package app
|
||||
import (
|
||||
"path"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/internal/linux"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/internal/linux"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -4,16 +4,15 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
shim0 "git.ophivana.moe/security/fortify/cmd/fshim/ipc"
|
||||
"git.ophivana.moe/security/fortify/cmd/fshim/ipc/shim"
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/state"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
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"
|
||||
)
|
||||
|
||||
// Start selects a user switcher and starts shim.
|
||||
@ -46,7 +45,6 @@ func (a *app) Start() error {
|
||||
uint32(a.seal.sys.UID()),
|
||||
a.seal.sys.user.as,
|
||||
a.seal.sys.user.supp,
|
||||
path.Join(a.seal.share, "shim"),
|
||||
&shim0.Payload{
|
||||
Argv: a.seal.command,
|
||||
Exec: shimExec,
|
||||
@ -70,17 +68,16 @@ func (a *app) Start() error {
|
||||
} else {
|
||||
// shim start and setup success, create process state
|
||||
sd := state.State{
|
||||
PID: a.shim.Unwrap().Process.Pid,
|
||||
Command: a.seal.command,
|
||||
Capability: a.seal.et,
|
||||
Argv: a.shim.Unwrap().Args,
|
||||
Time: *startTime,
|
||||
ID: *a.id,
|
||||
PID: a.shim.Unwrap().Process.Pid,
|
||||
Config: a.ct.Unwrap(),
|
||||
Time: *startTime,
|
||||
}
|
||||
|
||||
// register process state
|
||||
var err0 = new(StateStoreError)
|
||||
err0.Inner, err0.DoErr = a.seal.store.Do(func(b state.Backend) {
|
||||
err0.InnerErr = b.Save(&sd)
|
||||
err0.Inner, err0.DoErr = a.seal.store.Do(a.seal.sys.user.aid, func(c state.Cursor) {
|
||||
err0.InnerErr = c.Save(&sd)
|
||||
})
|
||||
a.seal.sys.saveState = true
|
||||
return err0.equiv("cannot save process state:")
|
||||
@ -202,11 +199,11 @@ func (a *app) Wait() (int, error) {
|
||||
|
||||
// update store and revert app setup transaction
|
||||
e := new(StateStoreError)
|
||||
e.Inner, e.DoErr = a.seal.store.Do(func(b state.Backend) {
|
||||
e.Inner, e.DoErr = a.seal.store.Do(a.seal.sys.user.aid, func(b state.Cursor) {
|
||||
e.InnerErr = func() error {
|
||||
// destroy defunct state entry
|
||||
if cmd := a.shim.Unwrap(); cmd != nil && a.seal.sys.saveState {
|
||||
if err := b.Destroy(cmd.Process.Pid); err != nil {
|
||||
if err := b.Destroy(*a.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@ -227,8 +224,12 @@ func (a *app) Wait() (int, error) {
|
||||
}
|
||||
|
||||
// accumulate capabilities of other launchers
|
||||
for _, s := range states {
|
||||
*rt |= s.Capability
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
// invert accumulated enablements for cleanup
|
||||
@ -249,12 +250,6 @@ func (a *app) Wait() (int, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if a.shim.Unwrap() == nil {
|
||||
fmsg.VPrintln("fault before shim start")
|
||||
} else {
|
||||
a.shim.AbortWait(errors.New("shim exited"))
|
||||
}
|
||||
|
||||
if a.seal.sys.needRevert {
|
||||
if err := a.seal.sys.Revert(ec); err != nil {
|
||||
return err.(RevertCompoundError)
|
||||
|
@ -1,10 +1,10 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.ophivana.moe/security/fortify/internal/linux"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"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"
|
||||
)
|
||||
|
||||
// appSealSys encapsulates app seal behaviour with OS interactions
|
||||
|
@ -7,7 +7,7 @@ import (
|
||||
"path"
|
||||
"strconv"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// System provides safe access to operating system resources.
|
||||
@ -39,8 +39,6 @@ type System interface {
|
||||
Paths() Paths
|
||||
// Uid invokes fsu and returns target uid.
|
||||
Uid(aid int) (int, error)
|
||||
// SdBooted implements https://www.freedesktop.org/software/systemd/man/sd_booted.html
|
||||
SdBooted() bool
|
||||
}
|
||||
|
||||
// Paths contains environment dependent paths used by fortify.
|
||||
|
@ -1,7 +1,6 @@
|
||||
package linux
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
@ -10,8 +9,8 @@ import (
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// Std implements System using the standard library.
|
||||
@ -19,9 +18,6 @@ type Std struct {
|
||||
paths Paths
|
||||
pathsOnce sync.Once
|
||||
|
||||
sdBooted bool
|
||||
sdBootedOnce sync.Once
|
||||
|
||||
uidOnce sync.Once
|
||||
uidCopy map[int]struct {
|
||||
uid int
|
||||
@ -90,31 +86,3 @@ func (s *Std) Uid(aid int) (int, error) {
|
||||
return u.uid, u.err
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Std) SdBooted() bool {
|
||||
s.sdBootedOnce.Do(func() { s.sdBooted = copySdBooted() })
|
||||
return s.sdBooted
|
||||
}
|
||||
|
||||
const systemdCheckPath = "/run/systemd/system"
|
||||
|
||||
func copySdBooted() bool {
|
||||
if v, err := sdBooted(); err != nil {
|
||||
fmsg.Println("cannot read systemd marker:", err)
|
||||
return false
|
||||
} else {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
42
internal/proc/fd.go
Normal file
42
internal/proc/fd.go
Normal file
@ -0,0 +1,42 @@
|
||||
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)
|
||||
}
|
292
internal/state/multi.go
Normal file
292
internal/state/multi.go
Normal file
@ -0,0 +1,292 @@
|
||||
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
|
||||
}
|
11
internal/state/multi_test.go
Normal file
11
internal/state/multi_test.go
Normal file
@ -0,0 +1,11 @@
|
||||
package state_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.gensokyo.uk/security/fortify/internal/state"
|
||||
)
|
||||
|
||||
func TestMulti(t *testing.T) {
|
||||
testStore(t, state.NewMulti(t.TempDir()))
|
||||
}
|
@ -1,62 +1,45 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/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 dirs, err := os.ReadDir(path.Join(runDir, "state")); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
fmsg.Fatal("cannot read runtime directory:", err)
|
||||
if aids, err := s.List(); err != nil {
|
||||
fmsg.Fatal("cannot list store:", err)
|
||||
} else {
|
||||
for _, e := range dirs {
|
||||
// skip non-directories
|
||||
if !e.IsDir() {
|
||||
fmsg.VPrintf("skipped non-directory entry %q", e.Name())
|
||||
continue
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
for _, aid := range aids {
|
||||
// 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)
|
||||
}
|
||||
s.(*multiStore).mustPrintLauncherState(aid, w, now)
|
||||
}
|
||||
}
|
||||
|
||||
// mustPrintLauncherState causes store activity so store needs to be closed
|
||||
if err := s.Close(); err != nil {
|
||||
fmsg.Printf("cannot close store: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *simpleStore) mustPrintLauncherState(w **tabwriter.Writer, now time.Time) {
|
||||
func (s *multiStore) mustPrintLauncherState(aid int, w **tabwriter.Writer, now time.Time) {
|
||||
var innerErr error
|
||||
|
||||
if ok, err := s.Do(func(b Backend) {
|
||||
if ok, err := s.Do(aid, func(c Cursor) {
|
||||
innerErr = func() error {
|
||||
// read launcher states
|
||||
states, err := b.Load()
|
||||
states, err := c.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -82,40 +65,54 @@ func (s *simpleStore) mustPrintLauncherState(w **tabwriter.Writer, now time.Time
|
||||
continue
|
||||
}
|
||||
|
||||
// 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())
|
||||
// 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())
|
||||
}
|
||||
}
|
||||
|
||||
cs = fmt.Sprintf("%q", state.Config.Command)
|
||||
}
|
||||
// prevent an empty string when
|
||||
if ets.Len() == 0 {
|
||||
ets.WriteString("(No enablements)")
|
||||
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)")
|
||||
}
|
||||
|
||||
if !fmsg.Verbose() {
|
||||
_, _ = fmt.Fprintf(*w, "\t%d\t%s\t%s\t%s\t%s\n",
|
||||
state.PID, s.path[len(s.path)-1], now.Sub(state.Time).Round(time.Second).String(), strings.TrimPrefix(ets.String(), ", "),
|
||||
state.Command)
|
||||
_, _ = 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)
|
||||
} else {
|
||||
// emit argv instead when verbose
|
||||
_, _ = fmt.Fprintf(*w, "\t%d\t%s\t%s\n",
|
||||
state.PID, s.path[len(s.path)-1], state.Argv)
|
||||
_, _ = fmt.Fprintf(*w, "\t%d\t%d\t%s\n",
|
||||
state.PID, aid, state.ID)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}()
|
||||
}); err != nil {
|
||||
fmsg.Printf("cannot perform action on store %q: %s", path.Join(s.path...), err)
|
||||
fmsg.Printf("cannot perform action on app %d: %v", aid, err)
|
||||
if !ok {
|
||||
fmsg.Fatal("store faulted before printing")
|
||||
}
|
||||
}
|
||||
|
||||
if innerErr != nil {
|
||||
fmsg.Fatalf("cannot print launcher state for store %q: %s", path.Join(s.path...), innerErr)
|
||||
fmsg.Fatalf("cannot print launcher state of app %d: %s", aid, innerErr)
|
||||
}
|
||||
}
|
||||
|
@ -1,218 +0,0 @@
|
||||
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,38 +3,42 @@ package state
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
)
|
||||
|
||||
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.
|
||||
// Backend provided to f becomes invalid as soon as f returns.
|
||||
Do(f func(b Backend)) (bool, error)
|
||||
// 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)
|
||||
|
||||
// Close releases any resources held by Store.
|
||||
Close() error
|
||||
}
|
||||
|
||||
// Backend provides access to the store
|
||||
type Backend interface {
|
||||
// Cursor provides access to the store
|
||||
type Cursor interface {
|
||||
Save(state *State) error
|
||||
Destroy(pid int) error
|
||||
Load() ([]*State, error)
|
||||
Destroy(id fst.ID) error
|
||||
Load() (Entries, 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
|
||||
// command used to seal the app
|
||||
Command []string
|
||||
// capability enablements applied to child
|
||||
Capability system.Enablements
|
||||
PID int `json:"pid"`
|
||||
// sealed app configuration
|
||||
Config *fst.Config `json:"config"`
|
||||
|
||||
// full argv whe launching
|
||||
Argv []string
|
||||
// process start time
|
||||
Time time.Time
|
||||
}
|
||||
|
126
internal/state/state_test.go
Normal file
126
internal/state/state_test.go
Normal file
@ -0,0 +1,126 @@
|
||||
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()
|
||||
}
|
@ -4,8 +4,8 @@ import (
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// UpdatePerm appends an ephemeral acl update Op.
|
||||
|
@ -3,7 +3,7 @@ package system
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
)
|
||||
|
||||
func TestUpdatePerm(t *testing.T) {
|
||||
|
@ -7,8 +7,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.ophivana.moe/security/fortify/dbus"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
var (
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// Ensure the existence and mode of a directory.
|
||||
|
@ -5,7 +5,7 @@ import (
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
const (
|
||||
|
@ -4,7 +4,7 @@ import (
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"git.gensokyo.uk/security/fortify/internal/system"
|
||||
)
|
||||
|
||||
func TestNew(t *testing.T) {
|
||||
|
@ -7,8 +7,8 @@ import (
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
)
|
||||
|
||||
// CopyFile registers an Op that copies path dst from src.
|
||||
|
@ -4,7 +4,7 @@ import (
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.gensokyo.uk/security/fortify/acl"
|
||||
)
|
||||
|
||||
func TestCopyFile(t *testing.T) {
|
||||
|
@ -5,9 +5,9 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.ophivana.moe/security/fortify/acl"
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/wl"
|
||||
"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.
|
||||
|
@ -3,8 +3,8 @@ package system
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.ophivana.moe/security/fortify/internal/fmsg"
|
||||
"git.ophivana.moe/security/fortify/xcb"
|
||||
"git.gensokyo.uk/security/fortify/internal/fmsg"
|
||||
"git.gensokyo.uk/security/fortify/xcb"
|
||||
)
|
||||
|
||||
// ChangeHosts appends an X11 ChangeHosts command Op.
|
||||
|
@ -6,8 +6,8 @@ import (
|
||||
"os/exec"
|
||||
"strings"
|
||||
|
||||
"git.ophivana.moe/security/fortify/helper"
|
||||
"git.ophivana.moe/security/fortify/helper/bwrap"
|
||||
"git.gensokyo.uk/security/fortify/helper"
|
||||
"git.gensokyo.uk/security/fortify/helper/bwrap"
|
||||
)
|
||||
|
||||
func Exec(p string) ([]*Entry, error) {
|
||||
|
@ -6,7 +6,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.ophivana.moe/security/fortify/ldd"
|
||||
"git.gensokyo.uk/security/fortify/ldd"
|
||||
)
|
||||
|
||||
func TestParseError(t *testing.T) {
|
||||
|
27
main.go
27
main.go
@ -11,13 +11,14 @@ import (
|
||||
"sync"
|
||||
"text/tabwriter"
|
||||
|
||||
"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/linux"
|
||||
"git.ophivana.moe/security/fortify/internal/state"
|
||||
"git.ophivana.moe/security/fortify/internal/system"
|
||||
"git.gensokyo.uk/security/fortify/dbus"
|
||||
"git.gensokyo.uk/security/fortify/fst"
|
||||
"git.gensokyo.uk/security/fortify/internal"
|
||||
"git.gensokyo.uk/security/fortify/internal/app"
|
||||
"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"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -102,7 +103,7 @@ func main() {
|
||||
fmt.Println(license)
|
||||
fmsg.Exit(0)
|
||||
case "template": // print full template configuration
|
||||
if s, err := json.MarshalIndent(app.Template(), "", " "); err != nil {
|
||||
if s, err := json.MarshalIndent(fst.Template(), "", " "); err != nil {
|
||||
fmsg.Fatalf("cannot generate template: %v", err)
|
||||
panic("unreachable")
|
||||
} else {
|
||||
@ -129,7 +130,7 @@ func main() {
|
||||
fmsg.Fatal("app requires at least 1 argument")
|
||||
}
|
||||
|
||||
config := new(app.Config)
|
||||
config := new(fst.Config)
|
||||
if f, err := os.Open(args[1]); err != nil {
|
||||
fmsg.Fatalf("cannot access config file %q: %s", args[1], err)
|
||||
panic("unreachable")
|
||||
@ -179,7 +180,7 @@ func main() {
|
||||
_ = set.Parse(args[1:])
|
||||
|
||||
// initialise config from flags
|
||||
config := &app.Config{
|
||||
config := &fst.Config{
|
||||
ID: fid,
|
||||
Command: set.Args(),
|
||||
}
|
||||
@ -275,11 +276,7 @@ func main() {
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
func runApp(config *app.Config) {
|
||||
if os.SdBooted() {
|
||||
fmsg.VPrintln("system booted with systemd as init system")
|
||||
}
|
||||
|
||||
func runApp(config *fst.Config) {
|
||||
a, err := app.New(os)
|
||||
if err != nil {
|
||||
fmsg.Fatalf("cannot create app: %s\n", err)
|
||||
|
@ -36,7 +36,7 @@ package
|
||||
|
||||
|
||||
*Default:*
|
||||
` <derivation fortify-0.2.1> `
|
||||
` <derivation fortify-0.2.5> `
|
||||
|
||||
|
||||
|
||||
|
@ -14,7 +14,7 @@
|
||||
|
||||
buildGoModule rec {
|
||||
pname = "fortify";
|
||||
version = "0.2.3";
|
||||
version = "0.2.5";
|
||||
|
||||
src = ./.;
|
||||
vendorHash = null;
|
||||
@ -26,7 +26,7 @@ buildGoModule rec {
|
||||
ldflags
|
||||
++ [
|
||||
"-X"
|
||||
"git.ophivana.moe/security/fortify/internal.${name}=${value}"
|
||||
"git.gensokyo.uk/security/fortify/internal.${name}=${value}"
|
||||
]
|
||||
)
|
||||
[
|
||||
|
42
test.nix
42
test.nix
@ -1,4 +1,5 @@
|
||||
{
|
||||
system,
|
||||
self,
|
||||
home-manager,
|
||||
nixosTest,
|
||||
@ -31,11 +32,14 @@ nixosTest {
|
||||
services.getty.autologinUser = "alice";
|
||||
|
||||
environment = {
|
||||
# For glinfo and wayland-info:
|
||||
systemPackages = with pkgs; [
|
||||
# For glinfo and wayland-info:
|
||||
mesa-demos
|
||||
wayland-utils
|
||||
alacritty
|
||||
|
||||
# For go tests:
|
||||
self.devShells.${system}.fhs
|
||||
];
|
||||
|
||||
variables = {
|
||||
@ -73,8 +77,13 @@ nixosTest {
|
||||
|
||||
programs.sway.enable = true;
|
||||
|
||||
# Need to switch to a different GPU driver than the default one (-vga std) so that Sway can launch:
|
||||
virtualisation.qemu.options = [ "-vga none -device virtio-gpu-pci" ];
|
||||
virtualisation.qemu.options = [
|
||||
# Need to switch to a different GPU driver than the default one (-vga std) so that Sway can launch:
|
||||
"-vga none -device virtio-gpu-pci"
|
||||
|
||||
# Increase Go test compiler performance:
|
||||
"-smp 8"
|
||||
];
|
||||
|
||||
environment.fortify = {
|
||||
enable = true;
|
||||
@ -136,10 +145,19 @@ nixosTest {
|
||||
|
||||
retry(func)
|
||||
|
||||
def collect_state_ui(name):
|
||||
swaymsg(f"exec fortify ps > '/tmp/{name}.ps'")
|
||||
machine.copy_from_vm(f"/tmp/{name}.ps", "")
|
||||
machine.screenshot(name)
|
||||
|
||||
start_all()
|
||||
machine.wait_for_unit("multi-user.target")
|
||||
|
||||
# To check the version:
|
||||
# Run fortify Go tests outside of nix build:
|
||||
machine.succeed("rm -rf /tmp/src && cp -a '${self.packages.${system}.fortify.src}' /tmp/src")
|
||||
print(machine.succeed("fortify-fhs -c '(cd /tmp/src && go generate ./... && go test ./...)'"))
|
||||
|
||||
# To check sway's version:
|
||||
print(machine.succeed("sway --version"))
|
||||
|
||||
# Wait for Sway to complete startup:
|
||||
@ -164,9 +182,13 @@ nixosTest {
|
||||
wait_for_window("u0_a0@machine")
|
||||
machine.send_chars("wayland-info && touch /tmp/success-client\n")
|
||||
machine.wait_for_file("/tmp/fortify.1000/tmpdir/0/success-client")
|
||||
machine.screenshot("foot_wayland_permissive")
|
||||
collect_state_ui("foot_wayland_permissive")
|
||||
# Verify acl on XDG_RUNTIME_DIR:
|
||||
print(machine.succeed("getfacl --absolute-names --omit-header --numeric /run/user/1000 | grep 1000000"))
|
||||
machine.send_chars("exit\n")
|
||||
machine.wait_until_fails("pgrep foot")
|
||||
# Verify acl cleanup on XDG_RUNTIME_DIR:
|
||||
machine.wait_until_fails("getfacl --absolute-names --omit-header --numeric /run/user/1000 | grep 1000000")
|
||||
|
||||
# Start a terminal (foot) within fortify from a terminal on workspace 4:
|
||||
machine.send_key("alt-4")
|
||||
@ -175,7 +197,7 @@ nixosTest {
|
||||
wait_for_window("u0_a0@machine")
|
||||
machine.send_chars("wayland-info && touch /tmp/success-client-term\n")
|
||||
machine.wait_for_file("/tmp/fortify.1000/tmpdir/0/success-client-term")
|
||||
machine.screenshot("foot_wayland_permissive_term")
|
||||
collect_state_ui("foot_wayland_permissive_term")
|
||||
machine.send_chars("exit\n")
|
||||
machine.wait_until_fails("pgrep foot")
|
||||
|
||||
@ -184,12 +206,16 @@ nixosTest {
|
||||
wait_for_window("u0_a0@machine")
|
||||
machine.send_chars("glinfo && touch /tmp/success-client-x11\n")
|
||||
machine.wait_for_file("/tmp/fortify.1000/tmpdir/0/success-client-x11")
|
||||
machine.screenshot("alacritty_x11_permissive")
|
||||
machine.succeed("pkill alacritty")
|
||||
collect_state_ui("alacritty_x11_permissive")
|
||||
machine.send_chars("exit\n")
|
||||
machine.wait_until_fails("pgrep alacritty")
|
||||
|
||||
# Exit Sway and verify process exit status 0:
|
||||
swaymsg("exit", succeed=False)
|
||||
machine.wait_until_fails("pgrep -x sway")
|
||||
machine.wait_for_file("/tmp/sway-exit-ok")
|
||||
|
||||
# Print fortify runDir contents:
|
||||
print(machine.succeed("find /run/user/1000/fortify"))
|
||||
'';
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user