Compare commits

..

16 Commits

Author SHA1 Message Date
9f95f60400
release: 0.2.4
All checks were successful
Tests / Go tests (push) Successful in 52s
Create distribution / Release (push) Successful in 1m9s
Nix / NixOS tests (push) Successful in 1m23s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 23:52:52 +09:00
90dd57f75d
workflows: cache nix store
All checks were successful
Tests / Go tests (push) Successful in 45s
Nix / NixOS tests (push) Successful in 1m11s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 23:38:39 +09:00
141f2e3685
workflows: cache apt packages
All checks were successful
Tests / Go tests (push) Successful in 36s
Nix / NixOS tests (push) Successful in 5m43s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 23:05:28 +09:00
73aa285e8f
workflows: upload nixos test output
All checks were successful
Tests / Go tests (push) Successful in 44s
Nix / NixOS tests (push) Successful in 5m45s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 20:32:40 +09:00
6e87fc02dd
workflows: build and upload test distribution
All checks were successful
Tests / Go tests (push) Successful in 43s
Nix / NixOS tests (push) Successful in 5m33s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 20:28:35 +09:00
52f21a19f3
cmd/fshim: switch to setup pipe
All checks were successful
Tests / Go tests (push) Successful in 38s
Nix / NixOS tests (push) Successful in 5m43s
The socket-based approach is no longer necessary as fsu allows extra files and sudo compatibility is no longer relevant.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 19:39:25 +09:00
7be53a2438
cmd/fshim: switch to generic setup func
All checks were successful
Tests / Go tests (push) Successful in 38s
Nix / NixOS tests (push) Successful in 5m47s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 17:20:31 +09:00
7f29b37a32
proc: setup payload send
Generic setup payload encoder adapted from fshim.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 17:20:01 +09:00
f69e8e753e
cmd/finit: switch to generic receive func
All checks were successful
Tests / Go tests (push) Successful in 38s
Nix / NixOS tests (push) Successful in 5m40s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 16:49:19 +09:00
ef8fd37e9d
proc: setup payload receive
Generic implementation of setup payload receiver adapted from finit.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 16:48:41 +09:00
2f676c9d6e
fst: rename from fipc
All checks were successful
Tests / Go tests (push) Successful in 38s
Nix / NixOS tests (push) Successful in 5m48s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 15:50:46 +09:00
bbace8f84b
nix: increase cpu count
All checks were successful
Tests / Go tests (push) Successful in 38s
Nix / NixOS tests (push) Successful in 5m41s
This improves performance, especially when kvm is inaccessible.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 15:32:52 +09:00
2efedf56c0
nix: collect fortify ps output
All checks were successful
Tests / Go tests (push) Successful in 38s
Nix / NixOS tests (push) Successful in 10m38s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 13:48:39 +09:00
b752ec4468
fipc: export config struct
All checks were successful
Tests / Go tests (push) Successful in 1m12s
Nix / NixOS tests (push) Successful in 10m51s
Also store full config as part of state.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 13:45:55 +09:00
5d00805a7c
nix: check acl rollback
All checks were successful
Tests / Go tests (push) Successful in 1m1s
Nix / NixOS tests (push) Successful in 10m32s
Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-18 12:49:32 +09:00
7b6052a473
nix: run Go tests in nixos
All checks were successful
Tests / Go tests (push) Successful in 41s
Nix / NixOS tests (push) Successful in 9m56s
Nix build environment does not support ACLs in any filesystem. This allows acl tests to run.

Signed-off-by: Ophestra Umiker <cat@ophivana.moe>
2024-12-17 21:16:55 +09:00
25 changed files with 331 additions and 331 deletions

View File

@ -22,5 +22,25 @@ jobs:
system-features = nixos-test benchmark big-parallel kvm system-features = nixos-test benchmark big-parallel kvm
enable_kvm: true 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 - 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

View File

@ -11,19 +11,22 @@ jobs:
container: container:
image: node:16-bookworm-slim image: node:16-bookworm-slim
steps: steps:
- name: Get dependencies - name: Enable backports
run: >- run: >-
echo 'deb http://deb.debian.org/debian bookworm-backports main' >> /etc/apt/sources.list.d/backports.list && echo 'deb http://deb.debian.org/debian bookworm-backports main' >> /etc/apt/sources.list.d/backports.list
apt-get update && if: ${{ runner.os == 'Linux' }}
apt-get install -y
acl - name: Ensure environment
git run: >-
gcc apt-get update && apt-get install -y curl wget sudo libxml2
pkg-config if: ${{ runner.os == 'Linux' }}
libwayland-dev
wayland-protocols/bookworm-backports - name: Get dependencies
libxcb1-dev uses: awalsh128/cache-apt-pkgs-action@latest
libacl1-dev 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' }} if: ${{ runner.os == 'Linux' }}
- name: Checkout - name: Checkout
@ -44,13 +47,16 @@ jobs:
run: >- run: >-
go test ./... go test ./...
- name: Build for Linux - name: Build for test
id: build-test
run: >- run: >-
go build -v -ldflags '-s -w FORTIFY_VERSION="$(git rev-parse --short HEAD)"
-X git.ophivana.moe/security/fortify/internal.Version=${{ github.ref_name }} bash -c './dist/release.sh &&
-X git.ophivana.moe/security/fortify/internal.Fsu=/usr/bin/fsu echo "rev=$FORTIFY_VERSION" >> $GITHUB_OUTPUT'
-X git.ophivana.moe/security/fortify/internal.Finit=/usr/libexec/fortify/finit
-X main.Fmain=/usr/bin/fortify - name: Upload test build
-X main.Fshim=/usr/libexec/fortify/fshim' uses: actions/upload-artifact@v3
-o bin/ ./... && with:
(cd bin && sha512sum --tag -b * > sha512sums) name: "fortify-${{ steps.build-test.outputs.rev }}"
path: dist/fortify-*
retention-days: 1

View File

@ -1,19 +1,18 @@
package main package main
import ( import (
"encoding/gob"
"errors" "errors"
"os" "os"
"os/exec" "os/exec"
"os/signal" "os/signal"
"path" "path"
"strconv"
"syscall" "syscall"
"time" "time"
init0 "git.ophivana.moe/security/fortify/cmd/finit/ipc" init0 "git.ophivana.moe/security/fortify/cmd/finit/ipc"
"git.ophivana.moe/security/fortify/internal" "git.ophivana.moe/security/fortify/internal"
"git.ophivana.moe/security/fortify/internal/fmsg" "git.ophivana.moe/security/fortify/internal/fmsg"
"git.ophivana.moe/security/fortify/internal/proc"
) )
const ( const (
@ -48,30 +47,24 @@ func main() {
} }
} }
// setup pipe fd from environment // receive setup payload
var setup *os.File var (
if s, ok := os.LookupEnv(init0.Env); !ok { payload init0.Payload
fmsg.Fatal("FORTIFY_INIT not set") closeSetup func() error
panic("unreachable") )
} else { if f, err := proc.Receive(init0.Env, &payload); err != nil {
if fd, err := strconv.Atoi(s); err != nil { if errors.Is(err, proc.ErrInvalid) {
fmsg.Fatalf("cannot parse %q: %v", s, err) fmsg.Fatal("invalid config descriptor")
panic("unreachable") }
} else { if errors.Is(err, proc.ErrNotSet) {
setup = os.NewFile(uintptr(fd), "setup") fmsg.Fatal("FORTIFY_INIT not set")
if setup == nil {
fmsg.Fatal("invalid config descriptor")
panic("unreachable")
}
} }
}
var payload init0.Payload fmsg.Fatalf("cannot decode init setup payload: %v", err)
if err := gob.NewDecoder(setup).Decode(&payload); err != nil {
fmsg.Fatal("cannot decode init setup payload:", err)
panic("unreachable") panic("unreachable")
} else { } else {
fmsg.SetVerbose(payload.Verbose) fmsg.SetVerbose(payload.Verbose)
closeSetup = f
// child does not need to see this // child does not need to see this
if err = os.Unsetenv(init0.Env); err != nil { if err = os.Unsetenv(init0.Env); err != nil {
@ -98,7 +91,7 @@ func main() {
fmsg.Suspend() fmsg.Suspend()
// close setup pipe as setup is now complete // 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) fmsg.Println("cannot close setup pipe:", err)
// not fatal // not fatal
} }

View File

@ -1,11 +1,7 @@
package shim0 package shim0
import ( import (
"encoding/gob"
"net"
"git.ophivana.moe/security/fortify/helper/bwrap" "git.ophivana.moe/security/fortify/helper/bwrap"
"git.ophivana.moe/security/fortify/internal/fmsg"
) )
const Env = "FORTIFY_SHIM" const Env = "FORTIFY_SHIM"
@ -23,13 +19,3 @@ type Payload struct {
// verbosity pass through // verbosity pass through
Verbose bool 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:")
}

View File

@ -1,18 +1,16 @@
package shim package shim
import ( import (
"encoding/gob"
"errors" "errors"
"net"
"os" "os"
"os/exec" "os/exec"
"os/signal" "os/signal"
"strconv"
"strings" "strings"
"sync"
"sync/atomic"
"syscall" "syscall"
"time" "time"
"git.ophivana.moe/security/fortify/acl"
shim0 "git.ophivana.moe/security/fortify/cmd/fshim/ipc" shim0 "git.ophivana.moe/security/fortify/cmd/fshim/ipc"
"git.ophivana.moe/security/fortify/internal" "git.ophivana.moe/security/fortify/internal"
"git.ophivana.moe/security/fortify/internal/fmsg" "git.ophivana.moe/security/fortify/internal/fmsg"
@ -32,20 +30,14 @@ type Shim struct {
aid string aid string
// string representation of supplementary group ids // string representation of supplementary group ids
supp []string 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 // fallback exit notifier with error returned killing the process
killFallback chan error killFallback chan error
// shim setup payload // shim setup payload
payload *shim0.Payload payload *shim0.Payload
} }
func New(uid uint32, aid string, supp []string, socket string, payload *shim0.Payload) *Shim { func New(uid uint32, aid string, supp []string, payload *shim0.Payload) *Shim {
return &Shim{uid: uid, aid: aid, supp: supp, socket: socket, payload: payload} return &Shim{uid: uid, aid: aid, supp: supp, payload: payload}
} }
func (s *Shim) String() string { func (s *Shim) String() string {
@ -59,39 +51,11 @@ func (s *Shim) Unwrap() *exec.Cmd {
return s.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 { func (s *Shim) WaitFallback() chan error {
return s.killFallback return s.killFallback
} }
func (s *Shim) Start() (*time.Time, error) { 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 // start user switcher process and save time
var fsu string var fsu string
if p, ok := internal.Check(internal.Fsu); !ok { if p, ok := internal.Check(internal.Fsu); !ok {
@ -101,10 +65,19 @@ func (s *Shim) Start() (*time.Time, error) {
fsu = p fsu = p
} }
s.cmd = exec.Command(fsu) s.cmd = exec.Command(fsu)
s.cmd.Env = []string{
shim0.Env + "=" + s.socket, var encoder *gob.Encoder
"FORTIFY_APP_ID=" + s.aid, 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 { if len(s.supp) > 0 {
fmsg.VPrintf("attaching supplementary group ids %s", s.supp) fmsg.VPrintf("attaching supplementary group ids %s", s.supp)
s.cmd.Env = append(s.cmd.Env, "FORTIFY_GROUPS="+strings.Join(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) signal.Ignore(syscall.SIGINT, syscall.SIGTERM)
}() }()
accept() shimErr := make(chan error)
var conn *net.UnixConn go func() { shimErr <- encoder.Encode(s.payload) }()
select { select {
case c := <-cf: case err := <-shimErr:
if c == nil { if err != nil {
return &startTime, fmsg.WrapErrorSuffix(*s.abortErr.Load(), "cannot accept call on setup socket:") return &startTime, fmsg.WrapErrorSuffix(err,
} else { "cannot transmit shim config:")
conn = c
} }
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() {} 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 return &startTime, nil
}
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
} }

View File

@ -1,8 +1,7 @@
package main package main
import ( import (
"encoding/gob" "errors"
"net"
"os" "os"
"path" "path"
"strconv" "strconv"
@ -13,6 +12,7 @@ import (
"git.ophivana.moe/security/fortify/helper" "git.ophivana.moe/security/fortify/helper"
"git.ophivana.moe/security/fortify/internal" "git.ophivana.moe/security/fortify/internal"
"git.ophivana.moe/security/fortify/internal/fmsg" "git.ophivana.moe/security/fortify/internal/fmsg"
"git.ophivana.moe/security/fortify/internal/proc"
) )
// everything beyond this point runs as unconstrained target user // 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 // check path to finit
var finitPath string var finitPath string
if p, ok := internal.Path(internal.Finit); !ok { if p, ok := internal.Path(internal.Finit); !ok {
@ -54,21 +45,24 @@ func main() {
finitPath = p finitPath = p
} }
// dial setup socket // receive setup payload
var conn *net.UnixConn var (
if c, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: socketPath, Net: "unix"}); err != nil { payload shim.Payload
fmsg.Fatal(err.Error()) 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") 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 { } else {
fmsg.SetVerbose(payload.Verbose) fmsg.SetVerbose(payload.Verbose)
closeSetup = f
} }
if payload.Bwrap == nil { if payload.Bwrap == nil {
@ -81,8 +75,8 @@ func main() {
} }
// close setup socket // close setup socket
if err := conn.Close(); err != nil { if err := closeSetup(); err != nil {
fmsg.Println("cannot close setup socket:", err) fmsg.Println("cannot close setup pipe:", err)
// not fatal // not fatal
} }
@ -110,17 +104,14 @@ func main() {
var extraFiles []*os.File var extraFiles []*os.File
// share config pipe // serve setup payload
if r, w, err := os.Pipe(); err != nil { if fd, encoder, err := proc.Setup(&extraFiles); err != nil {
fmsg.Fatalf("cannot pipe: %v", err) fmsg.Fatalf("cannot pipe: %v", err)
} else { } else {
conf.SetEnv[init0.Env] = strconv.Itoa(3 + len(extraFiles)) conf.SetEnv[init0.Env] = strconv.Itoa(fd)
extraFiles = append(extraFiles, r)
fmsg.VPrintln("transmitting config to init")
go func() { go func() {
// stream config to pipe fmsg.VPrintln("transmitting config to init")
if err = gob.NewEncoder(w).Encode(&ic); err != nil { if err = encoder.Encode(&ic); err != nil {
fmsg.Fatalf("cannot transmit init config: %v", err) fmsg.Fatalf("cannot transmit init config: %v", err)
} }
}() }()

View File

@ -83,17 +83,17 @@ func main() {
uid += aid uid += aid
} }
// pass through setup path to shim // pass through setup fd to shim
var shimSetupPath string var shimSetupFd string
if s, ok := os.LookupEnv(envShim); !ok { if s, ok := os.LookupEnv(envShim); !ok {
// fortify requests target uid // fortify requests target uid
// print resolved uid and exit // print resolved uid and exit
fmt.Print(uid) fmt.Print(uid)
os.Exit(0) os.Exit(0)
} else if !path.IsAbs(s) { } else if len(s) != 1 || s[0] > '9' || s[0] < '3' {
log.Fatal("FORTIFY_SHIM is not absolute") log.Fatal("FORTIFY_SHIM holds an invalid value")
} else { } else {
shimSetupPath = s shimSetupFd = s
} }
// supplementary groups // supplementary groups
@ -142,7 +142,7 @@ func main() {
if _, _, errno := syscall.AllThreadsSyscall(syscall.SYS_PRCTL, PR_SET_NO_NEW_PRIVS, 1, 0); errno != 0 { 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()) 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) log.Fatalf("cannot start shim: %v", err)
} }

View File

@ -74,7 +74,7 @@
touch $out 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; 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 { withPackage = nixpkgsFor.${system}.mkShell {
buildInputs = buildInputs =
with nixpkgsFor.${system}; with nixpkgsFor.${system};

View File

@ -1,4 +1,4 @@
package app package fst
import ( import (
"errors" "errors"

View File

@ -1,4 +1,5 @@
package app // Package fst exports shared fortify types.
package fst
import ( import (
"crypto/rand" "crypto/rand"
@ -11,7 +12,7 @@ func (a *ID) String() string {
return hex.EncodeToString(a[:]) return hex.EncodeToString(a[:])
} }
func newAppID(id *ID) error { func NewAppID(id *ID) error {
_, err := rand.Read(id[:]) _, err := rand.Read(id[:])
return err return err
} }

View File

@ -2,14 +2,16 @@ package app
import ( import (
"sync" "sync"
"sync/atomic"
"git.ophivana.moe/security/fortify/cmd/fshim/ipc/shim" "git.ophivana.moe/security/fortify/cmd/fshim/ipc/shim"
"git.ophivana.moe/security/fortify/fst"
"git.ophivana.moe/security/fortify/internal/linux" "git.ophivana.moe/security/fortify/internal/linux"
) )
type App interface { type App interface {
// ID returns a copy of App's unique ID. // ID returns a copy of App's unique ID.
ID() ID ID() fst.ID
// Start sets up the system and starts the App. // Start sets up the system and starts the App.
Start() error Start() error
// Wait waits for App's process to exit and reverts system setup. // 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 returns error returned by the underlying wait syscall.
WaitErr() error WaitErr() error
Seal(config *Config) error Seal(config *fst.Config) error
String() string String() string
} }
type app struct { type app struct {
// single-use config reference
ct *appCt
// application unique identifier // application unique identifier
id *ID id *fst.ID
// operating system interface // operating system interface
os linux.System os linux.System
// shim process manager // shim process manager
@ -36,7 +41,7 @@ type app struct {
lock sync.RWMutex lock sync.RWMutex
} }
func (a *app) ID() ID { func (a *app) ID() fst.ID {
return *a.id return *a.id
} }
@ -65,7 +70,28 @@ func (a *app) WaitErr() error {
func New(os linux.System) (App, error) { func New(os linux.System) (App, error) {
a := new(app) a := new(app)
a.id = new(ID) a.id = new(fst.ID)
a.os = os 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
} }

View File

@ -3,23 +3,23 @@ package app_test
import ( import (
"git.ophivana.moe/security/fortify/acl" "git.ophivana.moe/security/fortify/acl"
"git.ophivana.moe/security/fortify/dbus" "git.ophivana.moe/security/fortify/dbus"
"git.ophivana.moe/security/fortify/fst"
"git.ophivana.moe/security/fortify/helper/bwrap" "git.ophivana.moe/security/fortify/helper/bwrap"
"git.ophivana.moe/security/fortify/internal/app"
"git.ophivana.moe/security/fortify/internal/system" "git.ophivana.moe/security/fortify/internal/system"
) )
var testCasesNixos = []sealTestCase{ var testCasesNixos = []sealTestCase{
{ {
"nixos chromium direct wayland", new(stubNixOS), "nixos chromium direct wayland", new(stubNixOS),
&app.Config{ &fst.Config{
ID: "org.chromium.Chromium", ID: "org.chromium.Chromium",
Command: []string{"/nix/store/yqivzpzzn7z5x0lq9hmbzygh45d8rhqd-chromium-start"}, Command: []string{"/nix/store/yqivzpzzn7z5x0lq9hmbzygh45d8rhqd-chromium-start"},
Confinement: app.ConfinementConfig{ Confinement: fst.ConfinementConfig{
AppID: 1, Groups: []string{}, Username: "u0_a1", AppID: 1, Groups: []string{}, Username: "u0_a1",
Outer: "/var/lib/persist/module/fortify/0/1", Outer: "/var/lib/persist/module/fortify/0/1",
Sandbox: &app.SandboxConfig{ Sandbox: &fst.SandboxConfig{
UserNS: true, Net: true, MapRealUID: true, DirectWayland: true, Env: nil, 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: "/bin", Must: true}, {Src: "/usr/bin", Must: true},
{Src: "/nix/store", Must: true}, {Src: "/run/current-system", 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: "/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(), Enablements: system.EWayland.Mask() | system.EDBus.Mask() | system.EPulse.Mask(),
}, },
}, },
app.ID{ fst.ID{
0x8e, 0x2c, 0x76, 0xb0, 0x8e, 0x2c, 0x76, 0xb0,
0x66, 0xda, 0xbe, 0x57, 0x66, 0xda, 0xbe, 0x57,
0x4c, 0xf0, 0x73, 0xbd, 0x4c, 0xf0, 0x73, 0xbd,

View File

@ -3,23 +3,23 @@ package app_test
import ( import (
"git.ophivana.moe/security/fortify/acl" "git.ophivana.moe/security/fortify/acl"
"git.ophivana.moe/security/fortify/dbus" "git.ophivana.moe/security/fortify/dbus"
"git.ophivana.moe/security/fortify/fst"
"git.ophivana.moe/security/fortify/helper/bwrap" "git.ophivana.moe/security/fortify/helper/bwrap"
"git.ophivana.moe/security/fortify/internal/app"
"git.ophivana.moe/security/fortify/internal/system" "git.ophivana.moe/security/fortify/internal/system"
) )
var testCasesPd = []sealTestCase{ var testCasesPd = []sealTestCase{
{ {
"nixos permissive defaults no enablements", new(stubNixOS), "nixos permissive defaults no enablements", new(stubNixOS),
&app.Config{ &fst.Config{
Command: make([]string, 0), Command: make([]string, 0),
Confinement: app.ConfinementConfig{ Confinement: fst.ConfinementConfig{
AppID: 0, AppID: 0,
Username: "chronos", Username: "chronos",
Outer: "/home/chronos", Outer: "/home/chronos",
}, },
}, },
app.ID{ fst.ID{
0x4a, 0x45, 0x0b, 0x65, 0x4a, 0x45, 0x0b, 0x65,
0x96, 0xd7, 0xbc, 0x15, 0x96, 0xd7, 0xbc, 0x15,
0xbd, 0x01, 0x78, 0x0e, 0xbd, 0x01, 0x78, 0x0e,
@ -190,10 +190,10 @@ var testCasesPd = []sealTestCase{
}, },
{ {
"nixos permissive defaults chromium", new(stubNixOS), "nixos permissive defaults chromium", new(stubNixOS),
&app.Config{ &fst.Config{
ID: "org.chromium.Chromium", ID: "org.chromium.Chromium",
Command: []string{"/run/current-system/sw/bin/zsh", "-c", "exec chromium "}, Command: []string{"/run/current-system/sw/bin/zsh", "-c", "exec chromium "},
Confinement: app.ConfinementConfig{ Confinement: fst.ConfinementConfig{
AppID: 9, AppID: 9,
Groups: []string{"video"}, Groups: []string{"video"},
Username: "chronos", Username: "chronos",
@ -232,7 +232,7 @@ var testCasesPd = []sealTestCase{
Enablements: system.EWayland.Mask() | system.EDBus.Mask() | system.EPulse.Mask(), Enablements: system.EWayland.Mask() | system.EDBus.Mask() | system.EPulse.Mask(),
}, },
}, },
app.ID{ fst.ID{
0xeb, 0xf0, 0x83, 0xd1, 0xeb, 0xf0, 0x83, 0xd1,
0xb1, 0x75, 0x91, 0x17, 0xb1, 0x75, 0x91, 0x17,
0x82, 0xd4, 0x13, 0x36, 0x82, 0xd4, 0x13, 0x36,

View File

@ -6,6 +6,7 @@ import (
"testing" "testing"
"time" "time"
"git.ophivana.moe/security/fortify/fst"
"git.ophivana.moe/security/fortify/helper/bwrap" "git.ophivana.moe/security/fortify/helper/bwrap"
"git.ophivana.moe/security/fortify/internal/app" "git.ophivana.moe/security/fortify/internal/app"
"git.ophivana.moe/security/fortify/internal/linux" "git.ophivana.moe/security/fortify/internal/linux"
@ -15,8 +16,8 @@ import (
type sealTestCase struct { type sealTestCase struct {
name string name string
os linux.System os linux.System
config *app.Config config *fst.Config
id app.ID id fst.ID
wantSys *system.I wantSys *system.I
wantBwrap *bwrap.Config wantBwrap *bwrap.Config
} }

View File

@ -1,12 +1,13 @@
package app package app
import ( import (
"git.ophivana.moe/security/fortify/fst"
"git.ophivana.moe/security/fortify/helper/bwrap" "git.ophivana.moe/security/fortify/helper/bwrap"
"git.ophivana.moe/security/fortify/internal/linux" "git.ophivana.moe/security/fortify/internal/linux"
"git.ophivana.moe/security/fortify/internal/system" "git.ophivana.moe/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 := new(app)
a.id = &id a.id = &id
a.os = os a.os = os

View File

@ -9,6 +9,7 @@ import (
"strconv" "strconv"
"git.ophivana.moe/security/fortify/dbus" "git.ophivana.moe/security/fortify/dbus"
"git.ophivana.moe/security/fortify/fst"
"git.ophivana.moe/security/fortify/internal/fmsg" "git.ophivana.moe/security/fortify/internal/fmsg"
"git.ophivana.moe/security/fortify/internal/linux" "git.ophivana.moe/security/fortify/internal/linux"
"git.ophivana.moe/security/fortify/internal/state" "git.ophivana.moe/security/fortify/internal/state"
@ -59,7 +60,7 @@ type appSeal struct {
} }
// Seal seals the app launch context // Seal seals the app launch context
func (a *app) Seal(config *Config) error { func (a *app) Seal(config *fst.Config) error {
a.lock.Lock() a.lock.Lock()
defer a.lock.Unlock() defer a.lock.Unlock()
@ -147,7 +148,7 @@ func (a *app) Seal(config *Config) error {
fmsg.VPrintln("sandbox configuration not supplied, PROCEED WITH CAUTION") fmsg.VPrintln("sandbox configuration not supplied, PROCEED WITH CAUTION")
// permissive defaults // permissive defaults
conf := &SandboxConfig{ conf := &fst.SandboxConfig{
UserNS: true, UserNS: true,
Net: true, Net: true,
NoNewSession: true, NoNewSession: true,
@ -157,7 +158,7 @@ func (a *app) Seal(config *Config) error {
if d, err := a.os.ReadDir("/"); err != nil { if d, err := a.os.ReadDir("/"); err != nil {
return err return err
} else { } else {
b := make([]*FilesystemConfig, 0, len(d)) b := make([]*fst.FilesystemConfig, 0, len(d))
for _, ent := range d { for _, ent := range d {
p := "/" + ent.Name() p := "/" + ent.Name()
switch p { switch p {
@ -169,7 +170,7 @@ func (a *app) Seal(config *Config) error {
case "/etc": case "/etc":
default: 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...) 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 { if d, err := a.os.ReadDir("/run"); err != nil {
return err return err
} else { } else {
b := make([]*FilesystemConfig, 0, len(d)) b := make([]*fst.FilesystemConfig, 0, len(d))
for _, ent := range d { for _, ent := range d {
name := ent.Name() name := ent.Name()
switch name { switch name {
@ -186,7 +187,7 @@ func (a *app) Seal(config *Config) error {
case "dbus": case "dbus":
default: default:
p := "/run/" + name 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...) conf.Filesystem = append(conf.Filesystem, b...)
@ -198,7 +199,7 @@ func (a *app) Seal(config *Config) error {
} }
// bind GPU stuff // bind GPU stuff
if config.Confinement.Enablements.Has(system.EX11) || config.Confinement.Enablements.Has(system.EWayland) { 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 config.Confinement.Sandbox = conf
@ -236,5 +237,6 @@ func (a *app) Seal(config *Config) error {
// seal app and release lock // seal app and release lock
a.seal = seal a.seal = seal
a.ct = newAppCt(config)
return nil return nil
} }

View File

@ -4,7 +4,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"os/exec" "os/exec"
"path"
"path/filepath" "path/filepath"
"strings" "strings"
@ -46,7 +45,6 @@ func (a *app) Start() error {
uint32(a.seal.sys.UID()), uint32(a.seal.sys.UID()),
a.seal.sys.user.as, a.seal.sys.user.as,
a.seal.sys.user.supp, a.seal.sys.user.supp,
path.Join(a.seal.share, "shim"),
&shim0.Payload{ &shim0.Payload{
Argv: a.seal.command, Argv: a.seal.command,
Exec: shimExec, Exec: shimExec,
@ -70,11 +68,10 @@ func (a *app) Start() error {
} else { } else {
// shim start and setup success, create process state // shim start and setup success, create process state
sd := state.State{ sd := state.State{
PID: a.shim.Unwrap().Process.Pid, ID: *a.id,
Command: a.seal.command, PID: a.shim.Unwrap().Process.Pid,
Capability: a.seal.et, Config: a.ct.Unwrap(),
Argv: a.shim.Unwrap().Args, Time: *startTime,
Time: *startTime,
} }
// register process state // register process state
@ -227,8 +224,12 @@ func (a *app) Wait() (int, error) {
} }
// accumulate capabilities of other launchers // accumulate capabilities of other launchers
for _, s := range states { for i, s := range states {
*rt |= s.Capability 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 // 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 a.seal.sys.needRevert {
if err := a.seal.sys.Revert(ec); err != nil { if err := a.seal.sys.Revert(ec); err != nil {
return err.(RevertCompoundError) return err.(RevertCompoundError)

42
internal/proc/fd.go Normal file
View 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)
}

View File

@ -82,27 +82,41 @@ func (s *simpleStore) mustPrintLauncherState(w **tabwriter.Writer, now time.Time
continue continue
} }
// build enablements string // build enablements and command string
ets := strings.Builder{} var (
// append enablement strings in order ets *strings.Builder
for i := system.Enablement(0); i < system.Enablement(system.ELen); i++ { cs = "(No command information)"
if state.Capability.Has(i) { )
ets.WriteString(", " + i.String())
// 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 != nil {
if ets.Len() == 0 { // prevent an empty string
ets.WriteString("(No enablements)") if ets.Len() == 0 {
ets.WriteString("(No enablements)")
}
} else {
ets = new(strings.Builder)
ets.WriteString("(No confinement information)")
} }
if !fmsg.Verbose() { if !fmsg.Verbose() {
_, _ = fmt.Fprintf(*w, "\t%d\t%s\t%s\t%s\t%s\n", _, _ = 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.PID, s.path[len(s.path)-1], now.Sub(state.Time).Round(time.Second).String(), strings.TrimPrefix(ets.String(), ", "), cs)
state.Command)
} else { } else {
// emit argv instead when verbose // emit argv instead when verbose
_, _ = fmt.Fprintf(*w, "\t%d\t%s\t%s\n", _, _ = fmt.Fprintf(*w, "\t%d\t%s\t%s\n",
state.PID, s.path[len(s.path)-1], state.Argv) state.PID, s.path[len(s.path)-1], state.ID)
} }
} }

View File

@ -176,6 +176,10 @@ func (b *simpleBackend) Save(state *State) error {
b.lock.Lock() b.lock.Lock()
defer b.lock.Unlock() defer b.lock.Unlock()
if state.Config == nil {
return errors.New("state does not contain config")
}
statePath := b.filename(state.PID) statePath := b.filename(state.PID)
// create and open state data file // create and open state data file

View File

@ -3,7 +3,7 @@ package state
import ( import (
"time" "time"
"git.ophivana.moe/security/fortify/internal/system" "git.ophivana.moe/security/fortify/fst"
) )
type Store interface { type Store interface {
@ -26,15 +26,13 @@ type Backend interface {
// State is the on-disk format for a fortified process's state information // State is the on-disk format for a fortified process's state information
type State struct { type State struct {
// fortify instance id
ID fst.ID `json:"instance"`
// child process PID value // child process PID value
PID int PID int `json:"pid"`
// command used to seal the app // sealed app configuration
Command []string Config *fst.Config `json:"config"`
// capability enablements applied to child
Capability system.Enablements
// full argv whe launching
Argv []string
// process start time // process start time
Time time.Time Time time.Time
} }

View File

@ -12,6 +12,7 @@ import (
"text/tabwriter" "text/tabwriter"
"git.ophivana.moe/security/fortify/dbus" "git.ophivana.moe/security/fortify/dbus"
"git.ophivana.moe/security/fortify/fst"
"git.ophivana.moe/security/fortify/internal" "git.ophivana.moe/security/fortify/internal"
"git.ophivana.moe/security/fortify/internal/app" "git.ophivana.moe/security/fortify/internal/app"
"git.ophivana.moe/security/fortify/internal/fmsg" "git.ophivana.moe/security/fortify/internal/fmsg"
@ -102,7 +103,7 @@ func main() {
fmt.Println(license) fmt.Println(license)
fmsg.Exit(0) fmsg.Exit(0)
case "template": // print full template configuration 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) fmsg.Fatalf("cannot generate template: %v", err)
panic("unreachable") panic("unreachable")
} else { } else {
@ -129,7 +130,7 @@ func main() {
fmsg.Fatal("app requires at least 1 argument") 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 { if f, err := os.Open(args[1]); err != nil {
fmsg.Fatalf("cannot access config file %q: %s", args[1], err) fmsg.Fatalf("cannot access config file %q: %s", args[1], err)
panic("unreachable") panic("unreachable")
@ -179,7 +180,7 @@ func main() {
_ = set.Parse(args[1:]) _ = set.Parse(args[1:])
// initialise config from flags // initialise config from flags
config := &app.Config{ config := &fst.Config{
ID: fid, ID: fid,
Command: set.Args(), Command: set.Args(),
} }
@ -275,7 +276,7 @@ func main() {
panic("unreachable") panic("unreachable")
} }
func runApp(config *app.Config) { func runApp(config *fst.Config) {
if os.SdBooted() { if os.SdBooted() {
fmsg.VPrintln("system booted with systemd as init system") fmsg.VPrintln("system booted with systemd as init system")
} }

View File

@ -36,7 +36,7 @@ package
*Default:* *Default:*
` <derivation fortify-0.2.1> ` ` <derivation fortify-0.2.4> `

View File

@ -14,7 +14,7 @@
buildGoModule rec { buildGoModule rec {
pname = "fortify"; pname = "fortify";
version = "0.2.3"; version = "0.2.4";
src = ./.; src = ./.;
vendorHash = null; vendorHash = null;

View File

@ -1,4 +1,5 @@
{ {
system,
self, self,
home-manager, home-manager,
nixosTest, nixosTest,
@ -31,11 +32,14 @@ nixosTest {
services.getty.autologinUser = "alice"; services.getty.autologinUser = "alice";
environment = { environment = {
# For glinfo and wayland-info:
systemPackages = with pkgs; [ systemPackages = with pkgs; [
# For glinfo and wayland-info:
mesa-demos mesa-demos
wayland-utils wayland-utils
alacritty alacritty
# For go tests:
self.devShells.${system}.fhs
]; ];
variables = { variables = {
@ -73,8 +77,13 @@ nixosTest {
programs.sway.enable = true; 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 = [
virtualisation.qemu.options = [ "-vga none -device virtio-gpu-pci" ]; # 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 = { environment.fortify = {
enable = true; enable = true;
@ -136,10 +145,19 @@ nixosTest {
retry(func) 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() start_all()
machine.wait_for_unit("multi-user.target") 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")) print(machine.succeed("sway --version"))
# Wait for Sway to complete startup: # Wait for Sway to complete startup:
@ -164,9 +182,13 @@ nixosTest {
wait_for_window("u0_a0@machine") wait_for_window("u0_a0@machine")
machine.send_chars("wayland-info && touch /tmp/success-client\n") machine.send_chars("wayland-info && touch /tmp/success-client\n")
machine.wait_for_file("/tmp/fortify.1000/tmpdir/0/success-client") 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.send_chars("exit\n")
machine.wait_until_fails("pgrep foot") 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: # Start a terminal (foot) within fortify from a terminal on workspace 4:
machine.send_key("alt-4") machine.send_key("alt-4")
@ -175,7 +197,7 @@ nixosTest {
wait_for_window("u0_a0@machine") wait_for_window("u0_a0@machine")
machine.send_chars("wayland-info && touch /tmp/success-client-term\n") machine.send_chars("wayland-info && touch /tmp/success-client-term\n")
machine.wait_for_file("/tmp/fortify.1000/tmpdir/0/success-client-term") 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.send_chars("exit\n")
machine.wait_until_fails("pgrep foot") machine.wait_until_fails("pgrep foot")
@ -184,8 +206,9 @@ nixosTest {
wait_for_window("u0_a0@machine") wait_for_window("u0_a0@machine")
machine.send_chars("glinfo && touch /tmp/success-client-x11\n") machine.send_chars("glinfo && touch /tmp/success-client-x11\n")
machine.wait_for_file("/tmp/fortify.1000/tmpdir/0/success-client-x11") machine.wait_for_file("/tmp/fortify.1000/tmpdir/0/success-client-x11")
machine.screenshot("alacritty_x11_permissive") collect_state_ui("alacritty_x11_permissive")
machine.succeed("pkill alacritty") machine.send_chars("exit\n")
machine.wait_until_fails("pgrep alacritty")
# Exit Sway and verify process exit status 0: # Exit Sway and verify process exit status 0:
swaymsg("exit", succeed=False) swaymsg("exit", succeed=False)